From f0a62d0e38fe499a9807f4a1987fb900ea001bd5 Mon Sep 17 00:00:00 2001 From: Tim Date: Wed, 25 Nov 2026 11:03:50 -0700 Subject: [PATCH] feat(decode): 12-bit DCT, arithmetic coding and two-component lossless SOF1/SOF2 at 12 bits, SOF9/SOF10 with DAC at 8 and 12 bits, and the two-component SOF3 layout of DNG CFA tiles. 12-bit and lossless output matches libjpeg-turbo 3.1.0 exactly; arithmetic files decode to what their Huffman twins do. Also stores the planes of a lossless image with one scan per component where they belong. Refs #28 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 3 + CHANGES.md | 33 + README.md | 6 +- fuzz/Cargo.toml | 7 + fuzz/fuzz_targets/decode_modes.rs | 81 +++ src/decode/arith.rs | 565 ++++++++++++++++++ src/decode/decoder.rs | 378 +++++++++--- src/decode/decoder/arithmetic.rs | 158 +++++ src/decode/decoder/lossless.rs | 35 +- src/decode/decoder/smoothing.rs | 6 +- src/decode/decoder/twelve.rs | 379 ++++++++++++ src/decode/error.rs | 15 +- src/decode/mod.rs | 5 +- src/decode/parser.rs | 84 ++- tests/damaged_streams.rs | 7 +- tests/extended_modes.rs | 387 ++++++++++++ .../fixtures/modes/lossless12_pair_scans.jpg | Bin 0 -> 1188 bytes tests/fixtures/modes/lossless14_pair.jpg | Bin 0 -> 1339 bytes .../fixtures/modes/prog12_420_arithmetic.jpg | Bin 0 -> 2044 bytes tests/fixtures/modes/prog12_422_huffman.jpg | Bin 0 -> 2467 bytes tests/fixtures/modes/prog8_422_arithmetic.jpg | Bin 0 -> 1182 bytes tests/fixtures/modes/prog8_422_huffman.jpg | Bin 0 -> 1385 bytes tests/fixtures/modes/seq12_420_huffman.jpg | Bin 0 -> 1867 bytes tests/fixtures/modes/seq12_440_separate.jpg | Bin 0 -> 2458 bytes .../fixtures/modes/seq12_grey_arithmetic.jpg | Bin 0 -> 1410 bytes tests/fixtures/modes/seq12_ycck.jpg | Bin 0 -> 1477 bytes tests/fixtures/modes/seq8_420_arithmetic.jpg | Bin 0 -> 943 bytes tests/fixtures/modes/seq8_420_huffman.jpg | Bin 0 -> 1022 bytes tools/generate_modes_libjpeg.c | 184 ++++++ 29 files changed, 2231 insertions(+), 102 deletions(-) create mode 100644 fuzz/fuzz_targets/decode_modes.rs create mode 100644 src/decode/arith.rs create mode 100644 src/decode/decoder/arithmetic.rs create mode 100644 src/decode/decoder/twelve.rs create mode 100644 tests/extended_modes.rs create mode 100644 tests/fixtures/modes/lossless12_pair_scans.jpg create mode 100644 tests/fixtures/modes/lossless14_pair.jpg create mode 100644 tests/fixtures/modes/prog12_420_arithmetic.jpg create mode 100644 tests/fixtures/modes/prog12_422_huffman.jpg create mode 100644 tests/fixtures/modes/prog8_422_arithmetic.jpg create mode 100644 tests/fixtures/modes/prog8_422_huffman.jpg create mode 100644 tests/fixtures/modes/seq12_420_huffman.jpg create mode 100644 tests/fixtures/modes/seq12_440_separate.jpg create mode 100644 tests/fixtures/modes/seq12_grey_arithmetic.jpg create mode 100644 tests/fixtures/modes/seq12_ycck.jpg create mode 100644 tests/fixtures/modes/seq8_420_arithmetic.jpg create mode 100644 tests/fixtures/modes/seq8_420_huffman.jpg create mode 100644 tools/generate_modes_libjpeg.c diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2a0a51a..6faf0ad 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -98,6 +98,9 @@ jobs: - name: decode_planar run: cargo fuzz run decode_planar -- -max_total_time=60 -rss_limit_mb=4096 working-directory: fuzz + - name: decode_modes + run: cargo fuzz run decode_modes -- -max_total_time=60 -rss_limit_mb=4096 + working-directory: fuzz - name: roundtrip run: cargo fuzz run roundtrip -- -max_total_time=60 -rss_limit_mb=4096 working-directory: fuzz diff --git a/CHANGES.md b/CHANGES.md index d688098..d048c63 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -6,6 +6,39 @@ upstream possible. ## Unreleased +- **12-bit, arithmetic-coded and two-component lossless JPEGs decode** (#28). + Oracle for all of it: libjpeg-turbo 3.1.0. Fixtures it wrote, and the hashes + of what it decodes them to, are in `tests/extended_modes.rs` + (`tools/generate_modes_libjpeg.c`). + - **12-bit DCT** (SOF1 and SOF2; a 12-bit SOF0 stays an error, as B.2.2 + says). `decode` returns two bytes per sample in native byte order, as it + does for lossless images of more than 8 bits; samples are unscaled, + `0..=4095`. IDCT, upsampling and colour conversion are libjpeg-turbo's + 12-bit arithmetic and match it sample for sample (`decoder/twelve.rs`, + scalar). The whole frame's coefficients are kept and rendered at the end. + `decode_planar` refuses these frames (`SamplePrecision(12)`). + - **Arithmetic coding**, SOF9 and SOF10 at 8 and 12 bits, and DAC: a port of + `jdarith.c` (`decode/arith.rs`). As there, running into a marker early is + legal and reads as zero bytes, and a coefficient that overflows its band + or 15 bits stops the segment: new `Warning::BadArithmeticCode`. SOF11 + (lossless) stays `Unsupported(ArithmeticEntropyCoding)`. A DAC in a Huffman + file is checked and ignored; it was refused. + - **Two-component lossless** (SOF3), the layout DNG codes CFA tiles in: + interleaved samples. Full-size components only; every other process still + refuses two. + - **API:** `Decoder::decode_u16`, `Decoder::frame_header` -> `FrameHeader` + (dimensions, components, precision, coding process, arithmetic or not, + `bytes_per_sample`), `Warning::BadArithmeticCode`. `Decoder::info` is + `None` for two components, which no `PixelFormat` describes. + - **Lossless images with one scan per component decoded wrongly**, even when + intact: each scan's plane was stored by its position in the scan, so all + of them landed on component 0. They match libjpeg-turbo now. + - `set_max_decoding_buffer_size` counts a 12-bit sample as two bytes, and + also bounds the stored coefficients of 12-bit and arithmetic frames. + - Known limit, unchanged and shared with 8-bit: in a sequential scan a + damaged AC table's symbol `r0` (`1 <= r <= 14`) is read as a progressive + end-of-band run; libjpeg-turbo reads it as end of block. + - **Four encoder defects, found by new property tests and Kani proofs.** `tests/properties.rs` and in-crate proptests check the encode -> decode round trip and Huffman table construction against real oracles; Kani diff --git a/README.md b/README.md index 8164a90..00b8e0b 100644 --- a/README.md +++ b/README.md @@ -78,8 +78,10 @@ campaign's harness runs under [rusty_alloc](https://github.com/Remade-With-Rust/rusty_alloc), the pure-Rust remake of mimalloc that our binaries ship with. -**Not covered yet:** 12-bit DCT files and arithmetic-coded files are refused -with `Error::Unsupported`. libjpeg-turbo opens both. +**Not in this table:** 12-bit DCT files and arithmetic-coded files, which +`Decoder` reads ([#28](https://github.com/Remade-With-Rust/rusty_jpeg/issues/28)) +but with scalar code. Lossless arithmetic coding (SOF11) is refused with +`Error::Unsupported`; libjpeg-turbo does not read it either. ### Against FFmpeg (measured at 0.3.0) diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 0ecf87c..74e14cf 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -41,3 +41,10 @@ path = "fuzz_targets/roundtrip.rs" test = false doc = false bench = false + +[[bin]] +name = "decode_modes" +path = "fuzz_targets/decode_modes.rs" +test = false +doc = false +bench = false diff --git a/fuzz/fuzz_targets/decode_modes.rs b/fuzz/fuzz_targets/decode_modes.rs new file mode 100644 index 0000000..98459a2 --- /dev/null +++ b/fuzz/fuzz_targets/decode_modes.rs @@ -0,0 +1,81 @@ +#![no_main] +//! 12-bit, arithmetic-coded and two-component lossless frames. +//! +//! Arbitrary bytes rarely get past the headers of these, so this target writes +//! valid headers for a mode picked by the input and hands the rest of it over +//! as everything that follows the frame header: scan data, and whatever +//! segments the fuzzer finds its way to. +use libfuzzer_sys::fuzz_target; +use rusty_jpeg::decode::Decoder; + +fn segment(out: &mut Vec, marker: u8, body: &[u8]) { + out.extend_from_slice(&[0xFF, marker]); + out.extend_from_slice(&(body.len() as u16 + 2).to_be_bytes()); + out.extend_from_slice(body); +} + +fuzz_target!(|data: &[u8]| { + if data.len() < 8 { + return; + } + let (head, rest) = data.split_at(8); + let sof = [0xC1, 0xC2, 0xC3, 0xC9, 0xCA][usize::from(head[0] % 5)]; + let lossless = sof == 0xC3; + let precision = match (lossless, head[1] % 2) { + (true, _) => 2 + head[1] % 15, + (false, 0) => 8, + (false, _) => 12, + }; + let components = match (lossless, head[2] % 4) { + (true, n) => n + 1, + (false, 0) => 1, + (false, 1) => 4, + (false, _) => 3, + }; + let mut jpeg = vec![0xFF, 0xD8]; + let mut dqt = vec![0]; + dqt.extend((0..64).map(|i| head[3].wrapping_add(i))); + segment(&mut jpeg, 0xDB, &dqt); + let mut frame = vec![precision, 0, head[4] % 64 + 1, 0, head[5] % 64 + 1, components]; + for c in 0..components { + let factors = match (lossless, c) { + (false, 0) => [0x11, 0x21, 0x12, 0x22, 0x41][usize::from(head[6] % 5)], + _ => 0x11, + }; + frame.extend_from_slice(&[c + 1, factors, 0]); + } + segment(&mut jpeg, sof, &frame); + // One table of each class: codes of 1 to 16 bits, all categories. + for class in [0x00, 0x10] { + let mut dht = vec![class, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; + dht.extend((0..15).map(|i| if class == 0 { i } else { i * 17 + head[7] % 16 })); + segment(&mut jpeg, 0xC4, &dht); + } + segment(&mut jpeg, 0xDD, &[0, head[7] % 5]); + // A first scan, so that plain scan data is enough; progressive ones follow + // from the input. + let mut scan = vec![components]; + for c in 0..components { + scan.extend_from_slice(&[c + 1, 0]); + } + scan.extend_from_slice(&match sof { + 0xC3 => [head[7] % 8, 0, 0], + 0xC2 | 0xCA => [0, 0, 0], + _ => [0, 63, 0], + }); + segment(&mut jpeg, 0xDA, &scan); + jpeg.extend_from_slice(rest); + + let mut d = Decoder::new(&jpeg[..]); + d.set_max_decoding_buffer_size(64 * 1024 * 1024); + d.set_single_threaded(true); + d.set_strict(head[3] & 0x40 != 0); + if let Ok(samples) = d.decode_u16() { + let h = d.frame_header().unwrap(); + assert_eq!( + samples.len(), + usize::from(h.width) * usize::from(h.height) * usize::from(h.components) + ); + assert!(h.precision == 16 || lossless || samples.iter().all(|&s| s >> h.precision == 0)); + } +}); diff --git a/src/decode/arith.rs b/src/decode/arith.rs new file mode 100644 index 0000000..4907a4c --- /dev/null +++ b/src/decode/arith.rs @@ -0,0 +1,565 @@ +//! Arithmetic entropy decoding: the QM-coder of T.81 Annex D and the DCT +//! coefficient models of Annexes F and G. +//! +//! A port of libjpeg-turbo's `jdarith.c` / `jaricom.c` (with their "floating +//! cut-point" arrangement of the C register), down to what it does with corrupt +//! data, so that a damaged stream decodes to what `djpeg` shows. +//! +//! No Huffman code is involved, but `HuffmanDecoder` also holds the state of a +//! scan's data source -- the marker it ran into, whether the data ended -- and +//! the restart resynchronisation works on that, so one is embedded for it. + +use crate::decode::decoder::{process_restart, UNZIGZAG}; +use crate::decode::error::{Error, Result, Warnings}; +use crate::decode::huffman::HuffmanDecoder; +use crate::decode::marker::Marker; +use crate::decode::{Buffered, Source}; +use core::ops::Range; + +/// Conditioning table destinations (B.2.4.3, `Tb`). +pub(crate) const TABLES: usize = 16; + +/// The conditioning parameters a DAC segment sets (B.2.4.3), with the defaults +/// that apply until one does (F.1.4.4.1.4 and F.1.4.4.2.1). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Conditioning { + /// Bounds `(L, U)` of the "small difference" DC category. + pub(crate) dc: [(u8, u8); TABLES], + /// `Kx`: the last zigzag position of the low-frequency AC category. + pub(crate) ac: [u8; TABLES], +} + +impl Default for Conditioning { + fn default() -> Self { + Conditioning { + dc: [(0, 1); TABLES], + ac: [5; TABLES], + } + } +} + +/// Statistics bins per DC and per AC table: 49 and 245 (Tables F.4 and F.5), +/// rounded up as libjpeg does. +const DC_BINS: usize = 64; +const AC_BINS: usize = 256; + +/// First of the DC magnitude-category bins, Table F.4 (`X1`). +const DC_X1: usize = 20; +/// First of the AC magnitude-category bins for low and high frequencies, +/// Table F.5 (`X2`). +const AC_X2_LOW: usize = 189; +const AC_X2_HIGH: usize = 217; +/// From a magnitude-category bin to the bin of its bit pattern. +const M_OFFSET: usize = 14; + +/// The state of the "fixed probability 0.5" bin, whose estimate never moves. +const FIXED: u8 = 113; + +/// The decoding registers. +pub(crate) struct ArithDecoder { + c: u32, + a: u32, + /// Bits of `c` below the cut point; negative while the first bytes of a + /// segment are still to come. + ct: i32, + /// The segment's data has ended at a marker. Unlike in a Huffman segment + /// that is legal before the last MCU (D.1.8: trailing zero bytes are not + /// sent), and the decoder supplies zero bytes from there on. + ended: bool, + /// A coefficient ran past the end of its band or its magnitude past 15 + /// bits. Nothing more is decoded before the next restart marker. + bad: bool, + /// A `bad` was met at any time in the scan. + saw_bad_code: bool, + source: HuffmanDecoder, +} + +impl ArithDecoder { + pub(crate) fn new(strict: bool) -> ArithDecoder { + ArithDecoder { + c: 0, + a: 0, + ct: -16, + ended: false, + bad: false, + saw_bad_code: false, + source: HuffmanDecoder::new(strict), + } + } + + /// Nothing more to decode in this segment (libjpeg's `ct == -1`). + pub(crate) fn failed(&self) -> bool { + self.bad + } + + pub(crate) fn saw_bad_code(&self) -> bool { + self.saw_bad_code + } + + /// The marker and end-of-data state of the scan. + pub(crate) fn source(&mut self) -> &mut HuffmanDecoder { + &mut self.source + } + + /// Cross a restart marker (see `process_restart`) and start the next + /// segment. The caller resets the statistics and the DC predictions. + pub(crate) fn restart( + &mut self, + reader: &mut Buffered, + expected: u8, + warnings: &mut Warnings, + ) -> Result<()> { + let consumed = process_restart(reader, &mut self.source, expected, warnings)?; + self.c = 0; + self.a = 0; + self.ct = -16; + // A marker left unread means the coming segment is empty. + self.ended = !consumed; + self.bad = false; + Ok(()) + } + + #[cold] + fn fail(&mut self) { + self.bad = true; + self.saw_bad_code = true; + } + + /// The next byte of the segment, zero once it has ended. + #[inline] + fn byte(&mut self, reader: &mut Buffered) -> Result { + if self.ended { + return Ok(0); + } + match reader.next_byte() { + Ok(0xFF) => self.byte_after_ff(reader), + Ok(byte) => Ok(byte), + Err(error) => self.end_of_data(error), + } + } + + #[cold] + fn byte_after_ff(&mut self, reader: &mut Buffered) -> Result { + loop { + match reader.next_byte() { + // Fill bytes. + Ok(0xFF) => {} + // Byte stuffing. + Ok(0) => return Ok(0xFF), + Ok(code) => { + self.ended = true; + self.source + .set_pending_marker(Marker::from_u8(code).unwrap_or(Marker::EOI)); + return Ok(0); + } + Err(error) => return self.end_of_data(error), + } + } + } + + #[cold] + fn end_of_data(&mut self, error: Error) -> Result { + self.source.end_of_data(error)?; + self.ended = true; + Ok(0) + } + + /// One binary decision with the estimate in `state` (Figure D.16, with the + /// renormalisation of D.2.6 done before the decision that needs it). + #[inline] + fn decode(&mut self, reader: &mut Buffered, state: &mut u8) -> Result { + if self.a < 0x8000 { + self.renormalise(reader)?; + } + + let mut sv = *state; + let (qe, lps, mps) = QE[usize::from(sv & 0x7F)]; + let qe = u32::from(qe); + + // `0x8000 <= a <= 0x10000`, `qe < 0x8000` and `0 <= ct <= 7`. + self.a -= qe; + let split = self.a << self.ct; + if self.c >= split { + self.c -= split; + // Conditional LPS exchange. + if self.a < qe { + *state = (sv & 0x80) ^ mps; + } else { + *state = (sv & 0x80) ^ lps; + sv ^= 0x80; + } + self.a = qe; + } else if self.a < 0x8000 { + // Conditional MPS exchange. + if self.a < qe { + *state = (sv & 0x80) ^ lps; + sv ^= 0x80; + } else { + *state = (sv & 0x80) ^ mps; + } + } + Ok(sv & 0x80 != 0) + } + + #[inline] + fn renormalise(&mut self, reader: &mut Buffered) -> Result<()> { + while self.a < 0x8000 { + self.ct -= 1; + if self.ct < 0 { + let byte = self.byte(reader)?; + // `c < a << ct` once the first two bytes are in, so this stays + // within 25 bits. + self.c = (self.c << 8) | u32::from(byte); + self.ct += 8; + if self.ct < 0 { + self.ct += 1; + if self.ct == 0 { + // Both initial bytes are in: `a` becomes 0x10000. + self.a = 0x8000; + } + } + } + self.a <<= 1; + } + Ok(()) + } + + /// Figure F.24: the bits of a magnitude below its leading one, `m`, and + /// from them the value, `v + 1` with its sign. + #[inline] + fn magnitude( + &mut self, + reader: &mut Buffered, + bin: &mut u8, + mut m: i32, + negative: bool, + ) -> Result { + let mut v = m; + loop { + m >>= 1; + if m == 0 { + break; + } + if self.decode(reader, bin)? { + v |= m; + } + } + v += 1; + Ok(if negative { -v } else { v }) + } + + /// A value's magnitude category beyond its first steps (Figure F.23): `m` + /// doubles for every 1 decoded, each in the next bin from `at`. `false` + /// when it overflows; `m` stays below `0x8000`, so `at` moves at most 14 + /// bins. + #[inline] + fn category( + &mut self, + reader: &mut Buffered, + bins: &mut [u8], + at: &mut usize, + m: &mut i32, + ) -> Result { + while self.decode(reader, &mut bins[*at])? { + *m <<= 1; + if *m == 0x8000 { + self.fail(); + return Ok(false); + } + *at += 1; + } + Ok(true) + } +} + +/// The statistics of one scan's tables. +pub(crate) struct Stats { + dc: [[u8; DC_BINS]; TABLES], + ac: [[u8; AC_BINS]; TABLES], +} + +impl Stats { + pub(crate) fn new() -> Stats { + Stats { + dc: [[0; DC_BINS]; TABLES], + ac: [[0; AC_BINS]; TABLES], + } + } + + /// Forget what a DC and an AC table have learned. + pub(crate) fn reset(&mut self, dc_table: usize, ac_table: usize) { + self.dc[dc_table] = [0; DC_BINS]; + self.ac[ac_table] = [0; AC_BINS]; + } +} + +/// One component's DC prediction and conditioning state. +#[derive(Clone, Copy, Default)] +pub(crate) struct DcState { + prediction: i32, + /// First bin of the context the previous difference selects (Table F.4). + context: usize, +} + +/// Sections F.2.4.1 and F.1.4.4.1: the DC value of a block. `None` when the +/// magnitude of the difference overflowed. +pub(crate) fn decode_dc( + d: &mut ArithDecoder, + reader: &mut Buffered, + stats: &mut Stats, + table: usize, + (low, high): (u8, u8), + dc: &mut DcState, +) -> Result> { + let bins = &mut stats.dc[table]; + let mut at = dc.context; + if !d.decode(reader, &mut bins[at])? { + dc.context = 0; + return Ok(Some(dc.prediction)); + } + let negative = d.decode(reader, &mut bins[at + 1])?; + let sign = usize::from(negative); + at += 2 + sign; + let mut m = i32::from(d.decode(reader, &mut bins[at])?); + if m != 0 { + at = DC_X1; + if !d.category(reader, bins, &mut at, &mut m)? { + return Ok(None); + } + } + // F.1.4.4.1.2. `low` and `high` are nibbles. + dc.context = if m < (1i32 << low) >> 1 { + 0 + } else if m > (1i32 << high) >> 1 { + 12 + sign * 4 + } else { + 4 + sign * 4 + }; + let diff = d.magnitude(reader, &mut bins[at + M_OFFSET], m, negative)?; + dc.prediction = (dc.prediction + diff) & 0xFFFF; + Ok(Some(dc.prediction)) +} + +/// Section F.2.4.2: the AC coefficients of a block in `band` (zigzag +/// positions, `1 <= start`, `end <= 64`), scaled by `2^al`; also the first +/// pass of a progressive band. `nonzero` is kept as `Decoder::nonzero` says. +#[allow(clippy::too_many_arguments)] +pub(crate) fn decode_ac( + d: &mut ArithDecoder, + reader: &mut Buffered, + stats: &mut Stats, + table: usize, + kx: u8, + band: Range, + al: u8, + coefficients: &mut [i16; 64], + nonzero: &mut u64, +) -> Result<()> { + let bins = &mut stats.ac[table]; + let end = usize::from(band.end.min(64)); + let mut fixed = FIXED; + let mut k = usize::from(band.start.max(1)); + while k < end { + let mut at = 3 * (k - 1); + if d.decode(reader, &mut bins[at])? { + // End of block. + break; + } + while !d.decode(reader, &mut bins[at + 1])? { + at += 3; + k += 1; + if k >= end { + d.fail(); + return Ok(()); + } + } + let negative = d.decode(reader, &mut fixed)?; + at += 2; + let mut m = i32::from(d.decode(reader, &mut bins[at])?); + if m != 0 && d.decode(reader, &mut bins[at])? { + m <<= 1; + at = if k <= usize::from(kx) { + AC_X2_LOW + } else { + AC_X2_HIGH + }; + if !d.category(reader, bins, &mut at, &mut m)? { + return Ok(()); + } + } + let v = d.magnitude(reader, &mut bins[at + M_OFFSET], m, negative)?; + // Truncated to 16 bits, as libjpeg's `JCOEF` is. + let value = (v << al) as i16; + coefficients[usize::from(UNZIGZAG[k & 63]) & 63] = value; + *nonzero = (*nonzero & !(1 << k)) | (u64::from(value != 0) << k); + k += 1; + } + Ok(()) +} + +/// Section G.1.3.1: one more bit of a block's DC value. +pub(crate) fn refine_dc( + d: &mut ArithDecoder, + reader: &mut Buffered, + al: u8, + coefficients: &mut [i16; 64], +) -> Result<()> { + let mut fixed = FIXED; + if d.decode(reader, &mut fixed)? { + coefficients[0] |= 1 << al; + } + Ok(()) +} + +/// Section G.1.3.3: one more bit of a block's AC coefficients in `band`. +#[allow(clippy::too_many_arguments)] +pub(crate) fn refine_ac( + d: &mut ArithDecoder, + reader: &mut Buffered, + stats: &mut Stats, + table: usize, + band: Range, + al: u8, + coefficients: &mut [i16; 64], + nonzero: &mut u64, +) -> Result<()> { + let bins = &mut stats.ac[table]; + let end = usize::from(band.end.min(64)); + let bit = 1i16 << al; + let mut fixed = FIXED; + // `EOBx`, the end of the block as the previous scans left it: no + // end-of-block decision is coded up to there. (Bit 0 is never set in + // `nonzero`; setting it here makes the answer 0 for an empty block.) + let below_end = !0u64 >> (64 - end.max(1)); + let previous_end = 63 - ((*nonzero & below_end) | 1).leading_zeros() as usize; + + let mut k = usize::from(band.start.max(1)); + while k < end { + let mut at = 3 * (k - 1); + if k > previous_end && d.decode(reader, &mut bins[at])? { + break; + } + loop { + let coefficient = &mut coefficients[usize::from(UNZIGZAG[k & 63]) & 63]; + if *coefficient != 0 { + if d.decode(reader, &mut bins[at + 2])? { + // Wrapping as libjpeg's 16-bit arithmetic does; never to + // zero, `bit` being at most `1 << 13`. + *coefficient = if *coefficient < 0 { + coefficient.wrapping_sub(bit) + } else { + coefficient.wrapping_add(bit) + }; + } + break; + } + if d.decode(reader, &mut bins[at + 1])? { + *coefficient = if d.decode(reader, &mut fixed)? { + -bit + } else { + bit + }; + *nonzero |= 1 << k; + break; + } + at += 3; + k += 1; + if k >= end { + d.fail(); + return Ok(()); + } + } + k += 1; + } + Ok(()) +} + +/// Table D.3: `Qe`, the next state after an LPS (with bit 7 set where the +/// sense of the MPS switches) and the next state after an MPS. The last entry +/// is the fixed estimate of 0.5 (T.851, section 10.3). +#[rustfmt::skip] +static QE: [(u16, u8, u8); 128] = { + const STATES: [(u16, u8, u8); 114] = [ + (0x5a1d, 0x81, 1), (0x2586, 0x0e, 2), (0x1114, 0x10, 3), (0x080b, 0x12, 4), + (0x03d8, 0x14, 5), (0x01da, 0x17, 6), (0x00e5, 0x19, 7), (0x006f, 0x1c, 8), + (0x0036, 0x1e, 9), (0x001a, 0x21, 10), (0x000d, 0x23, 11), (0x0006, 0x09, 12), + (0x0003, 0x0a, 13), (0x0001, 0x0c, 13), (0x5a7f, 0x8f, 15), (0x3f25, 0x24, 16), + (0x2cf2, 0x26, 17), (0x207c, 0x27, 18), (0x17b9, 0x28, 19), (0x1182, 0x2a, 20), + (0x0cef, 0x2b, 21), (0x09a1, 0x2d, 22), (0x072f, 0x2e, 23), (0x055c, 0x30, 24), + (0x0406, 0x31, 25), (0x0303, 0x33, 26), (0x0240, 0x34, 27), (0x01b1, 0x36, 28), + (0x0144, 0x38, 29), (0x00f5, 0x39, 30), (0x00b7, 0x3b, 31), (0x008a, 0x3c, 32), + (0x0068, 0x3e, 33), (0x004e, 0x3f, 34), (0x003b, 0x20, 35), (0x002c, 0x21, 9), + (0x5ae1, 0xa5, 37), (0x484c, 0x40, 38), (0x3a0d, 0x41, 39), (0x2ef1, 0x43, 40), + (0x261f, 0x44, 41), (0x1f33, 0x45, 42), (0x19a8, 0x46, 43), (0x1518, 0x48, 44), + (0x1177, 0x49, 45), (0x0e74, 0x4a, 46), (0x0bfb, 0x4b, 47), (0x09f8, 0x4d, 48), + (0x0861, 0x4e, 49), (0x0706, 0x4f, 50), (0x05cd, 0x30, 51), (0x04de, 0x32, 52), + (0x040f, 0x32, 53), (0x0363, 0x33, 54), (0x02d4, 0x34, 55), (0x025c, 0x35, 56), + (0x01f8, 0x36, 57), (0x01a4, 0x37, 58), (0x0160, 0x38, 59), (0x0125, 0x39, 60), + (0x00f6, 0x3a, 61), (0x00cb, 0x3b, 62), (0x00ab, 0x3d, 63), (0x008f, 0x3d, 32), + (0x5b12, 0xc1, 65), (0x4d04, 0x50, 66), (0x412c, 0x51, 67), (0x37d8, 0x52, 68), + (0x2fe8, 0x53, 69), (0x293c, 0x54, 70), (0x2379, 0x56, 71), (0x1edf, 0x57, 72), + (0x1aa9, 0x57, 73), (0x174e, 0x48, 74), (0x1424, 0x48, 75), (0x119c, 0x4a, 76), + (0x0f6b, 0x4a, 77), (0x0d51, 0x4b, 78), (0x0bb6, 0x4d, 79), (0x0a40, 0x4d, 48), + (0x5832, 0xd0, 81), (0x4d1c, 0x58, 82), (0x438e, 0x59, 83), (0x3bdd, 0x5a, 84), + (0x34ee, 0x5b, 85), (0x2eae, 0x5c, 86), (0x299a, 0x5d, 87), (0x2516, 0x56, 71), + (0x5570, 0xd8, 89), (0x4ca9, 0x5f, 90), (0x44d9, 0x60, 91), (0x3e22, 0x61, 92), + (0x3824, 0x63, 93), (0x32b4, 0x63, 94), (0x2e17, 0x5d, 86), (0x56a8, 0xdf, 96), + (0x4f46, 0x65, 97), (0x47e5, 0x66, 98), (0x41cf, 0x67, 99), (0x3c3d, 0x68, 100), + (0x375e, 0x63, 93), (0x5231, 0x69, 102), (0x4c0f, 0x6a, 103), (0x4639, 0x6b, 104), + (0x415e, 0x67, 99), (0x5627, 0xe9, 106), (0x50e7, 0x6c, 107), (0x4b85, 0x6d, 103), + (0x5597, 0x6e, 109), (0x504f, 0x6f, 107), (0x5a10, 0xee, 111), (0x5522, 0x70, 109), + (0x59eb, 0xf0, 111), (0x5a1d, 0x71, 113), + ]; + // Padded to 128 so that a 7-bit index needs no bounds check; no state + // leads to the padding. + let mut table = [STATES[113]; 128]; + let mut i = 0; + while i < STATES.len() { + table[i] = STATES[i]; + i += 1; + } + table +}; + +#[cfg(test)] +mod tests { + use super::*; + + /// The bounds the decoder's unchecked-looking arithmetic relies on. + #[test] + fn states_are_closed_and_estimates_small() { + for &(qe, lps, mps) in &QE { + assert!(qe > 0 && qe < 0x8000); + assert!(usize::from(lps & 0x7F) < 114 && mps < 114); + } + assert_eq!(QE[usize::from(FIXED)], (0x5a1d, FIXED, FIXED)); + } + + /// The worked example of T.81 K.4: decoding the compressed test sequence + /// gives back the 256 input bits. + #[test] + fn annex_k4_test_sequence() { + const CODED: [u8; 30] = [ + 0x65, 0x5B, 0x51, 0x44, 0xF7, 0x96, 0x9D, 0x51, 0x78, 0x55, 0xBF, 0xFF, 0x00, 0xFC, + 0x51, 0x84, 0xC7, 0xCE, 0xF9, 0x39, 0x00, 0x28, 0x7D, 0x46, 0x70, 0x8E, 0xCB, 0xC0, + 0xF6, 0xFF, + ]; + const BITS: [u8; 32] = [ + 0x00, 0x02, 0x00, 0x51, 0x00, 0x00, 0x00, 0xC0, 0x03, 0x52, 0x87, 0x2A, 0xAA, 0xAA, + 0xAA, 0xAA, 0x82, 0xC0, 0x20, 0x00, 0xFC, 0xD7, 0x9E, 0xF6, 0x74, 0xEA, 0xAB, 0xF7, + 0x69, 0x7E, 0xE7, 0x4C, + ]; + let mut data = CODED.to_vec(); + data.push(0xD9); + let mut reader = Buffered::new(&data[..]); + let mut d = ArithDecoder::new(false); + let mut state = 0u8; + for (i, &byte) in BITS.iter().enumerate() { + let mut got = 0u8; + for _ in 0..8 { + got = got << 1 | u8::from(d.decode(&mut reader, &mut state).unwrap()); + } + assert_eq!(got, byte, "byte {i}"); + } + } +} diff --git a/src/decode/decoder.rs b/src/decode/decoder.rs index 87a0013..8ac6842 100644 --- a/src/decode/decoder.rs +++ b/src/decode/decoder.rs @@ -1,10 +1,11 @@ +use crate::decode::arith::Conditioning; use crate::decode::error::{Error, Result, UnsupportedFeature, Warning, Warnings}; use crate::decode::huffman::{ fill_default_mjpeg_tables, HuffmanDecoder, HuffmanTable, AC_EOB, FAST_BITS, }; use crate::decode::marker::Marker; use crate::decode::parser::{ - parse_app, parse_com, parse_dht, parse_dqt, parse_dri, parse_sof, parse_sos, + parse_app, parse_com, parse_dac, parse_dht, parse_dqt, parse_dri, parse_sof, parse_sos, AdobeColorTransform, AppData, CodingProcess, Component, Dimensions, EntropyCoding, FrameInfo, IccChunk, ScanInfo, }; @@ -25,13 +26,15 @@ use core::ops::Range; pub const MAX_COMPONENTS: usize = 4; +mod arithmetic; mod lossless; mod smoothing; -use self::lossless::compute_image_lossless; +mod twelve; +use self::lossless::{compute_image_lossless, convert_to_u8}; use self::smoothing::{Grid, Progression}; #[rustfmt::skip] -static UNZIGZAG: [u8; 64] = [ +pub(crate) static UNZIGZAG: [u8; 64] = [ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, @@ -80,6 +83,42 @@ pub struct ImageInfo { pub coding_process: CodingProcess, } +/// The frame header of an image: what [`ImageInfo`] says, for every layout the +/// decoder reads, and how its samples are output. +/// +/// [`ImageInfo`] cannot say that samples are wider than 8 bits (its +/// [`PixelFormat`] only does for one component) and has no format at all for +/// the two components of a lossless DNG tile. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct FrameHeader { + /// The width of the output, in pixels. + pub width: u16, + /// The height of the output, in pixels. + pub height: u16, + /// Components per pixel, interleaved in the output: 1, 3 or 4, or 2 in a + /// lossless image. + pub components: u8, + /// Bits per sample. Samples are output unscaled, in `0..2^precision`. + pub precision: u8, + /// The coding process of the image. + pub coding_process: CodingProcess, + /// Arithmetic rather than Huffman entropy coding. + pub arithmetic_coding: bool, +} + +impl FrameHeader { + /// Bytes per sample in what [`Decoder::decode`] returns: 1 for 8-bit + /// images, otherwise 2, in native byte order. + pub fn bytes_per_sample(&self) -> usize { + if self.precision == 8 { + 1 + } else { + 2 + } + } +} + /// Describes the colour transform to apply before binary data is returned #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[non_exhaustive] @@ -155,6 +194,17 @@ pub struct Decoder { planar_output: bool, planar_result: Option, + // The same for `decode_u16`, for images whose samples are wider than 8 bits. + u16_output: bool, + u16_result: Option>, + + /// Arithmetic conditioning parameters (DAC). + conditioning: Conditioning, + /// For a frame that `renders_late`: the quantization table each component's + /// first scan found (libjpeg's `latch_quant_tables`). A DQT between scans + /// may replace it afterwards. + latched_tables: [Option>; MAX_COMPONENTS], + /// Decode on the calling thread only. See [`set_single_threaded`]. single_threaded: bool, @@ -296,6 +346,10 @@ impl Decoder { decoding_buffer_size_limit: usize::MAX, planar_output: false, planar_result: None, + u16_output: false, + u16_result: None, + conditioning: Conditioning::default(), + latched_tables: [None, None, None, None], single_threaded: false, plane_pool: Vec::new(), warnings: Warnings::default(), @@ -314,8 +368,14 @@ impl Decoder { /// out in and uniform grey below; a progressive image shows every block /// at the precision the scans that did arrive gave it. /// - [`Warning::SegmentEndedEarly`], [`Warning::BadHuffmanCode`], - /// [`Warning::RestartMarkerMismatch`], [`Warning::ExtraneousBytes`], - /// [`Warning::MissingScan`]: damage inside the stream. + /// [`Warning::BadArithmeticCode`], [`Warning::RestartMarkerMismatch`], + /// [`Warning::ExtraneousBytes`], [`Warning::MissingScan`]: damage inside + /// the stream. + /// + /// Arithmetic coding allows a segment to stop before its last MCU (the + /// decoder supplies zero bytes), so a segment that a marker cuts short is + /// not reported as [`Warning::SegmentEndedEarly`]: its remaining MCUs + /// decode from those zeros, as in libjpeg-turbo. /// /// ```no_run /// # use rusty_jpeg::decode::{Decoder, Warning}; @@ -368,16 +428,15 @@ impl Decoder { /// Returns metadata about the image. /// /// The returned value will be `None` until a call to either `read_info` or `decode` has - /// returned `Ok`. + /// returned `Ok`, and for a lossless image of two components, which no [`PixelFormat`] + /// describes: see [`frame_header`](Self::frame_header), which also tells the sample precision. + /// ([`PixelFormat::RGB24`] and [`PixelFormat::CMYK32`] name the components only: with more + /// than 8 bits per sample the output has two bytes for each.) pub fn info(&self) -> Option { match self.frame { Some(ref frame) => { - // The frame header is validated (1, 3 or 4 components, - // precision 2..=16) before a frame is stored, so the `None` - // arms are unreachable today. They are `None` rather than - // `panic!()` so that admitting another layout later, such as - // the 2-component lossless tiles in DNG, cannot turn a metadata - // query into a panic. + // The frame header is validated (1 to 4 components, precision + // 2..=16) before a frame is stored. let pixel_format = match frame.components.len() { 1 => match frame.precision { 2..=8 => PixelFormat::L8, @@ -400,6 +459,21 @@ impl Decoder { } } + /// The frame header, for every image the decoder reads. + /// + /// The returned value will be `None` until a call to either `read_info` or `decode` has + /// returned `Ok`. + pub fn frame_header(&self) -> Option { + self.frame.as_ref().map(|frame| FrameHeader { + width: frame.output_size.width, + height: frame.output_size.height, + components: frame.components.len() as u8, + precision: frame.precision, + coding_process: frame.coding_process, + arithmetic_coding: frame.entropy_coding == EntropyCoding::Arithmetic, + }) + } + /// Returns raw exif data, starting at the TIFF header, if the image contains any. /// /// The returned value will be `None` until a call to `decode` has returned `Ok`. @@ -510,10 +584,38 @@ impl Decoder { /// case, a file cut short). Call [`set_strict`](Self::set_strict) first to /// have such a stream refused instead. The same holds for /// [`decode_planar`](Self::decode_planar). + /// + /// Samples are interleaved. At 8 bits each is a byte. An image of any other + /// precision -- 12-bit DCT, lossless up to 16 bits -- has two bytes per + /// sample in **native byte order**, unscaled: a 12-bit sample is in + /// `0..=4095`. [`frame_header`](Self::frame_header) tells which, and + /// [`decode_u16`](Self::decode_u16) returns them as `u16`. pub fn decode(&mut self) -> Result> { WorkerScope::with(|worker| self.decode_internal(false, worker)) } + /// [`decode`](Self::decode), with the samples as `u16`. + /// + /// Samples are not scaled: they are in `0..2^precision` (see + /// [`FrameHeader::precision`]), `0..=4095` for a 12-bit image. An 8-bit + /// image is widened. + /// + /// A lossless image may have two components. That is how DNG codes a tile + /// of CFA data, whose neighbouring columns are different colours: the two + /// components are the even and the odd columns, so the interleaved samples + /// returned here are the tile's samples in order (and the tile has twice + /// as many per JPEG row as the JPEG has pixels). + pub fn decode_u16(&mut self) -> Result> { + self.u16_output = true; + let result = self.decode(); + self.u16_output = false; + let bytes = result?; + Ok(match self.u16_result.take() { + Some(samples) => samples, + None => bytes.iter().map(|&sample| u16::from(sample)).collect(), + }) + } + /// Hand plane allocations from a previous decode back for reuse. /// /// Sizing fresh output planes is **66.7% of whole-frame decode** here — 3.1 @@ -567,7 +669,8 @@ impl Decoder { /// planes as the entropy decoder produced them, which is what such a /// pipeline actually wants. /// - /// Not supported for lossless JPEG (which has its own 16-bit path). + /// Not supported for lossless JPEG (which has its own 16-bit path), nor for + /// 12-bit images. pub fn decode_planar(&mut self) -> Result { let _t = crate::prof::scope(crate::prof::Stage::Total); self.planar_output = true; @@ -661,22 +764,30 @@ impl Decoder { if frame.is_differential { return Err(Error::Unsupported(UnsupportedFeature::Hierarchical)); } - if frame.entropy_coding == EntropyCoding::Arithmetic { + if frame.entropy_coding == EntropyCoding::Arithmetic + && frame.coding_process == CodingProcess::Lossless + { return Err(Error::Unsupported( UnsupportedFeature::ArithmeticEntropyCoding, )); } - if frame.precision != 8 && frame.coding_process != CodingProcess::Lossless { - return Err(Error::Unsupported(UnsupportedFeature::SamplePrecision( - frame.precision, - ))); - } if !(2..=16).contains(&frame.precision) { return Err(Error::Unsupported(UnsupportedFeature::SamplePrecision( frame.precision, ))); } - if component_count != 1 && component_count != 3 && component_count != 4 { + // Two components are the columns of a DNG lossless tile, + // and only make sense as full-size planes. + let lossless_pair = component_count == 2 + && frame.coding_process == CodingProcess::Lossless + && frame.components.iter().all(|c| { + (c.horizontal_sampling_factor, c.vertical_sampling_factor) == (1, 1) + }); + if !lossless_pair + && component_count != 1 + && component_count != 3 + && component_count != 4 + { return Err(Error::Unsupported(UnsupportedFeature::ComponentCount( component_count as u8, ))); @@ -720,11 +831,12 @@ impl Decoder { // files; demanding neither is what let a panic reach the // block loop. The checks below are the exact conditions // under which `decode_block` will actually use each table. + // (An arithmetic scan needs none: its tables have defaults.) // // This is not progressive-specific: any scan, baseline // included, can name a table slot no DHT ever defined. // Progressive merely makes it common. - { + if frame.entropy_coding == EntropyCoding::Huffman { let needs_dc = scan.spectral_selection.start == 0 && scan.successive_approximation_high == 0; let needs_ac = scan.spectral_selection.end > 1; @@ -759,6 +871,7 @@ impl Decoder { .len() .checked_mul(frame.output_size.width.into()) .and_then(|m| m.checked_mul(frame.output_size.height.into())) + .and_then(|m| m.checked_mul(1 + usize::from(frame.is_twelve_bit()))) .is_none_or(|m| self.decoding_buffer_size_limit < m) { return Err(Error::Format( @@ -776,9 +889,13 @@ impl Decoder { return Err(Error::UnexpectedEof); } - if frame.coding_process == CodingProcess::DctProgressive - && self.coefficients.is_empty() - { + if frame.is_twelve_bit() && self.planar_output { + return Err(Error::Unsupported(UnsupportedFeature::SamplePrecision( + frame.precision, + ))); + } + + if frame.stores_coefficients() && self.coefficients.is_empty() { // Progressive keeps every coefficient of the whole image // resident, because later scans revisit the same blocks. // That buffer is sized straight from the frame header, @@ -834,14 +951,44 @@ impl Decoder { if frame.coding_process == CodingProcess::Lossless { let (marker, data) = self.decode_scan_lossless(&frame, &scan)?; - for (i, plane) in data - .into_iter() - .enumerate() - .filter(|(_, plane)| !plane.is_empty()) - { + // In scan order, which is not the frame's when a scan + // codes one component of several. + for (&i, plane) in scan.component_indices.iter().zip(data) { planes_u16[i] = plane; } pending_marker = marker; + } else if frame.renders_late() { + if frame.coding_process == CodingProcess::DctProgressive { + self.progression.start_scan(&scan); + } + for &i in &scan.component_indices { + let table = frame.components[i].quantization_table_index; + if self.latched_tables[i].is_none() { + self.latched_tables[i] = self.quantization_tables[table].clone(); + } + } + + pending_marker = if frame.entropy_coding == EntropyCoding::Arithmetic { + self.decode_scan_arithmetic(&frame, &scan)? + } else { + // The progressive block loop, which stores what it + // decodes. It codes a whole block at full precision + // when the scan says so, as a sequential one does. + // No component is "finished" by it, so it never + // hands the worker anything. + let (marker, _) = worker_scope.get_or_init_worker( + PreferWorkerKind::Immediate, + |worker| { + self.decode_scan( + &frame, + &scan, + worker, + &[false; MAX_COMPONENTS], + ) + }, + )?; + marker + }; } else { // This was previously buggy, so let's explain the log here a bit. When a // progressive frame is encoded then the coefficients (DC, AC) of each @@ -957,9 +1104,7 @@ impl Decoder { } // Arithmetic conditioning table-specification Marker::DAC => { - return Err(Error::Unsupported( - UnsupportedFeature::ArithmeticEntropyCoding, - )) + or_end_of_image!(parse_dac(&mut self.reader, &mut self.conditioning)) } // Restart interval definition Marker::DRI => { @@ -1080,6 +1225,7 @@ impl Decoder { .len() .checked_mul(frame.output_size.width.into()) .and_then(|m| m.checked_mul(frame.output_size.height.into())) + .and_then(|m| m.checked_mul(1 + usize::from(frame.is_twelve_bit()))) .is_none_or(|m| self.decoding_buffer_size_limit < m) { return Err(Error::Format( @@ -1087,10 +1233,13 @@ impl Decoder { )); } + if frame.is_twelve_bit() { + let samples = self.render_twelve_bit(any_scan)?; + return Ok(self.output_wide(samples)); + } + // If we're decoding a progressive jpeg and a component is unfinished, render what we've got - if frame.coding_process == CodingProcess::DctProgressive - && self.coefficients.len() == frame.components.len() - { + if frame.stores_coefficients() && self.coefficients.len() == frame.components.len() { // A progressive image whose DATA ENDED EARLY is rendered with // libjpeg-turbo's interblock smoothing (see `smoothing`), which is // what makes a cut-short download look like a soft version of the @@ -1103,29 +1252,24 @@ impl Decoder { // a stream that ends with a proper EOI but whose scans never bring // the low coefficients to full precision; such a stream decodes // here today, and its output is left exactly as it was. - let smoothing = if self.warnings.as_slice().contains(&Warning::Truncated) { + let smoothing = if frame.coding_process == CodingProcess::DctProgressive + && self.warnings.as_slice().contains(&Warning::Truncated) + { self.progression - .smoothing(&frame.components, &self.quantization_tables) + .smoothing(&frame.components, |i| self.component_table(frame, i)) } else { None }; - let max_sampling = |factor: fn(&Component) -> u8| { - usize::from(frame.components.iter().map(factor).max().unwrap_or(1)) - }; - let h_max = max_sampling(|c| c.horizontal_sampling_factor); - let v_max = max_sampling(|c| c.vertical_sampling_factor); - for (i, component) in frame.components.iter().enumerate() { // Only dealing with unfinished components if smoothing.is_none() && self.coefficients_finished[i] == !0 { continue; } - let quantization_table = - match self.quantization_tables[component.quantization_table_index].clone() { - Some(quantization_table) => quantization_table, - None => continue, - }; + let quantization_table = match self.component_table(frame, i) { + Some(quantization_table) => quantization_table, + None => continue, + }; // Get the worker prepared let row_data = RowData { @@ -1145,18 +1289,7 @@ impl Decoder { * usize::from(component.vertical_sampling_factor) * 64; - let grid = Grid { - coefficients: &self.coefficients[i], - blocks_wide: usize::from(component.block_size.width), - width_in_blocks: (usize::from(frame.image_size.width) - * usize::from(component.horizontal_sampling_factor)) - .div_ceil(h_max * 8), - height_in_blocks: (usize::from(frame.image_size.height) - * usize::from(component.vertical_sampling_factor)) - .div_ceil(v_max * 8), - v_samp: usize::from(component.vertical_sampling_factor), - mcu_rows: usize::from(frame.mcu_size.height), - }; + let grid = self.grid(frame, i); let mut tasks = (0..frame.mcu_size.height).map(|mcu_y| { let offset = usize::from(mcu_y) * coefficients_per_mcu_row; @@ -1215,7 +1348,8 @@ impl Decoder { let _s = crate::prof::scope(crate::prof::Stage::DecOutput); if frame.coding_process == CodingProcess::Lossless { - return compute_image_lossless(frame, planes_u16); + let samples = compute_image_lossless(frame, planes_u16)?; + return Ok(self.output_wide(samples)); } // Clone the little bits we need so the borrow of `self.frame` ends here @@ -1242,6 +1376,97 @@ impl Decoder { ) } + /// The quantization table component `i` is rendered with. + fn component_table(&self, frame: &FrameInfo, i: usize) -> Option> { + if frame.renders_late() { + self.latched_tables[i].clone() + } else { + self.quantization_tables[frame.components[i].quantization_table_index].clone() + } + } + + /// The block grid of component `i`, for smoothing. + fn grid(&self, frame: &FrameInfo, i: usize) -> Grid<'_> { + let component = &frame.components[i]; + let (width_in_blocks, height_in_blocks) = frame.image_blocks(i); + Grid { + coefficients: &self.coefficients[i], + blocks_wide: usize::from(component.block_size.width), + width_in_blocks: usize::from(width_in_blocks), + height_in_blocks: usize::from(height_in_blocks), + v_samp: usize::from(component.vertical_sampling_factor), + mcu_rows: usize::from(frame.mcu_size.height), + } + } + + /// Hand out samples decoded as `u16`, as the caller asked for them. + fn output_wide(&mut self, samples: Vec) -> Vec { + if self.u16_output { + self.u16_result = Some(samples); + return Vec::new(); + } + convert_to_u8(self.frame.as_ref().unwrap(), samples) + } + + /// Render a 12-bit frame from its stored coefficients. + fn render_twelve_bit(&mut self, any_scan: bool) -> Result> { + let frame = self.frame.as_ref().unwrap(); + if !any_scan { + return Err(Error::Format("not all components have data".to_owned())); + } + // As for 8 bits (see `decode_planes`). + let smoothing = if frame.coding_process == CodingProcess::DctProgressive + && self.warnings.as_slice().contains(&Warning::Truncated) + { + self.progression + .smoothing(&frame.components, |i| self.component_table(frame, i)) + } else { + None + }; + + let mut planes = Vec::with_capacity(frame.components.len()); + for (i, component) in frame.components.iter().enumerate() { + let blocks_per_row = usize::from(component.block_size.width) + * usize::from(component.vertical_sampling_factor); + let samples_per_row = blocks_per_row * component.dct_scale * component.dct_scale; + let mut plane = vec![0u16; samples_per_row * usize::from(frame.mcu_size.height)]; + let table = match self.component_table(frame, i) { + Some(table) => table, + None => { + self.warnings.raise(Warning::MissingScan)?; + plane.fill(1 << (frame.precision - 1)); + planes.push(plane); + continue; + } + }; + let rows = self.coefficients[i].chunks_exact(blocks_per_row * 64); + let masks = self.nonzero[i].chunks_exact(blocks_per_row); + let grid = self.grid(frame, i); + let mut smoothed = Vec::new(); + for (mcu_y, ((row, masks), output)) in rows + .zip(masks) + .zip(plane.chunks_exact_mut(samples_per_row)) + .enumerate() + { + if let Some(smoothing) = &smoothing { + smoothed.clear(); + smoothed.extend_from_slice(row); + smoothing.smooth_mcu_row(i, &grid, &table, mcu_y, &mut smoothed); + twelve::render_rows(component, &smoothed, None, &table, output); + } else { + twelve::render_rows(component, row, Some(masks), &table, output); + } + } + planes.push(plane); + } + twelve::compute_image( + &frame.components, + planes, + frame.output_size, + self.determine_color_transform(), + ) + } + /// A plane to refill for `component`: the caller's (`recycle_planes`) /// first, else one from this thread's pool (see `plane_pool`). fn take_plane(pool: &mut Vec>, component: &Component) -> Option> { @@ -1347,7 +1572,7 @@ impl Decoder { // registers (+0.7% Ir on a sequential 4:4:4 decode after the // `nonzero` refinement and the in-place row hand-off). With the // process a constant, each copy carries only its own paths. - if frame.coding_process == CodingProcess::DctProgressive { + if frame.stores_coefficients() { self.decode_scan_for::(frame, scan, worker, finished) } else { self.decode_scan_for::(frame, scan, worker, finished) @@ -1425,10 +1650,9 @@ impl Decoder { } } - debug_assert_eq!( - PROGRESSIVE, - frame.coding_process == CodingProcess::DctProgressive - ); + // `PROGRESSIVE` also decodes sequential frames whose coefficients are + // stored, with no component to hand to the worker. + debug_assert_eq!(PROGRESSIVE, frame.stores_coefficients()); let is_progressive = PROGRESSIVE; let is_interleaved = components.len() > 1; // Fuse entropy decode straight into the IDCT when the worker consumes @@ -1498,6 +1722,8 @@ impl Decoder { // the MCUs will be exactly the block count. let (max_mcu_x, max_mcu_y) = if is_interleaved { (frame.mcu_size.width, frame.mcu_size.height) + } else if PROGRESSIVE && frame.renders_late() { + frame.image_blocks(scan.component_indices[0]) } else { ( components[0].block_size.width, @@ -1832,11 +2058,23 @@ impl Decoder { // Whole bytes of the scan's data that no MCU used, here or (below) // beyond what the bit reader can hold before it meets a marker. let mut extraneous = huffman.unread_bytes() > 0; - let mut marker = huffman.take_marker(&mut self.reader)?; + let marker = huffman.take_marker(&mut self.reader)?; extraneous |= marker.is_none(); if extraneous { self.warnings.raise(Warning::ExtraneousBytes)?; } + let marker = self.skip_stray_markers(marker)?; + if huffman.saw_bad_code() { + self.warnings.raise(Warning::BadHuffmanCode)?; + } + if huffman.hit_end_of_data() { + self.warnings.raise(Warning::Truncated)?; + } + Ok(marker) + } + + /// The marker after a scan's data, given the one found there. + fn skip_stray_markers(&mut self, mut marker: Option) -> Result> { // Some encoders emit a final RST after the entropy-coded data; skip it. // A TEM or RES code here is corrupt entropy data that merely looked // like a marker (FF followed by a byte below SOF0): skip to the next @@ -1850,12 +2088,6 @@ impl Decoder { Err(error) => return Err(error), }; } - if huffman.saw_bad_code() { - self.warnings.raise(Warning::BadHuffmanCode)?; - } - if huffman.hit_end_of_data() { - self.warnings.raise(Warning::Truncated)?; - } Ok(marker) } } diff --git a/src/decode/decoder/arithmetic.rs b/src/decode/decoder/arithmetic.rs new file mode 100644 index 0000000..93e1f4c --- /dev/null +++ b/src/decode/decoder/arithmetic.rs @@ -0,0 +1,158 @@ +//! Scans of arithmetic-coded frames (SOF9 and SOF10). + +use crate::decode::arith::{self, ArithDecoder, DcState, Stats}; +use crate::decode::decoder::{Decoder, MAX_COMPONENTS}; +use crate::decode::error::{Error, Result, Warning}; +use crate::decode::marker::Marker; +use crate::decode::parser::{FrameInfo, ScanInfo}; +use crate::decode::Source; +use alloc::borrow::ToOwned; +use alloc::boxed::Box; + +impl Decoder { + /// Decode one scan into the stored coefficients (`self.coefficients`), + /// sequential and progressive alike. Returns the marker that ended it, if + /// the decoder ran into one. + pub(super) fn decode_scan_arithmetic( + &mut self, + frame: &FrameInfo, + scan: &ScanInfo, + ) -> Result> { + let components = &scan.component_indices; + assert!(components.len() <= MAX_COMPONENTS); + if components.iter().any(|&i| { + self.quantization_tables[frame.components[i].quantization_table_index].is_none() + }) { + return Err(Error::Format("use of unset quantization table".to_owned())); + } + + let band = scan.spectral_selection.clone(); + let al = scan.successive_approximation_low; + let codes_dc = band.start == 0; + let codes_ac = band.end > 1; + let refinement = scan.successive_approximation_high != 0; + + // The MCUs of the scan, and what one holds of each component (4.8.2): + // in a scan of one component a single block, and only those blocks + // that carry samples of the image. + let interleaved = components.len() > 1; + let (mcus_wide, mcus_high) = if interleaved { + (frame.mcu_size.width, frame.mcu_size.height) + } else { + frame.image_blocks(components[0]) + }; + + let mut d = ArithDecoder::new(self.warnings.strict); + let mut stats = Box::new(Stats::new()); + let mut dc = [DcState::default(); MAX_COMPONENTS]; + let mut mcus_left_until_restart = self.restart_interval; + let mut expected_rst_num = 0; + + for mcu_y in 0..usize::from(mcus_high) { + for mcu_x in 0..usize::from(mcus_wide) { + if self.restart_interval > 0 { + if mcus_left_until_restart == 0 { + d.restart(&mut self.reader, expected_rst_num, &mut self.warnings)?; + for (&dc_table, &ac_table) in + scan.dc_table_indices.iter().zip(&scan.ac_table_indices) + { + stats.reset(dc_table, ac_table); + } + dc = Default::default(); + expected_rst_num = (expected_rst_num + 1) % 8; + mcus_left_until_restart = self.restart_interval; + } + mcus_left_until_restart -= 1; + } + + 'mcu: for (i, &ci) in components.iter().enumerate() { + let component = &frame.components[ci]; + let (across, down) = if interleaved { + ( + usize::from(component.horizontal_sampling_factor), + usize::from(component.vertical_sampling_factor), + ) + } else { + (1, 1) + }; + let dc_table = scan.dc_table_indices[i]; + let ac_table = scan.ac_table_indices[i]; + for v in 0..down { + for h in 0..across { + // The rest of a segment that went wrong is left as + // it is: zero, or as earlier scans had it. + if d.failed() { + break 'mcu; + } + let block = (mcu_y * down + v) + * usize::from(component.block_size.width) + + mcu_x * across + + h; + let coefficients: &mut [i16; 64] = (&mut self.coefficients[ci] + [block * 64..block * 64 + 64]) + .try_into() + .unwrap(); + let nonzero = &mut self.nonzero[ci][block]; + + if codes_dc && refinement { + arith::refine_dc(&mut d, &mut self.reader, al, coefficients)?; + } else if codes_dc { + match arith::decode_dc( + &mut d, + &mut self.reader, + &mut stats, + dc_table, + self.conditioning.dc[dc_table], + &mut dc[i], + )? { + Some(value) => coefficients[0] = (value << al) as i16, + None => break 'mcu, + } + } + if codes_ac && refinement { + arith::refine_ac( + &mut d, + &mut self.reader, + &mut stats, + ac_table, + band.clone(), + al, + coefficients, + nonzero, + )?; + } else if codes_ac { + arith::decode_ac( + &mut d, + &mut self.reader, + &mut stats, + ac_table, + self.conditioning.ac[ac_table], + band.clone(), + al, + coefficients, + nonzero, + )?; + } + } + } + } + } + } + + // libjpeg's arithmetic decoder never reports exhausted data (its + // `insufficient_data` stays FALSE), running into a marker early being + // legal. So the smoothing of a truncated progressive image takes every + // row of the scan for decoded. + self.progression.last_good_row = frame.mcu_size.height.saturating_sub(1); + + if d.saw_bad_code() { + self.warnings.raise(Warning::BadArithmeticCode)?; + } + let marker = d.source().take_pending_marker(); + let marker = self.skip_stray_markers(marker)?; + if d.source().hit_end_of_data() { + self.warnings.raise(Warning::Truncated)?; + } + Ok(marker) + } +} diff --git a/src/decode/decoder/lossless.rs b/src/decode/decoder/lossless.rs index 00c56fa..e934f36 100644 --- a/src/decode/decoder/lossless.rs +++ b/src/decode/decoder/lossless.rs @@ -213,36 +213,37 @@ fn predict(ra: i32, rb: i32, rc: i32, predictor: Predictor) -> i32 { } } -pub fn compute_image_lossless(frame: &FrameInfo, mut data: Vec>) -> Result> { +/// The image's samples, interleaved. +pub fn compute_image_lossless(frame: &FrameInfo, mut data: Vec>) -> Result> { if data.is_empty() || data.iter().any(Vec::is_empty) { return Err(Error::Format("not all components have data".to_owned())); } let output_size = frame.output_size; - let components = &frame.components; - let ncomp = components.len(); + let ncomp = frame.components.len(); if ncomp == 1 { - let decoded = convert_to_u8(frame, data.remove(0)); - Ok(decoded) - } else { - let mut decoded: Vec = - vec![0u16; ncomp * output_size.width as usize * output_size.height as usize]; - for (x, chunk) in decoded.chunks_mut(ncomp).enumerate() { - for (i, (component_data, _)) in data.iter().zip(components.iter()).enumerate() { - chunk[i] = component_data[x]; - } + return Ok(data.remove(0)); + } + let mut decoded: Vec = + vec![0u16; ncomp * output_size.width as usize * output_size.height as usize]; + for (x, chunk) in decoded.chunks_mut(ncomp).enumerate() { + for (sample, component_data) in chunk.iter_mut().zip(&data) { + *sample = component_data[x]; } - let decoded = convert_to_u8(frame, decoded); - Ok(decoded) } + Ok(decoded) } -fn convert_to_u8(frame: &FrameInfo, data: Vec) -> Vec { +/// Samples as the bytes `decode` returns them in. +pub(super) fn convert_to_u8(frame: &FrameInfo, data: Vec) -> Vec { if frame.precision == 8 { data.iter().map(|x| *x as u8).collect() } else { // we output native endian, which is the standard for image-rs - let ne_bytes: Vec<_> = data.iter().map(|x| x.to_ne_bytes()).collect(); - ne_bytes.concat() + let mut bytes = vec![0u8; data.len() * 2]; + for (pair, sample) in bytes.chunks_exact_mut(2).zip(&data) { + pair.copy_from_slice(&sample.to_ne_bytes()); + } + bytes } } diff --git a/src/decode/decoder/smoothing.rs b/src/decode/decoder/smoothing.rs index 8cd36a7..145cb46 100644 --- a/src/decode/decoder/smoothing.rs +++ b/src/decode/decoder/smoothing.rs @@ -95,7 +95,7 @@ impl Progression { pub(crate) fn smoothing( &self, components: &[Component], - quantization_tables: &[Option>; 4], + table_of: impl Fn(usize) -> Option>, ) -> Option { let mut useful = false; let mut smoothing = Smoothing { @@ -103,8 +103,8 @@ impl Progression { prev_coef_bits: [[-1; SAVED_COEFS]; MAX_COMPONENTS], last_good_row: self.last_good_row, }; - for (ci, component) in components.iter().enumerate() { - let table = quantization_tables[component.quantization_table_index].as_ref()?; + for ci in 0..components.len() { + let table = table_of(ci)?; if POSITIONS.iter().any(|&position| table[position] == 0) { return None; } diff --git a/src/decode/decoder/twelve.rs b/src/decode/decoder/twelve.rs new file mode 100644 index 0000000..875351d --- /dev/null +++ b/src/decode/decoder/twelve.rs @@ -0,0 +1,379 @@ +//! Rendering of 12-bit lossy frames: dequantization and inverse DCT, chroma +//! upsampling and colour conversion on 16-bit samples. +//! +//! Everything here is libjpeg-turbo's 12-bit arithmetic -- the accurate integer +//! IDCT (jidctint.c) and its reduced sizes (jidctred.c) with the 12-bit +//! `PASS1_BITS`, the "fancy" upsampling of jdsample.c with its alternating +//! rounding biases, the fixed-point colour conversion of jdcolor.c -- so the +//! output is `djpeg`'s, sample for sample. (libjpeg-turbo has no SIMD for it +//! either.) The 8-bit path keeps the kernels it always had. + +use crate::decode::decoder::{choose_color_convert_func, ColorTransform}; +use crate::decode::error::{Error, Result}; +use crate::decode::parser::{Component, Dimensions}; +use alloc::borrow::ToOwned; +use alloc::vec; +use alloc::vec::Vec; + +/// The largest sample, and the level shift (A.3.1). +const MAX: i32 = 4095; +const CENTRE: i32 = 2048; + +const CONST_BITS: u32 = 13; +const PASS1_BITS: u32 = 1; + +// `x * 2^13`, rounded: the constants of jidctint.c and jidctred.c. +const FIX_0_211164243: i64 = 1730; +const FIX_0_298631336: i64 = 2446; +const FIX_0_390180644: i64 = 3196; +const FIX_0_509795579: i64 = 4176; +const FIX_0_541196100: i64 = 4433; +const FIX_0_601344887: i64 = 4926; +const FIX_0_720959822: i64 = 5906; +const FIX_0_765366865: i64 = 6270; +const FIX_0_850430095: i64 = 6967; +const FIX_0_899976223: i64 = 7373; +const FIX_1_061594337: i64 = 8697; +const FIX_1_175875602: i64 = 9633; +const FIX_1_272758580: i64 = 10426; +const FIX_1_451774981: i64 = 11893; +const FIX_1_501321110: i64 = 12299; +const FIX_1_847759065: i64 = 15137; +const FIX_1_961570560: i64 = 16069; +const FIX_2_053119869: i64 = 16819; +const FIX_2_172734803: i64 = 17799; +const FIX_2_562915447: i64 = 20995; +const FIX_3_072711026: i64 = 25172; +const FIX_3_624509785: i64 = 29692; + +/// libjpeg's `DESCALE`. Nothing overflows: a dequantized coefficient fits 32 +/// bits, and a pass gains fewer than 20. +#[inline(always)] +fn descale(x: i64, n: u32) -> i64 { + (x + (1 << (n - 1))) >> n +} + +/// libjpeg's `range_limit[x & RANGE_MASK]`: level shift and clamp, with the +/// wrap that a value beyond the table (corrupt data only) takes. +#[inline(always)] +fn range_limit(x: i64) -> u16 { + let wrapped = ((x as i32) << 18) >> 18; + (wrapped + CENTRE).clamp(0, MAX) as u16 +} + +/// One pass of the 8-point transform, not yet descaled. +#[inline(always)] +fn pass8(i: [i64; 8]) -> [i64; 8] { + let z1 = (i[2] + i[6]) * FIX_0_541196100; + let tmp2 = z1 - i[6] * FIX_1_847759065; + let tmp3 = z1 + i[2] * FIX_0_765366865; + let tmp0 = (i[0] + i[4]) << CONST_BITS; + let tmp1 = (i[0] - i[4]) << CONST_BITS; + let tmp10 = tmp0 + tmp3; + let tmp13 = tmp0 - tmp3; + let tmp11 = tmp1 + tmp2; + let tmp12 = tmp1 - tmp2; + + let z5 = (i[7] + i[3] + i[5] + i[1]) * FIX_1_175875602; + let z1 = -(i[7] + i[1]) * FIX_0_899976223; + let z2 = -(i[5] + i[3]) * FIX_2_562915447; + let z3 = z5 - (i[7] + i[3]) * FIX_1_961570560; + let z4 = z5 - (i[5] + i[1]) * FIX_0_390180644; + let tmp0 = i[7] * FIX_0_298631336 + z1 + z3; + let tmp1 = i[5] * FIX_2_053119869 + z2 + z4; + let tmp2 = i[3] * FIX_3_072711026 + z2 + z3; + let tmp3 = i[1] * FIX_1_501321110 + z1 + z4; + + [ + tmp10 + tmp3, + tmp11 + tmp2, + tmp12 + tmp1, + tmp13 + tmp0, + tmp13 - tmp0, + tmp12 - tmp1, + tmp11 - tmp2, + tmp10 - tmp3, + ] +} + +/// One pass of the 4-point output transform (`_jpeg_idct_4x4`). Input 4 is not +/// used. +#[inline(always)] +fn pass4(i: [i64; 8]) -> [i64; 4] { + let even = i[0] << (CONST_BITS + 1); + let tmp2 = i[2] * FIX_1_847759065 - i[6] * FIX_0_765366865; + let tmp10 = even + tmp2; + let tmp12 = even - tmp2; + let tmp0 = i[5] * FIX_1_451774981 + i[1] * FIX_1_061594337 + - i[7] * FIX_0_211164243 + - i[3] * FIX_2_172734803; + let tmp2 = i[3] * FIX_0_899976223 + i[1] * FIX_2_562915447 + - i[7] * FIX_0_509795579 + - i[5] * FIX_0_601344887; + [tmp10 + tmp2, tmp12 + tmp0, tmp12 - tmp0, tmp10 - tmp2] +} + +/// One pass of the 2-point output transform (`_jpeg_idct_2x2`). Inputs 2, 4 +/// and 6 are not used. +#[inline(always)] +fn pass2(i: [i64; 8]) -> [i64; 2] { + let tmp10 = i[0] << (CONST_BITS + 2); + let tmp0 = i[5] * FIX_0_850430095 + i[1] * FIX_3_624509785 + - i[7] * FIX_0_720959822 + - i[3] * FIX_1_272758580; + [tmp10 + tmp0, tmp10 - tmp0] +} + +/// Dequantize and transform one block to `N x N` samples. `extra` is the +/// additional scaling inside the reduced sizes' passes. +#[inline(always)] +fn idct( + coefficients: &[i16; 64], + table: &[u16; 64], + extra: u32, + pass: impl Fn([i64; 8]) -> [i64; N], + stride: usize, + output: &mut [u16], +) { + let mut workspace = [[0i64; 8]; N]; + for x in 0..8 { + let column: [i64; 8] = core::array::from_fn(|y| { + i64::from(coefficients[y * 8 + x]) * i64::from(table[y * 8 + x]) + }); + // libjpeg's workspace is `int`, hence the truncations. + if column[1..].iter().fold(0, |any, &c| any | c) == 0 { + // What the pass would give, without it. + for row in workspace.iter_mut() { + row[x] = i64::from((column[0] << PASS1_BITS) as i32); + } + continue; + } + for (row, value) in workspace.iter_mut().zip(pass(column)) { + row[x] = i64::from(descale(value, CONST_BITS - PASS1_BITS + extra) as i32); + } + } + for (row, line) in workspace.iter().zip(output.chunks_mut(stride)) { + for (sample, value) in line[..N].iter_mut().zip(pass(*row)) { + *sample = range_limit(descale(value, CONST_BITS + PASS1_BITS + 3 + extra)); + } + } +} + +fn idct_block( + scale: usize, + coefficients: &[i16; 64], + table: &[u16; 64], + dc_only: bool, + stride: usize, + output: &mut [u16], +) { + if dc_only || scale == 1 { + // Both passes reduce to their shortcuts, one value for the block. + // (`_jpeg_idct_1x1` descales by 3 only; the bit of `PASS1_BITS` that + // the larger sizes carry is even, so the rounding agrees.) + let dc = i64::from(coefficients[0]) * i64::from(table[0]); + let value = range_limit(descale(dc, 3)); + for line in output.chunks_mut(stride).take(scale) { + line[..scale].fill(value); + } + return; + } + match scale { + 8 => idct::<8>(coefficients, table, 0, pass8, stride, output), + 4 => idct::<4>(coefficients, table, 1, pass4, stride, output), + _ => idct::<2>(coefficients, table, 2, pass2, stride, output), + } +} + +/// Render whole block rows of a component: `coefficients` (and `nonzero`, the +/// blocks' AC masks, unless they no longer describe them) to their samples. +pub(super) fn render_rows( + component: &Component, + coefficients: &[i16], + nonzero: Option<&[u64]>, + table: &[u16; 64], + output: &mut [u16], +) { + let scale = component.dct_scale; + let blocks_wide = usize::from(component.block_size.width); + let stride = blocks_wide * scale; + for (i, block) in coefficients.chunks_exact(64).enumerate() { + let block: &[i16; 64] = block.try_into().unwrap(); + let dc_only = match nonzero { + Some(masks) => masks[i] == 0, + None => block[1..].iter().all(|&c| c == 0), + }; + let at = (i / blocks_wide) * stride * scale + (i % blocks_wide) * scale; + idct_block(scale, block, table, dc_only, stride, &mut output[at..]); + } +} + +/// Upsample, colour-convert and interleave the planes. +pub(super) fn compute_image( + components: &[Component], + mut planes: Vec>, + output_size: Dimensions, + color_transform: ColorTransform, +) -> Result> { + if planes.is_empty() || planes.iter().any(Vec::is_empty) { + return Err(Error::Format("not all components have data".to_owned())); + } + let width = usize::from(output_size.width); + let height = usize::from(output_size.height); + + if let [component] = components { + let stride = usize::from(component.block_size.width) * component.dct_scale; + let mut plane = planes.remove(0); + if stride != width { + for y in 1..height { + plane.copy_within(y * stride..y * stride + width, y * width); + } + } + plane.truncate(width * height); + return Ok(plane); + } + + // The same refusals as at 8 bits. + choose_color_convert_func(components.len(), color_transform)?; + let convert: fn(&mut [u16]) = match color_transform { + ColorTransform::YCbCr => |line| line.chunks_exact_mut(3).for_each(ycc_to_rgb), + // As at 8 bits, the output is CMYK with 0 for no ink where the file + // (Adobe's convention) has 0 for full ink: the complement of what + // libjpeg returns, and for the CMY of YCCK that is the RGB. + ColorTransform::YCCK => |line| { + line.chunks_exact_mut(4).for_each(|pixel| { + ycc_to_rgb(&mut pixel[..3]); + pixel[3] = complement(pixel[3]); + }) + }, + ColorTransform::CMYK => |line| line.iter_mut().for_each(|s| *s = complement(*s)), + _ => |_| {}, + }; + + let h_max = max_factor(components, |c| c.horizontal_sampling_factor); + let v_max = max_factor(components, |c| c.vertical_sampling_factor); + let n = components.len(); + let mut image = vec![0u16; width * height * n]; + // An expanded row can run past the output by less than one group (of 4). + let mut line = vec![0u16; width + 4]; + for (y, row) in image.chunks_exact_mut(width * n).enumerate() { + for (i, (component, plane)) in components.iter().zip(&planes).enumerate() { + let h = h_max / usize::from(component.horizontal_sampling_factor); + let v = v_max / usize::from(component.vertical_sampling_factor); + let samples = upsample_row(component, plane, (h, v), y, width, &mut line); + for (pixel, &sample) in row.chunks_exact_mut(n).zip(samples) { + pixel[i] = sample; + } + } + convert(row); + } + Ok(image) +} + +fn max_factor(components: &[Component], factor: fn(&Component) -> u8) -> usize { + usize::from(components.iter().map(factor).max().unwrap_or(1)) +} + +/// Row `y` of the component at full size: a row of its plane, or `line`, +/// filled. The expansion factors are whole (`Upsampler::new` has refused the +/// frame otherwise). +fn upsample_row<'a>( + component: &Component, + plane: &'a [u16], + (h, v): (usize, usize), + y: usize, + width: usize, + line: &'a mut [u16], +) -> &'a [u16] { + let stride = usize::from(component.block_size.width) * component.dct_scale; + let w = usize::from(component.size.width); + let rows = usize::from(component.size.height); + let row = |r: usize| &plane[r * stride..r * stride + w]; + let near = (y / v).min(rows - 1); + // The second-nearest row of a 2:1 vertical expansion, inside the image. + let far = if y % 2 == 1 { + (near + 1).min(rows - 1) + } else { + near.saturating_sub(1) + }; + // libjpeg has no fancy upsampling at 1/8 scale. + let fancy = component.dct_scale > 1; + let out = &mut line[..width.div_ceil(h) * h]; + let last = w - 1; + match (h, v) { + (1, 1) => return &row(near)[..width.min(w)], + (2, 1) if fancy && w > 2 => { + let sample = row(near).iter().map(|&s| u32::from(s)); + expand(sample, out, |c, left, right| { + (((3 * c + left + 1) >> 2), ((3 * c + right + 2) >> 2)) + }); + } + (1, 2) if fancy => { + let bias = 1 + (y % 2) as u32; + for ((o, &n), &f) in out.iter_mut().zip(row(near)).zip(row(far)) { + *o = ((3 * u32::from(n) + u32::from(f) + bias) >> 2) as u16; + } + } + (2, 2) if fancy && w > 2 => { + let columns = row(near).iter().zip(row(far)); + let sums = columns.map(|(&n, &f)| 3 * u32::from(n) + u32::from(f)); + expand(sums, out, |c, left, right| { + (((3 * c + left + 8) >> 4), ((3 * c + right + 7) >> 4)) + }); + } + _ => { + let s = row(near); + for (x, group) in out.chunks_exact_mut(h).enumerate() { + group.fill(s[x.min(last)]); + } + } + } + &out[..width] +} + +/// Two outputs for each input, from it and its neighbours. At the ends the +/// missing neighbour is the input itself, which weights it fully. +#[inline(always)] +fn expand( + input: impl Iterator, + output: &mut [u16], + filter: impl Fn(u32, u32, u32) -> (u32, u32), +) { + let mut input = input.fuse(); + let Some(mut current) = input.next() else { + return; + }; + let mut left = current; + for pair in output.chunks_exact_mut(2) { + let right = input.next().unwrap_or(current); + let (a, b) = filter(current, left, right); + pair[0] = a as u16; + pair[1] = b as u16; + left = current; + current = right; + } +} + +fn complement(sample: u16) -> u16 { + (MAX - i32::from(sample)) as u16 +} + +/// jdcolor.c's fixed-point conversion, at 12 bits. +fn ycc_to_rgb(pixel: &mut [u16]) { + const SCALE: u32 = 16; + const HALF: i32 = 1 << (SCALE - 1); + // `x * 2^16`, rounded. + const FIX_1_40200: i32 = 91881; + const FIX_1_77200: i32 = 116130; + const FIX_0_71414: i32 = 46802; + const FIX_0_34414: i32 = 22554; + let y = i32::from(pixel[0]); + let cb = i32::from(pixel[1]) - CENTRE; + let cr = i32::from(pixel[2]) - CENTRE; + let r = y + ((FIX_1_40200 * cr + HALF) >> SCALE); + let g = y + ((HALF - FIX_0_34414 * cb - FIX_0_71414 * cr) >> SCALE); + let b = y + ((FIX_1_77200 * cb + HALF) >> SCALE); + pixel[0] = r.clamp(0, MAX) as u16; + pixel[1] = g.clamp(0, MAX) as u16; + pixel[2] = b.clamp(0, MAX) as u16; +} diff --git a/src/decode/error.rs b/src/decode/error.rs index 7c96324..4153471 100644 --- a/src/decode/error.rs +++ b/src/decode/error.rs @@ -18,11 +18,14 @@ pub type Result = result::Result; pub enum UnsupportedFeature { /// Hierarchical JPEG. Hierarchical, - /// JPEG using arithmetic entropy coding instead of Huffman coding. + /// Lossless JPEG using arithmetic entropy coding (SOF11). Arithmetic-coded + /// DCT frames (SOF9, SOF10) are supported. ArithmeticEntropyCoding, - /// Sample precision in bits. 8 bit sample precision is what is currently supported in non-lossless coding process. + /// Sample precision in bits. 8 and 12 bits are supported in DCT frames, 2 to 16 in lossless ones; + /// [`Decoder::decode_planar`](crate::decode::Decoder::decode_planar) returns 8-bit planes only. SamplePrecision(u8), - /// Number of components in an image. 1, 3 and 4 components are currently supported. + /// Number of components in an image. 1, 3 and 4 components are currently supported, and 2 in + /// lossless frames. ComponentCount(u8), /// An image can specify a zero height in the frame header and use the DNL (Define Number of /// Lines) marker at the end of the first scan to define the number of lines in the frame. @@ -92,6 +95,11 @@ pub enum Warning { /// marker (or the end of the scan). libjpeg-turbo: "Corrupt JPEG data: /// bad Huffman code". BadHuffmanCode, + /// An arithmetic-coded coefficient ran past the end of its block or out of + /// range. Nothing more of the segment is decoded, up to the next restart + /// marker (or the end of the scan). libjpeg-turbo: "Corrupt JPEG data: bad + /// arithmetic code". + BadArithmeticCode, /// The marker at a restart boundary was not the restart marker due there; /// the decoder resynchronised as libjpeg-turbo's `jpeg_resync_to_restart` /// does. libjpeg-turbo: "Corrupt JPEG data: found marker 0x.. instead of @@ -125,6 +133,7 @@ impl fmt::Display for Warning { Warning::Truncated => "premature end of JPEG data", Warning::SegmentEndedEarly => "premature end of data segment", Warning::BadHuffmanCode => "bad Huffman code", + Warning::BadArithmeticCode => "bad arithmetic code", Warning::RestartMarkerMismatch => "restart marker missing or out of sequence", Warning::ExtraneousBytes => "extraneous bytes before marker", Warning::MissingScan => "no scan data for a component", diff --git a/src/decode/mod.rs b/src/decode/mod.rs index c8e2f95..306c56c 100644 --- a/src/decode/mod.rs +++ b/src/decode/mod.rs @@ -6,7 +6,9 @@ #![deny(unsafe_code)] #![cfg_attr(feature = "platform_independent", forbid(unsafe_code))] -pub use decoder::{ColorTransform, Decoder, ImageInfo, PixelFormat, PlanarComponent, PlanarImage}; +pub use decoder::{ + ColorTransform, Decoder, FrameHeader, ImageInfo, PixelFormat, PlanarComponent, PlanarImage, +}; pub use error::{Error, UnsupportedFeature, Warning}; pub use parser::CodingProcess; @@ -14,6 +16,7 @@ use alloc::boxed::Box; #[cfg(not(feature = "platform_independent"))] mod arch; +mod arith; mod decoder; mod error; mod huffman; diff --git a/src/decode/parser.rs b/src/decode/parser.rs index 060f0e3..27b31f3 100644 --- a/src/decode/parser.rs +++ b/src/decode/parser.rs @@ -1,3 +1,4 @@ +use crate::decode::arith::Conditioning; use crate::decode::error::{Error, Result, UnsupportedFeature}; use crate::decode::huffman::{HuffmanTable, HuffmanTableClass}; use crate::decode::marker::Marker; @@ -116,6 +117,49 @@ pub struct IccChunk { } impl FrameInfo { + /// A 12-bit lossy frame, whose samples are output as `u16`. + pub(crate) fn is_twelve_bit(&self) -> bool { + self.coding_process != CodingProcess::Lossless && self.precision > 8 + } + + /// Whether the frame's quantized coefficients are all kept and the planes + /// rendered from them once the last scan is in. Baseline and extended + /// Huffman frames of 8 bits stream through the worker instead. + pub(crate) fn stores_coefficients(&self) -> bool { + self.coding_process == CodingProcess::DctProgressive || self.renders_late() + } + + /// The part of `stores_coefficients` that renders a component only at the + /// end, with the quantization table latched at its first scan. + pub(crate) fn renders_late(&self) -> bool { + self.coding_process != CodingProcess::Lossless + && (self.entropy_coding == EntropyCoding::Arithmetic || self.is_twelve_bit()) + } + + /// The blocks, across and down, of component `i` that carry samples of the + /// image: what a scan of that component alone codes (A.2.2). + pub(crate) fn image_blocks(&self, i: usize) -> (u16, u16) { + let max = |factor: fn(&Component) -> u8| { + usize::from(self.components.iter().map(factor).max().unwrap_or(1)) + }; + let blocks = |size: u16, factor: u8, max: usize| { + (usize::from(size) * usize::from(factor)).div_ceil(max * 8) as u16 + }; + let c = &self.components[i]; + ( + blocks( + self.image_size.width, + c.horizontal_sampling_factor, + max(|c| c.horizontal_sampling_factor), + ), + blocks( + self.image_size.height, + c.vertical_sampling_factor, + max(|c| c.vertical_sampling_factor), + ), + ) + } + pub(crate) fn update_idct_size(&mut self, idct_size: usize) -> Result<()> { for component in &mut self.components { component.dct_scale = idct_size; @@ -459,13 +503,18 @@ pub fn parse_sos(reader: &mut R, frame: &FrameInfo) -> Result> 4; let ac_table_index = byte & 0x0f; - if dc_table_index > 3 || (frame.is_baseline && dc_table_index > 1) { + // Arithmetic conditioning tables have sixteen destinations (B.2.4.3). + let last_table = match frame.entropy_coding { + EntropyCoding::Huffman => 3, + EntropyCoding::Arithmetic => 15, + }; + if dc_table_index > last_table || (frame.is_baseline && dc_table_index > 1) { return Err(Error::Format(format!( "invalid dc table index {}", dc_table_index ))); } - if ac_table_index > 3 || (frame.is_baseline && ac_table_index > 1) { + if ac_table_index > last_table || (frame.is_baseline && ac_table_index > 1) { return Err(Error::Format(format!( "invalid ac table index {}", ac_table_index @@ -742,6 +791,37 @@ pub fn parse_dht( Ok((dc_tables, ac_tables)) } +// Section B.2.4.3 +/// Read a DAC segment into `conditioning`, with libjpeg's checks (`get_dac`, +/// jdmarker.c): the destination and the order of a DC table's bounds. A `Kx` +/// outside 1..=63 only moves the split between the two bin sets. +pub(crate) fn parse_dac(reader: &mut R, conditioning: &mut Conditioning) -> Result<()> { + let length = read_length(reader, DAC)?; + if !length.is_multiple_of(2) { + return Err(Error::Format("invalid length in DAC".to_owned())); + } + + for _ in 0..length / 2 { + let byte = read_u8(reader)?; + let value = read_u8(reader)?; + let index = usize::from(byte & 0x0f); + match byte >> 4 { + 0 => { + let (low, high) = (value & 0x0f, value >> 4); + if low > high { + return Err(Error::Format(format!("invalid value {} in DAC", value))); + } + conditioning.dc[index] = (low, high); + } + 1 => conditioning.ac[index] = value, + class => { + return Err(Error::Format(format!("invalid class {} in DAC", class))); + } + } + } + Ok(()) +} + // Section B.2.4.4 pub fn parse_dri(reader: &mut R) -> Result { let length = read_length(reader, DRI)?; diff --git a/tests/damaged_streams.rs b/tests/damaged_streams.rs index 4cb7381..040c2db 100644 --- a/tests/damaged_streams.rs +++ b/tests/damaged_streams.rs @@ -302,11 +302,16 @@ fn sof_stream(sof: u8, comps: &[(u8, u8)], scans: &[&[u8]]) -> Vec { /// A 2-component frame (grey + alpha, as JPEG-in-TIFF can carry) must be a /// clean `Unsupported(ComponentCount(2))` from every entry point, never a -/// panic -- including `info()`, whose fallback arms were `panic!()`. +/// panic -- including `info()`, whose fallback arms were `panic!()`. (The one +/// exception, a lossless frame of two full-size components, is in +/// `extended_modes.rs`.) #[test] fn two_component_frames_are_a_clean_error() { for sof in [0xC0u8, 0xC1, 0xC2, 0xC3] { for comps in [[(1u8, 1u8), (1, 1)], [(2, 2), (1, 1)], [(1, 1), (2, 1)]] { + if sof == 0xC3 && comps == [(1, 1), (1, 1)] { + continue; + } let data = sof_stream(sof, &comps, &[&[1, 2]]); let check = |r: Result<(), Error>| match r { Err(Error::Unsupported(UnsupportedFeature::ComponentCount(2))) => {} diff --git a/tests/extended_modes.rs b/tests/extended_modes.rs new file mode 100644 index 0000000..39a8242 --- /dev/null +++ b/tests/extended_modes.rs @@ -0,0 +1,387 @@ +//! 12-bit DCT frames (SOF1, SOF2), arithmetic coding (SOF9, SOF10, DAC) and +//! two-component lossless frames (SOF3, as in DNG). +//! +//! The streams in `fixtures/modes` were written by libjpeg-turbo 3.1.0 from +//! synthetic pictures, and the expected hashes are of what it decodes them to: +//! both with `tools/generate_modes_libjpeg.c`. + +use rusty_jpeg::decode::{CodingProcess, Decoder, Error, PixelFormat, UnsupportedFeature, Warning}; + +macro_rules! fixture { + ($name:literal) => { + ( + $name, + include_bytes!(concat!("fixtures/modes/", $name, ".jpg")) as &[u8], + ) + }; +} + +const FIXTURES: [(&str, &[u8]); 12] = [ + fixture!("lossless12_pair_scans"), + fixture!("lossless14_pair"), + fixture!("prog12_420_arithmetic"), + fixture!("prog12_422_huffman"), + fixture!("prog8_422_arithmetic"), + fixture!("prog8_422_huffman"), + fixture!("seq12_420_huffman"), + fixture!("seq12_440_separate"), + fixture!("seq12_grey_arithmetic"), + fixture!("seq12_ycck"), + fixture!("seq8_420_arithmetic"), + fixture!("seq8_420_huffman"), +]; + +fn stream(name: &str) -> &'static [u8] { + FIXTURES.iter().find(|f| f.0 == name).unwrap().1 +} + +fn hash(samples: impl IntoIterator) -> u64 { + samples + .into_iter() + .flat_map(u16::to_le_bytes) + .fold(0xcbf29ce484222325, |h, byte| { + (h ^ u64::from(byte)).wrapping_mul(0x100000001b3) + }) +} + +/// Decode a complete stream, refusing any repair. +fn samples(bytes: &[u8]) -> Vec { + let mut d = Decoder::new(bytes); + d.set_strict(true); + d.decode_u16().unwrap() +} + +#[test] +fn wide_modes_match_libjpeg_turbo_exactly() { + for (name, want) in [ + ("seq12_420_huffman", 0x6003099946f83b7b), + ("prog12_420_arithmetic", 0x6003099946f83b7b), + ("prog12_422_huffman", 0xbe2837924bcde433), + ("seq12_440_separate", 0x05a09438ce84443d), + ("seq12_grey_arithmetic", 0xa690aee45a7369a1), + ("lossless14_pair", 0x8203cc02383bc24e), + ("lossless12_pair_scans", 0x9e7427b33cbbfb3a), + ] { + assert_eq!(hash(samples(stream(name))), want, "{name}"); + } + // Four components come out complemented (see `twelve::compute_image`). + let cmyk = samples(stream("seq12_ycck")); + assert_eq!(hash(cmyk.iter().map(|s| 4095 - s)), 0x194e03e3981d20e2); +} + +/// An arithmetic-coded file holds the same coefficients as its Huffman twin. +#[test] +fn arithmetic_matches_huffman() { + for kind in ["seq8_420", "prog8_422"] { + let huffman = samples(stream(&format!("{kind}_huffman"))); + let arithmetic = samples(stream(&format!("{kind}_arithmetic"))); + assert!(huffman == arithmetic, "{kind}"); + + let planar = |coding: &str| { + let mut d = Decoder::new(stream(&format!("{kind}_{coding}"))); + d.set_single_threaded(true); + let image = d.decode_planar().unwrap(); + image.into_planes() + }; + assert!(planar("huffman") == planar("arithmetic"), "{kind} planar"); + } +} + +#[test] +fn headers_and_sample_layout() { + let mut d = Decoder::new(stream("seq12_420_huffman")); + d.read_info().unwrap(); + let h = d.frame_header().unwrap(); + assert_eq!((h.width, h.height, h.components), (35, 23, 3)); + assert_eq!((h.precision, h.bytes_per_sample()), (12, 2)); + assert_eq!(h.coding_process, CodingProcess::DctSequential); + assert!(!h.arithmetic_coding); + assert_eq!(d.info().unwrap().pixel_format, PixelFormat::RGB24); + let wide = samples(stream("seq12_420_huffman")); + assert_eq!(wide.len(), 35 * 23 * 3); + assert!(wide.iter().all(|&s| s <= 4095)); + // `decode` gives the same samples as native-endian bytes. + let bytes: Vec = wide.iter().flat_map(|s| s.to_ne_bytes()).collect(); + assert_eq!(d.decode().unwrap(), bytes); + + let mut d = Decoder::new(stream("seq12_grey_arithmetic")); + d.read_info().unwrap(); + assert_eq!(d.info().unwrap().pixel_format, PixelFormat::L16); + assert!(d.frame_header().unwrap().arithmetic_coding); + + let mut d = Decoder::new(stream("seq8_420_arithmetic")); + let eight = d.decode().unwrap(); + assert_eq!(eight.len(), 35 * 23 * 3); + assert_eq!(d.frame_header().unwrap().bytes_per_sample(), 1); + let widened: Vec = eight.iter().map(|&b| b.into()).collect(); + assert_eq!(samples(stream("seq8_420_arithmetic")), widened); + + // Two components have no pixel format; the samples of a row interleave + // into one row of the CFA tile. + let mut d = Decoder::new(stream("lossless14_pair")); + d.read_info().unwrap(); + assert_eq!(d.info(), None); + let h = d.frame_header().unwrap(); + assert_eq!((h.width, h.height, h.components), (24, 16, 2)); + assert_eq!(h.precision, 14); + assert_eq!(d.decode_u16().unwrap().len(), 48 * 16); +} + +/// Reduced sizes: the DC of each block at 1/8, and the right dimensions. +#[test] +fn scaled_twelve_bit() { + for (w, h) in [(5, 3), (9, 6), (18, 12), (35, 23)] { + let mut d = Decoder::new(stream("seq12_420_huffman")); + assert_eq!(d.scale(w, h).unwrap(), (w, h)); + let out = d.decode_u16().unwrap(); + assert_eq!(out.len(), usize::from(w) * usize::from(h) * 3); + assert!(out.iter().all(|&s| s <= 4095)); + } +} + +/// Where the segment with this marker starts (at the marker). +fn find(bytes: &[u8], marker: u8) -> usize { + bytes + .windows(2) + .position(|w| w == [0xFF, marker]) + .expect("marker present") +} + +fn with_sof(name: &str, from: u8, change: impl Fn(&mut [u8])) -> Vec { + let mut bytes = stream(name).to_vec(); + let at = find(&bytes, from); + change(&mut bytes[at..]); + bytes +} + +fn unsupported(bytes: &[u8]) -> UnsupportedFeature { + match Decoder::new(bytes).decode() { + Err(Error::Unsupported(feature)) => feature, + other => panic!("{:?}", other.map(|v| v.len())), + } +} + +#[test] +fn refusals() { + // Baseline is 8-bit (B.2.2). + let bytes = with_sof("seq12_420_huffman", 0xC1, |sof| sof[1] = 0xC0); + assert!(matches!( + Decoder::new(&bytes[..]).decode(), + Err(Error::Format(_)) + )); + // Other lossy precisions do not exist. + for precision in [0, 1, 2, 7, 9, 10, 11, 13, 16, 255] { + let bytes = with_sof("seq12_420_huffman", 0xC1, |sof| sof[4] = precision); + assert!(Decoder::new(&bytes[..]).decode().is_err(), "{precision}"); + } + // Lossless arithmetic. + let bytes = with_sof("lossless14_pair", 0xC3, |sof| sof[1] = 0xCB); + assert_eq!( + unsupported(&bytes), + UnsupportedFeature::ArithmeticEntropyCoding + ); + // Two components: lossless and full-size only. + let bytes = with_sof("lossless14_pair", 0xC3, |sof| sof[11] = 0x21); + assert_eq!(unsupported(&bytes), UnsupportedFeature::ComponentCount(2)); + for sof in [0xC1, 0xC2, 0xC9, 0xCA] { + let bytes = with_sof("lossless12_pair_scans", 0xC3, |s| s[1] = sof); + assert_eq!(unsupported(&bytes), UnsupportedFeature::ComponentCount(2)); + } + // 12-bit planes. + let mut d = Decoder::new(stream("seq12_420_huffman")); + assert!(matches!( + d.decode_planar(), + Err(Error::Unsupported(UnsupportedFeature::SamplePrecision(12))) + )); +} + +/// `bytes` with a segment inserted after SOI. +fn insert(bytes: &[u8], marker: u8, body: &[u8]) -> Vec { + let mut out = bytes[..2].to_vec(); + out.extend_from_slice(&[0xFF, marker]); + out.extend_from_slice(&(body.len() as u16 + 2).to_be_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(&bytes[2..]); + out +} + +#[test] +fn dac_segments() { + let base = stream("prog8_422_arithmetic"); + let want = samples(base); + // The defaults spelled out, and settings of tables the scans do not use. + for body in [ + &[][..], + &[0x00, 0x10, 0x10, 0x05], + &[0x0F, 0xF0, 0x1F, 0x00, 0x05, 0xFF, 0x12, 0xFF], + ] { + assert!(samples(&insert(base, 0xCC, body)) == want, "{body:?}"); + } + // In a Huffman file it is irrelevant. + let huffman = stream("seq8_420_huffman"); + assert!(samples(&insert(huffman, 0xCC, &[0x00, 0x21])) == samples(huffman)); + // Odd length, L > U, a class other than 0 and 1. + for body in [ + &[0x00][..], + &[0x00, 0x10, 0x10], + &[0x00, 0x01], + &[0x20, 0x10], + ] { + assert!( + matches!( + Decoder::new(&insert(base, 0xCC, body)[..]).decode(), + Err(Error::Format(_)) + ), + "{body:?}" + ); + } + // Other parameters than the file was coded with decode to something else, + // or at least do not fail. + for (a, b) in [(0xF0, 0x3F), (0xFF, 0x00), (0x00, 0xFF)] { + let _ = decode(&insert(base, 0xCC, &[0x00, a, 0x01, a, 0x10, b, 0x11, b])); + } +} + +/// A bounded decode of a hostile stream: it may fail, and may not panic. +fn decode(bytes: &[u8]) -> Result<(Vec, Vec), Error> { + let mut d = Decoder::new(bytes); + d.set_max_decoding_buffer_size(1 << 20); + d.set_single_threaded(true); + let samples = d.decode_u16()?; + Ok((samples, d.warnings().to_vec())) +} + +#[test] +fn truncation_anywhere() { + for (name, bytes) in FIXTURES { + let whole = samples(bytes).len(); + let first_scan = find(bytes, 0xDA); + let header = 2 + usize::from(bytes[first_scan + 3]); + for cut in 0..bytes.len() { + match decode(&bytes[..cut]) { + // Anything with scan data decodes to a full image and says + // what is wrong with it. + Ok((out, warnings)) => { + assert_eq!(out.len(), whole, "{name} cut at {cut}"); + assert!(warnings.contains(&Warning::Truncated), "{name} {cut}"); + assert!(cut > first_scan + header, "{name} {cut}"); + } + Err(Error::UnexpectedEof) => { + assert!(cut <= first_scan + header, "{name} cut at {cut}") + } + Err(error) => panic!("{name} cut at {cut}: {error}"), + } + let mut strict = Decoder::new(&bytes[..cut]); + strict.set_strict(true); + assert!( + matches!(strict.decode(), Err(Error::UnexpectedEof)), + "{name} {cut}" + ); + } + // Only the EOI gone: every sample is there. + let (out, _) = decode(&bytes[..bytes.len() - 2]).unwrap(); + assert!(out == samples(bytes), "{name} without EOI"); + } +} + +#[test] +fn bit_flips_anywhere() { + for (name, bytes) in FIXTURES { + let whole = samples(bytes).len(); + let first_scan = find(bytes, 0xDA); + let mut recovered = 0; + for at in 2..bytes.len() { + for bit in [(at * 5) % 8, (at * 5 + 3) % 8] { + let mut damaged = bytes.to_vec(); + damaged[at] ^= 1 << bit; + if let Ok((out, _)) = decode(&damaged) { + if at > first_scan + 14 { + assert_eq!(out.len(), whole, "{name} at {at}"); + recovered += 1; + } + } + } + } + assert!(recovered > 0, "{name}"); + } +} + +/// Every frame type over every fixture's scans and tables, and over zeros. +#[test] +fn mismatched_frame_types() { + for (_, bytes) in FIXTURES { + let at = [0xC0, 0xC1, 0xC2, 0xC3, 0xC9, 0xCA] + .into_iter() + .find_map(|m| bytes.windows(4).position(|w| w[..3] == [0xFF, m, 0])) + .unwrap(); + for sof in (0xC0..=0xCF).filter(|m| ![0xC4, 0xC8, 0xCC].contains(m)) { + for precision in [8, 12, 16] { + let mut changed = bytes.to_vec(); + changed[at + 1] = sof; + changed[at + 4] = precision; + let _ = decode(&changed); + let scan = find(&changed, 0xDA) + 14; + for fill in [0x00, 0xFE, 0xFF, 0xAA] { + let mut filled = changed.clone(); + filled[scan..].fill(fill); + let _ = decode(&filled); + } + } + } + } +} + +/// The size limit holds before anything is allocated from the header, and +/// counts a 12-bit sample as the two bytes it is. +#[test] +fn allocation_is_bounded() { + for name in ["seq12_420_huffman", "seq8_420_arithmetic"] { + for marker in [0xC1, 0xC9] { + let mut bytes = stream(name).to_vec(); + let Some(at) = bytes + .windows(4) + .position(|w| w[..3] == [0xFF, marker, 0] && w[3] == 17) + else { + continue; + }; + bytes[at + 5..at + 9].fill(0xFF); + assert!(matches!(decode(&bytes), Err(Error::Format(_))), "{name}"); + } + } + let limited = |limit| { + let mut d = Decoder::new(stream("seq12_grey_arithmetic")); + d.set_max_decoding_buffer_size(limit); + d.decode().map(|v| v.len()) + }; + assert!(limited(35 * 23 * 2 - 1).is_err()); + // The stored coefficients are bounded too: 5 x 3 blocks. + assert_eq!(limited(35 * 23 * 2).unwrap(), 35 * 23 * 2); +} + +/// Corrupt arithmetic data is reported, and refused in strict mode. +#[test] +fn bad_arithmetic_code_is_a_warning() { + let bytes = stream("prog12_420_arithmetic"); + let mut reported = 0; + for seed in 0..40u32 { + // Noise (free of FF) over the tail of the file, in its last scans. + let mut damaged = bytes.to_vec(); + let end = damaged.len() - 2; + let mut state = seed; + for byte in &mut damaged[end - 300..end] { + state = state.wrapping_mul(1103515245).wrapping_add(12345); + *byte = (state >> 16) as u8 & 0x7F; + } + let Ok((out, warnings)) = decode(&damaged) else { + continue; + }; + assert_eq!(out.len(), 35 * 23 * 3); + if warnings.contains(&Warning::BadArithmeticCode) { + reported += 1; + let mut strict = Decoder::new(&damaged[..]); + strict.set_strict(true); + assert!(matches!(strict.decode(), Err(Error::Format(_)))); + } + } + assert!(reported > 0); +} diff --git a/tests/fixtures/modes/lossless12_pair_scans.jpg b/tests/fixtures/modes/lossless12_pair_scans.jpg new file mode 100644 index 0000000000000000000000000000000000000000..08082c9103687d6326d8c64748a1e60c3dfce525 GIT binary patch literal 1188 zcmV;V1Y7(6*#E--4h#Sg02l%Q5dZ-Z0RO}Q9RL6V0|5X70RR9100000000LF1_=rU z0|W~K|J?ut02u$;00;p900sa7`Tqdx;muuUO*>_(u&X*JI!HVC&U2Ay`{2A9pJ(j> z|Ikm03KNS7W}`Z&voK$d3ViqS-0iQZvG_I&(!2Ey|Iw})!z`dXEMFsMD(uLm)(o~- zy)$z>e8O2)%H-1T|I(5dQ%G)2+57 zwzhs-ao)unNpQ!qu@Q2GV9EagAD0S&YxnfF{{a8gy;|;P$}h^P>DD;HXgUoxXKQ0P zM%u9vg&)tt?*RYRwH9xrjoHe;(9&vJR&P;j4OzZ&A9!y^iUnBStT?p%Z~xY^Bg)@k z>dlrQnVV=Ch+*UR-LxlpDS0HdPJTQ1P1!qjqJXNW=`fy#U**jmoSCZpaZg?w9fS=#^6Rukr&7Frlh zwV)Ph{{U;@N*A59{{W{XCNkCGw(9wp{{a8etHV-@HS!JZ0@h{3mGr7l5YTXGiuZ>f zO)s3LlaN~_|I~Gy=r+vIFaOk}_Ngec`o8RP zwm6&_16}_BBbA9Z7slXMB$TJ1g6XgS)vV8d(Sa|7@Gjk!z*E=iR*SEV;+LmBiI+p$ zDh?Ze|JJ-wcmYyp6ILT3&C;lKE}OX0|5a60RaI4 z00000000LF1_=rU1PcNK00IBn00;pA00sa7`Tqd@?$TC&vI;6=#n?}R2np)AG-)oZ zM&THprSvAbwx9pd+~0;sx0gC|Y^v6)C0zlYx9>!ij6QLIDi{MjGQa8n(bX?jMPZ{6 zO8uU-;i#(slfu4ONcoU0YigyeH|I*nEEbKKR#38>BFQ-p}r_11Ichf@;Uy;wW zW`fc^dNBV0|I^!qSl8LE*s1n_BFLoNXIy=KP9hK$Xjc#C=b17g{{a8gaHVUh=xQi~ z=F!2UL^kj%tk1VUCH57|JU$He}UK`zTcge z$g7u-XRmk0zv&@h4M+rp6i-CXr~LoWubVzpM01$*PgfG?SqWhG^Ruq5uB1ZZ3M8q& zp`mO4(a{79$cZvR=C?St%*2&zX|YAMMq5PqT_>iwD2^Jn{{a8ey|uBkLm9F>lP0~w z5?I9yiWXGl5Jm~U;qlFwrmDKX|I@rBNX|i6A}~r|4YWy9qL6hodts<|UUE7QX9CHF zfB)364&*IRag#=)EvMn1<$@aj0JYNwRQ~|GQQI44CCabg|J9jDqXZ$uV$*U3;xxnx zzOO!?ClRm@M#fg^ZjDO6|JKggF;Mlt@O8IR=PzREW2-A&m`H?h&nV)z8g2l+-~ZWG Cq)6NV literal 0 HcmV?d00001 diff --git a/tests/fixtures/modes/lossless14_pair.jpg b/tests/fixtures/modes/lossless14_pair.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3f670a0384a0da85823d930032bca0b8bc90811b GIT binary patch literal 1339 zcmV-B1;qOQ*#E--4h{ei02l%Q5dZ-Z0RO}Q9{>OX0|5X70RaI300000000UL2@DMg z1qTiW0t5fr015&C00962008;_0RI4={{Yv(``wo{q}6sT^q9`aY1k|_G^n*$G2+6t z*ev2t;GhI4(4aa%4>P|jh2uEr(Ye}O5p7tWKbv&;1ZJ-ybqy^que6~+{k6{^DYTnE z-+8uA{*+L(jX0@q(3D(^)9JX+nypj(s~a=btHF7aADXU{1)-pP-CggWEtc(~KJ6;U zi}D{tT)43OKu9)JJPiO1rEi|3{W(^L4?ZGDPn<5OWt4}g9>Y7b23d;&oyd#z+0M^g zS6cC=MW_WERx_+ZR5Tt6*!A;b_E=9d0r%#%c7ArMXETp+E1wZn!M&AyQ|T~p%(#Gn zrXLa1!vuI8aj1=y!4WGdVj+0&--nO!0$*j3^yy8Z^kJ)1`ceUYPw*Q1A{^gy^w9W= z7<%lZ@v2=N7fE}g@&h_1h%D1>q=2_d^&%j{a)&2|A;qC=n$p_)GsV|vZOmDY>GEt- zPzP-kTuXW@20m?j6lj(;TwIB|^C(+WlEHEyQ~?4!c&%Pz76@2~C==)Xe!TM^CYiOi z5Z1m$T^4@ku+bswHcVg6Lj1Z1-W%%MdOZc4UD2RmT&o_eGW5SYhbyYk z(>`wFbH<37`aGHOTor%22QuQUmkilr2vidnu4eY2OF&e<%oDqYO4;XyJsxT?dzm_x zgmaZ0;=E*~$-BvX9FmCLRIy4tNao2zyNu*h#;g*lvr7UpCXg<6{9uS3c&-E{yteyo zO#c9#mB%L84`sD-)k1P<9+{gLtKf`_;o5~?`po4dTT4p@td1Kdrywjz5`-@hBfXJ5 zh&`fcT#lep_xPnL2yubS1KwO5PJ?R-B1`dYRW`O*K8BOD%Sx#R$y$D(d8UR!3<#Vp zCPoY>d`+8Kb)YkiLf*NHPMDqMN|k(dwaQVkFu036?fp@7{{WWfOrnBFIAoXlL6$E= zuK`@IZQ_XKe3)&Qg|RGfbF}QEUN~yj+mrDKJXZ^#7*DRN^Tzf$SN93)?ydcB~4m0+OD_t_BZC9;YChIsAFn<05&H2 zAiFGQ2fE#MQt7(~bZVOvsq5qBrVG(A0BWICDeZ=CKixJEe#8a2WIF0uw^Zd-Pwm5` xT{(8x>q2tOOwq1aq4Nn`R}k{+9P8dQMv_VQiQ^b>ZXQvVn~R-5DOqoI|Ji@ucIW^A literal 0 HcmV?d00001 diff --git a/tests/fixtures/modes/prog12_420_arithmetic.jpg b/tests/fixtures/modes/prog12_420_arithmetic.jpg new file mode 100644 index 0000000000000000000000000000000000000000..113d9eb1d234ed494e85a78d179fe4def3c1beb7 GIT binary patch literal 2044 zcmb7Ec{J1u8~*)fky&I$V~jGka3y3J*>1*?r4)^&L@2scDoeI5F_Rl($&&1&P|?Uf zw2J5hCuGqD(@gxt#BO=XAgSzUO`ZeV_MzpYxta_*ys#U=CXyvI0O50Km-x zgkyjO0EIxdxCz)M;i7Oj3>Mv9lITc!r(F39XLrzNwl~W z0god{;3RQdA|Q0L2L?yL;Ru`lD*su3COP)Mw|H z=KdbKIorQwQwoNGZwiTSo({qx7J)1RfmURiS5}QYZ;pCE$cu@H!VdVHwphwIjt;)b zZ5vkDdE-PHd+aoN`f!7RrE-CsU&I>+P_{7QQ-y?Mk5|!4yWgK1)lp4s;tIQVESm}e z{N1;zZ7F>Rw`O7gGYblWWDw7?sgMc1`rMONM4b8C8llQFj=0V9ReG(ZUDI;5Ge*Wx zt>?z>9ag26D|6o^)-5|od7b$ENNs0+KGaDkcnPMKvnTb`On{^VSHqxprj^! zZ@q$id@mRKV_g#wRsGCeoAt+^tz@UP@Qi)#(_Fy3f$?y>-qb^X0?lkaMEvy;@(L1| zR^n(l)<4_(OsgK&=qdyf1(xMi@FX4DGGFCDF;TiAA$e4Dj%ELTFnNZwuOY--{^q&C zXlDqdXI&ZLTuMO621$KJ9JV zRMp$T>}bK4yI0B}_G#LyFX;t8xdPd8#W*2W);&z)c$dzshwN8@oGhu`P4_s~)ql#2 zD=yyfv>G+KK{qp^H1&;_@}98o*~QqdztaVqPF@-GtsDySvy%v19(EuTYO}K2a=xY+ zx6u3>E*J~Chh8l)f?R$~i_t0P=}SI3nO92m!{!MRAB$u2GL`6-J4TtZ_t!}A^Q_j= zS(hZ_x)3Nm=IE1|zy`k~tCekiojk1pg}{>!C|m4_Nx!F?cbUhG4O5!GW*u$5RB*i(O>VFzFQE45?5cJ) z*d=9tA$r7S z1{#_Qp9oAf*809TwQ7zpolnT{n-ID|aq6fE?~o?5%KUr}=MHK{uZp_f@ngN8>%JlK z9cEe3D($^Nv$`s|_lGEvWtg<#NUhe|M%^*dxP6mZRBHQ?T|_Yy+pHZU!0P1Ookx)t+9suSkNiAzgJ2GqmjbXDZ() z?r!Q7J=dRkOF8}H1@3fyc&<~NLk@ZSD9T{Z^9qki?;DZDkW4vO+=0q?kw=!Q!;gKK zcX;j7g51eiw?LIe-w$|BU)iC#i6I{^2y z*{_F)M>Jl|J}fA*kV-Geo(;c{@`oJawRqO&lTE=~sK1RB?z?~wJY1)EA-fu_^F?#K}kdb8H##fPy>Byuy`bl>Q0ajp(W@y~Iv?)a)FeB2) z>aaRk?&UWUdcGzW?_p-Pd%EzkZ|G>~uX2g$mFOsG zBCnowUl6c1nixGmYF~ukPF5MuEE>Pwp-eN$un!rT-rXIy-r8vy#acOte{rbxSR-;A zCA)T~gJ)YIK`K9)h{w+SH}e4~000=K)?Po;pAuv%S20Ylhx%#h5euarCd9siuDnpO z2O*Uy@UW%MNRa7MWD!R8^3 zw5_uWT#xoYj$+u!jE#{fXbrtrK|1VgX!8A2<1%Kad(ZXvo>ep=efOTN;FmI}O7aEm zudBR{6UU&d6Dz-j8BeKLmAjoeAd}J>hGk}uN}fic^1MH@AAP8g3D7>@Cn!`qbaWoi zuy{NoI+jWERI0-4n?-ryn|}a) Ce2HTK literal 0 HcmV?d00001 diff --git a/tests/fixtures/modes/prog12_422_huffman.jpg b/tests/fixtures/modes/prog12_422_huffman.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a0935704a653cac8f3c26a8a3b9ad585eca39828 GIT binary patch literal 2467 zcmb7Fc{o%J7r%4IEX=4oW5zNhV@5UhAt5n57|D_)OOzx;*+ywqN()&gS!>?1X7GNL zbxI{FjncxavX-(m(u5Qt+jr^xdiwV}_xy36d!BpF@0{OR7CRR|0MHh;EgL`}0003$ zz+w+z2_QjmNnw$I6@^8iBqUH$7z`SVm%`(5QaGIS3L+%Eg0KRIgJdCs42eu8<5$Yb z%aY`YBr<8q2?7cKBY~1cp(IJtIBC-VEsGBU0v?b9Xh;MV00{^r0kPN!Pyhf#E}{J` zl2QN$3!-3~0%FPb+W@~{q|jKLGFaLRsTR@ezNhGwp)d?GOt_OV8osI_Z@tR| z5TM|FP_r&t;Ydo5l&0XMOVb7mV5q$Bi7nUCZ8Efm(@y5T98qN?-|-r}7@R#Wa962a zJu`q<@&2=}X~B@Y4+Epu8a;sG_r=9M`!T=nMB?r=N@-GWSI9ArWy@z?7t_60h&8fm z3Jn@`<@Mb2edG3%SHnKt&Rg7#gORiH4DUlnL zZ&7=lT}RW9sm!r{`AM&6m4FlFyFG=QV0Lg~)$JowATTQ(cYxS2!pyI^O>%m2```8yfpG#X>(3`4TZGt4J zL{f*p;1QP{X<$sq{+j8R$2{aOxRGGP!5$XeX1N%YnFX}=tM}b$=Lns!_6yyqO;IAJ z>7Zi5r9MtpU}!{%P~};|zI_AHzN2N6^~Mh~)Hl7f-1+zzF?Dp8Mr3eGX!L?N0yP^S z-?gzd8`!&ZyPAo6gerZPZ`IpUvjDT1+aARw^f*OS62Hx;n`py%mO|zKBYwkT@!Jmc zhTSfae59T^Z6oEmY4lNVp{;>!ko1U*aT!a<*#Y%Yt=tY@y2lb9Ph?-jpU7^QEB{*M zp#~G#tDFLszKL?9I#4L>!ok>>J)0egQHC6}!%>tiH z9L`N2pO+n9pYWA}3U6o}p5OF`_>+%F9IDu-5(iJeVYnsu7vct)0Qu;82UE};>un<;6I2z zf8pDuQwrx7fs%nSvr0;voxH(#7bRVV9HZ#Ht}DZ9BsJw*oTvPk9F5JcV67ZF^<{Hj z=Uhnt-PDxXK!(=r6|LOM(^>^5@^QVipx%@7d)0%&a;?|&2)P@3vkNlA)56OiZ+G!g zoO_Vv`u7feAYEX@-F2_MNvtY(p~3*imGNcoj2RVA*p^pA1~pau^Zh&Y^@&c-{3zwL zq&mlf-QTk+QJKOahnleV(5(bZ`N2iN-|DZV!jHjd$5Owu8;UC(@8>qQIVL%*VP<|i z%p&`jJ(I2G*J-~LKw&RsLS$ICZz!x#-}VM}%*RLU%!t|0Gh=rY*^#dPK1JB= z+v+iH;ju5bnYNq3wc|am2(eVe<2N_`$5>OA{F*7hf2%sVGLvxVQ(>VJNo>w*9Rh4X zBd=4pQcq6}D025azYssOvQXFl$LxZ&Nz4n;-thXErRGwE5K995+gWgbAqeoQhMYP7 zyA>>|B%frBER1!newcnuG5A`e_TyOcW;T89!Hx6RecI9_*x$WL0-M*!JdhEJ@Ep^= zpdUtwXwX{I)3&~W@LIHXOJ_NE+d~ifIknXZ<{Ncx3-7sP32BeXx?3i-^YA%Bd;aEp z&Q(Il)S2q4W5p$V+U;29y>&IpsxVTU1T4z^TQHR6gSdB?+y&8z73fw%f8mduXkX@Bdx=JvN!y$T_yN-S9rllc!4;zdOiteK1qtCc z;^jQ$6lsH1y%VV7Z{OFl*EZRoX-p}K?L@aiTK4_ouv&Jvt4uz2r)jzCCDqT`yceZP zJrf!`*XHdP|P@zKk(4-*vTw6UHR^b;>e;joLK!Az*O%t?#LIf$_S2r(6 z>hcn&EA!UfeYWk&bW4&Z)mkk=pi_fIWUNOg`JQs0QD{9JYM1v~AFG3Rt4K^#b0*Up z9W3m)l))zY>?Jin#h;t=M~h}6>$*TD{!VgBrbqg^#Libm`;8t1!W&^&AQwO55~4jz W{@(I4M&`;$Uk=K2J!QClvFpE8wb?xY literal 0 HcmV?d00001 diff --git a/tests/fixtures/modes/prog8_422_arithmetic.jpg b/tests/fixtures/modes/prog8_422_arithmetic.jpg new file mode 100644 index 0000000000000000000000000000000000000000..77097a49b478f1c57fa6f79e0f61e0ed163d59c0 GIT binary patch literal 1182 zcmex=``2_j6xdp@o1cgOJMMZh|#U;coyG6VInuyV4pa*FVB^NNrR z{-0tHrd%dkMu;B zpIu>;=04lBAE^q*)N6nVFH%o>44j zW@FFY?7ILl+TXpq>|lZzG=wDNBd%CMXKEiCv~ zgV{1a#>{!*gd~{a1T6(#QtfItHZ{_N=$gG_Ezh+%m_c~SoSoVP6%W(VEbzga( zAX&-;vee4$lhW@;hTo=bWR8$|I`PfzgUeM5ru;iQXMy%=?_i%tjE?VBH${Ix)1v41 z(Uz%M=&7~VH!c_FeEU`nPs16TQ|@`KUn;1_=Vs6Ca7X?2uK8R&$l=3HzDI5U8KPr3B{iA7W4hNKYpAn+_i*V2|F1LO ztXU`TH_NvyV9&dwvBx}`!?wNtlf@5ohKtRjPQ`=2Iacmaw^$tNxf#VGMtjBT?5D>M z|J*V~q;k7m3t&xy{t-}TauEnC6dY8y~oe=z_1;i;C> zUMxS%|C}TL<%z@oo8xkXB-wPXiTdBZw0-J)&SSynpJh+0mAjg8+w#M$$Bk+HCy#Af zd*q^t-uk>e_2w>p= zH}3V$nYg$u^hv$1f_@HpS;RV}IgI%^_XrV2zceTid7TekPz5X-g^nO=+e57rU-}Ao@ zzMQB&pR{O3o|jx&*%y(@na`{8!Xg50Ewa3~;ogyS-l>&AANluIykOYWx{#yvdEl2f zbJ@;ET@2bQ)^x5_u;|^rTl024;%wRK#rUnQSlrByZ&8qScE-}_o~$j#bAHw{1TKh~ zyIis2>Z~m}w_+xlEspZ3=iIM-s)&)@x?|I%CG!qW)-m6`r}6jprN>n#?wEH|_{GW_ J64n220sv7D;_?6h literal 0 HcmV?d00001 diff --git a/tests/fixtures/modes/prog8_422_huffman.jpg b/tests/fixtures/modes/prog8_422_huffman.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6ad8e9cc76075abab676e2af9e4735dffb1911f6 GIT binary patch literal 1385 zcmb7DX;2ea9DjR-ge0&_5(pgy7Eli9V1QA?4iS=uQw&0jmSYB?MM0~e6_2Wrid>en zRuLN;s(@k{MeI03hY&ytT9gPSM68HNomh(Zpi)iWW>ngb{qOs1Qp_VQIM^HmiU9-{KxYt&4apG#op!5Tt7=;Dv?RGvrYw5p>^N1~X};;%Rh`xI_}TOHXm^)WnN|5sj~_r_Dz|MuFH}Zyx(pd-85U6 zwjHYQAOV75u%@|eVA-^*1cL%%HU1%~+2?eR-sH}bqCr8_51$VwX6=e~$c$chwZYj_ zr*0`V$sFzS%6g}UN)$%rYq?>`j=XA@SBnbNtsfc7J$wb*fNA4w=ir8mIYW=je_JMA zjU&ZtrEe%0E=MmvP*~vD>fi5e9y=!x1 z!DKXg;D%r3rQQ7j&t7$S9qFi9UGB#c$Y{m#S#j~U%c1cz8^iO?c>k@{?4(I-|`@;j;Br{;5 zqAXD%#9UQxqN;>hy@`t15;D@57E!!VUK=*JCLXW4x4-Ci;Ph$7owt_v^J%$?*5iSF z-smxo$X@qtVa3^BX>EYRK~fdwOUotlyS%D6sWdg*u-Pke^4W37JD-Gp8O!fFdRtMY z=3PBx`m(aTh%d@U>dxwptUrp^E7A&-!JhZal$}~d@8+5_MWQ}=etcD3QJcm&Zf029 zKC1H`0xu?F9^_swMXFa0M0Ff)n10#c`ibdyOnprVcan2@W*|tmL7t8~?iua`SIBii zt}aD@_mw!eG=T{9jDK>{`?KFg^T_GeM{E;TEc*NDkAu}8sK$ANc}nqFr)%oH(#Cyb I`^?6F0GUO}V*mgE literal 0 HcmV?d00001 diff --git a/tests/fixtures/modes/seq12_420_huffman.jpg b/tests/fixtures/modes/seq12_420_huffman.jpg new file mode 100644 index 0000000000000000000000000000000000000000..922d4bb19f7e29fd78fa0567c6a387dab8ae6ad0 GIT binary patch literal 1867 zcmb79cU04d8vSLGMMyAU0wO{fG6X|G2u4t3D5C-mBh&#BEmH(!G!Q{X88Rw}3=s#i zsw|N$1yO^FY!hMv5oJ^$6qIEZ$P4G4cTWF(_xt|4-@V_x624>tz}ed#w*^2T002n` zkO+aJ00a!)UMZl`g&|-tC=`a0k%1#HC=3RTLZfA|@;F&69*aif6mj?+1O){JjNDG5 zB7rDRP#|oZfFM#06o!PskOWz@EaCr#y000b;=KL2> za0D7DrS{?g@HRkD5bVD+6b6BVWk3i3iISIQR79(hH7MIA(z;;CzbpVW5(S21q?9%u zkm|RK|L+L|1ct)kG6*CJFAwY>s3}m6Xi5YCMtT6oL-2qlAn42P$f}8u0F&(cO>>rf zdElZ$H2qsv`{7HZz&=^Rc-*`Yq%$$R`Ym+zls)T1?9eNfmg zzp?9nFS=m(U^zE+Y6qu?0W95BwYQKRIlc&*2DjrXrF_f~uJ%T0Z+`qznG zG1yx4omx(8)sNRkAemQWbT!iKk{5r&p*6`l0%sA|n`mVjH@n7j^hn;M^qm#2;g|O9 zYQ|Iqz_6_KW}}y-7CH=OLA?BNPsUV*egQaOAmN|LbZB5#hRxZ6jg*zcqL=CX#zQub zzwnvXOFU(2{~J}4m#6i^Exb)A@k=(!N94K+dou84$xW6b(vs?~^Z6xem+yDPiP#RS z+CEXXXCqQq7sBgx>1Gg@I9}eZI|6^YAo`@&V?$(eU(zv4$Ma0VHNCU4u?hQO^$w1Y zbdsMXeaEe=4~6)T`_F6pvTp7cRmBiT+F!5NA%v_EmeO$5rRt{2X;*g**0d@0%WGnp z$xyQ6%1tYBTDX@P9U*XopVKtH$NF8Y#eY(GN{p?zUp|`bh1kQeikJ$TDjSYTY4KE+vT^2E54Nb%eu{>3-Paxy=i)( zZ5;HL5pH3v$xOw=2RZt`^nDHYcpZH`6l8pa#OGko-EBq8sSFv|MlW^>FPGH4dMtFM zG_@SRrBYPyL(xc@WXDokhMX{wJ~c&I%o)RvANlw$u_ZI-LP2b``2${7?fgQB#e?bM zv@5*^=Y9UjF&@~heZ$Hu-H1p_`qL*nttD&kt7nC0uOcSAs(ab_&N*3uW%9WFNes&mFMF0e6Mi6qsV)tiKA-Lz9d`m5@PN-J z)J#oAFRL4g?~RaahZbybTE{5-o=0XP4k3%|wYD!Ml3E=`F6a!V)3;daj-?4D@F2s# z-duRSno)UFK@^D9)!Qg}FjLu#s;pTYcX5k}T9}8$G4nf+qo)Vlx#Ts1Wl*mF-0m{5 z{z224D?upl%7-~JuJ1n2i8X^zkgc|5BPDnJ-_N5_lSns#HQgzp=?%%tT!xb}V=Ai6 z`Bl`$64o;(>&(mc@OHPk3;sUzc;dyaFkXv!<%nh5Q;L$E&fA*qChN_Gy*n`KJk^W1*FW@S@9ZcnN^2 z_I~=vJ0##^pUaqSy?_1~a_~-=Y&)D~@kvkB9c&;t$7|&)4fEdE%V)&#Y;8i@3bJ+g zQj)?dvcaP#7q za&hp}jeey1Rhqt>j?rNUEHztonN3o(F1E|x%wBZT80%RHKX4|hc!Nfx^`hpO(?yDg z9;BiXasxTJYAe`?y+?4neAJ}s+onln+J^OsTF27N2x%<2#YvLV><|+{;*$q9t_Cp(u<@noJZ7=?| zN% zy>Dqu7IVISna?bSXd&@DChyy;bDBaQ@l<*~^SOCR%Kqo@59LwUz#b*9^o_(VLUOg1 z!%+^snuw$CPv{P>Ky-yEC#(LJi?#En<1Bj27I&N;mkDBW(pD0p5pBf6sRXY~&lquZ z&g_xr3n?vgxVhmepJPR#o9==@siu)hrSL)JVr^BRrvjRXOuy90@*B?3^ub17(Sbj* zwR^lfz76b+k76!W&I;TOn*~)3Yl7^s9SCY&UP7@|A3gH68**&dEAJ)zYQn)CWBT`Y z%K0ZzDQN~fUdyq%hcp@e-bKruspF2*Lj^cTlBlZu=A>w-_@Ib$>*mNh4DNi!+Usgo z9y6R|88Q4w^-5%)+3v_zztB(@)h!HA7^Syr9J29kSThO)>ikc*oyOQ1AaR1 zb)??bJ0(Y`nuoc++UJrC_P@vx+KS`m1OX3&Gu8+U_Kl!fwL%Hi=s;O48|7V8l8JD9 z`)O9PosEKR)PJUtoT=$7G-_P-`0(Ll_E)MqiS8ss>$S-PVnOD4al~?sPkWp985@%l zCyPw`8*S?1w5Uz2>F7OE3gjqV>X za%V={>*AW>>&KPOS?A39-F<{#>bLp^y}^x?jooK^Y>Ru)RY2et-Kv#AmLn_1Jc?-N zv%|c%q%}S*j{yhss7*RS3R|Z1MORnz@#adAu4;~cm$OyF)fkg&H0pKzH0||m;+xiW zY15PJrjG_2&C)t2LI5c2zj^>d7LLN8rKz1b03rj0O837Gz#vc=_$CBW7LSs)DFCNV zra1js`%s*;_RSjx=lHStT@`Ht{gwNA*n<}}GDaMN(k)H;EF091F3U7gWSKaoOQ+Qh zet~Z%`7okUqRQrxOryL1*xi`v8~ESP8u6=06*u1dT0kgYHAl2z z?!zl4q7RrHy8IzSY5&zD)7^g{mOz01a5*%nu|17hTNAu0!$~0P1@3{DzN>JS^+%}( z7|!?^KAKPd*(9!ae@T9;1x9EXZ6Rma3HItNc-lp*S68gFH?G=A5_{%lmk!es^wkE5 zrIeU<_HoxCN<+fmK06na$s6fiGbbeLS+{Z)z9Ui_c+F`c@&4ywfm){=AD2^d+~4-h zb-Ya9mC92ULev+cb2ATxZdHlYPPACn28F`SBQAWAV4-lWyh%cdS2?YFl9%E#UQzHS zI@29n_GI5fejC-c`EgRMw!^W&@Y?oBeg?F%Sz>L#YEtMPBFZK%Zw})7w4!Cp3Oq z$U~*V6kXJr|?Rm*YR-A5ya~-C-UX6seS3^|^8q zUZ$ogE2+0;7MNyuT-aHdS87Q*9I=)PwJfdlO5&P*?Gju%nbUK&Au4!b@(3^GFE6PC z-+mUR?-<@`G<#;~1%<4S&2G*L?kP|U$WpS}eE(1!J_hV18)@G2OrTMJJwE--w{H7m zAC%dV>7yqmgIZ{n4?c!Ygd>OUwVIzMl!ROVzVo+NQo$FRn$Uwpo> zHf!7QzJm`)f(zefrhk&9(IIZvraYEnHCk?|`O23$TZcS7D5VW?sZ4Af6yi`r{5rI6 zZStjCqU55Ze$0^8wu57RGqkZ`d;7~H(BTe_+s#1Q_S9mlJ%_U0Cg2k8xXwh|O!fTA z%?-YqE$cgTK7_vaeB9Ww5>b`(^@`RWy|G7?y+3to6w41Dp}bIAYfl>BE*j?grwel- z6b9I*v?VQ?z1g94>6vJdo4m+kC&NI%n^d>LGNwL*Z~qP$ CVl%`5 literal 0 HcmV?d00001 diff --git a/tests/fixtures/modes/seq12_grey_arithmetic.jpg b/tests/fixtures/modes/seq12_grey_arithmetic.jpg new file mode 100644 index 0000000000000000000000000000000000000000..26b7dda4f82ac0a1fe2f45ed66f00f56a006173e GIT binary patch literal 1410 zcmV-|1%3Me*#F=F5K2Z#MgRc;000310RRC1+W5_|H%Lg3;-7Z zBLM*s0RPMY1^_`24FBB#1ONm7+5iXv0RR9$0Mh59_eYbln2g>xxK|&sqkU0xU~>4R zuZIfaiMM6q+J{@*t8;RbQ>(Gf)=p7QhRUs=WNeh1OTPzFklHyGu*(ieW06L{M6DOZjyW`)mommWBWFZLn&AG zh|BOCQ}GCqodO~-ko*~>C!V2f`PxdJ3@$fiVCKMzT5w4%1eNeOFsB%fY{3K&;r+^8 zN%2vo8!iRVDtw|C3T)wuu`Xbqm1CBH5tzyDpe`#6@kAb->R@i+j`*hq22YX*AM!^v z)cz`o-zDo6Uk{anq4;2ME%b#H+Uq=7bL9fCiZNVU7P2x{P`^v89+JB?e;HXJ=9){=s6l_p{{Zva6q0VP z<$vKyYekc*4V^I8bGNzsHjdbxBg=KfVWV1B8!afNyP(OpRafz6V+bIZdRgp*DSYsE zp#7rCw*(f@0?F^NZbY323KcrT`Qoz8$l3cMdccHWyCIIX%zS+Xob6;g38m$MUK91b&{_oPT;-6 zdFDQ%Gqgw8r|d`kqf`(hE+8y^<{0OFwUfWtv2w&E^yd3+PJ@ZCfz}$Do7y^XsI04JzUD$EG3DP@4IulB>LbO3kGCDJAfi7` zH<&1s?1ejQFhTqEB*Y_2E9+}>JDUx$^nss#-a8tSk((O8s5B1E@kBn+3?B{>xX{t_ zXJ|~-?-ep)#Du_}1>ungX1WnI5(k`QfRWJT|I+^e?-~_FKc_P(lrUe$VDppEuxfF0 zoN-$su-x3DKy;Bb-Edw+K z7KD+$jSdE#BvE;%ZE4NqIf&YGtry}bnnARHymx$Fb6awdWc&q@g{}zWrL!=Np~0UzdubY>6u^ znJs7QIVEups}_{{a1osCWSz6Y3IIEsy~r=Cr+t zG({$w9|r+%6CZGdX)ae!<(0rQt$_5o_CwY%)}3e`5`xxphRZAd*UVdG1y^ QPjXFGTD}ZxfXIOV+31#p+5i9m literal 0 HcmV?d00001 diff --git a/tests/fixtures/modes/seq12_ycck.jpg b/tests/fixtures/modes/seq12_ycck.jpg new file mode 100644 index 0000000000000000000000000000000000000000..db21e1baacac513152521249c6fbccfd62f92254 GIT binary patch literal 1477 zcmb7Fz~Gv2xF$&ptws9ZQau4k7yu0rVIUQN;6W%Jgi!%i1E324P!L>R`$H%+ zMpK>8aR8tJfq*dRe=$ToUjqRmHBkT>PatAQWZPu|2tc4e%FBl)8iqis6H`0@!a#@y z2toXtL)4F`5lBE2r3R45RK^CTy|b&Y>J5N}sX2Hk9tHq5K*HI!PjO)%kNUlUO0mAd zcNV1$+P&0CgQ<4n$@D7L^jEv`{u{KINi<7<%NC~x8tK7rHE;}bd<;u!T$GLevTb#p z%@1mM<-2;h;Q=}PyixNSr-^{~HV!U_6z5rQO}vHMx`B&Bga?kScjLj|@UWJ5g?ouj z!;cNZYErc2SCXNw>5qn)mP{)#cG4)YLKvby+}CmYcI(f?vK31Fv~*v!MEud=QAGa! z{hX|ZrI~`Y%~$De?&9>-@{LC`6!O88YPM8ooYtAd%xUU6tz;}Rg;)l?E3eJltv6E` zd^=EQ6yLYy3}cCnbn3d86G}GAmBk-O-RBv1m%aP9uH@6Zkq3X8k=D%2nP)HV62|jI2EwFeuw{Li%d+XY;Sp= z969zy!5OWd*YC!5EKc^Onh*SCV0AL72|sS3|4VgAHlxb)t?uf}GmmA8*J<_o;`75E zq{xi)K>^h~E%rLL*~*9~Q)XQ*du3S|-ANkalbH!Ov!A=CM~PlK_t)QJ-B=BwAY0uK zMe9EhW25rp5PJR>kf-pHU!PJFXV#Bf@Q<_wRCCH4%|cgx32aT3Z~gOleYf?_v5csI zl*5nfqELBUG)9yiv{Pz7V>e*ksjOuEOwWpKUv>HSFw}KJf?sW4XF-mwQCW1FJu;1K zMYWJOjpYU{N>b<`uh`UM<2T7+p51*bLeD`*FA?3*1wo^pGMh2UF6C}A^0?&19^~Tv z42XNRn>9Q^w&ZSwKx0w+kqUw5s7c8EBZ ze>;!aU;<5~*MfL+LL$@UTaceG+J8yl*FSj|Qo9BLl!r@m~d1lC4 zsxI+nYBszY?%~%}(s!lw%>{kf`uv*yy1NrXUG{A0N+(9UM_=8W3iIz3Rp*wj3d+kj z?G)Ns*qBSNOKBUZH$O3jXjjAFhhp*?*8-*%&lsw7$6$E`wFMaZQjN; z%Hk7GNTgbhSGQ&<1u0He;?UrPxus#_1yR6eoK(lDKXCr|oi)Yzsh^!3kDZa9Y-JI0 z6tQ{liz``2_j6xdp@o1cgOJMMZh|#U;coyG6VInuyV4pa*FVB^NNrR z{-0zJg7m(q)qsGxRu_8dr z+H+-_P9Ar=ryxNmO8PzoqND{X}(9nYWIDCJ^dl3I`Ru-4))x; zqA7B7D*NuvtB(x-7(D%Qp>oc$*)eyRjJ_6#CLak6s4{xY}@7ga@~xQ-|VN~DYtL-|4{6r z5^_aYF#gj1?h@Hv*NnMV%k{pOtgSA}VUrK|D|dUwIX*YO4PjfJSxj@>9)7%Ui{46m zt(`0Dip2R)|EyBqp^i3h8Pkf+SX7tJwB3|e7%a(_1wF<>4cvC6h{YuPO4T?kEV@d}q$xukUsKxGq^~_+sXU=z#wh z{xh7`KRN5bfwbH$ozpC5itXsDG}qR#ec6~PvQQfi-8MxVwe5ep0xJNsfXtx zuddSDzVyZB7dzsD7C)ZfwCl$vZ?Dhq7~Rk8F7CR0^w@s}C(h3oR(-e4*!FQ+Pea+s zB3Zvz#zIVU9qdoP`_ut>VLt~!ZyVNw_T_An$4E}r1 zzpOnO+`PB)a&70{@|QiO8*kq?S(xwa+}ta&yiBypwuWK-?5M&U@juQzaktd4WNZ1M y{qdZ<>nTy+e1pG<@0#wF6)6iE-RS=}BeP0MzV>Ovf?=C&?|0V#3&5l3- literal 0 HcmV?d00001 diff --git a/tests/fixtures/modes/seq8_420_huffman.jpg b/tests/fixtures/modes/seq8_420_huffman.jpg new file mode 100644 index 0000000000000000000000000000000000000000..98b5a842c9e0972b2ec6ca54902d6799187ea27e GIT binary patch literal 1022 zcmex=``2_j6xdp@o1cgOJMMZh|#U;coyG6VInuyV4pa*FVB^NNrR z{vTivB$T3Y5|jU|?bdx*5oY$}%zm zT`$NWq{t?0sAR;h;+QC^>=c+ZaUsYcpqH7Lk&IzrXJun#<^W0=2{JG;v9K_5aKoe- znFN6*88Wa5DFXefq-^9Ec+uFzIkB*D;-rNeFa5vEz{0@%{}uxe&}l%Wf(-Tyw|c)# zo4@SI<_IBcy;F|<4pQ@K%*9>oQ zBab6)o*efkeA3LbT`(zx>D03Mf|F+Nn_|v)v*Jj;-(=bITiUn|f9*XnNAUT4n^&_- zZC$H%N|&CM2q-hqo;>#^v*dRTiSrY`pIdc#im1O!NG8h^r(Ku!U24u>_F&q!H_xSw zzN7>u>Uj3a2>o$6@^*#UFY|rV#rX=BUJ3cn&?zY-Sv_x2YGy?k??Lrfe1(nY7G`We znXzQjmKocQE4eXDQl0YQhhoIL1hYB2n#3(s#3T!L+ozQLUn-3x6%#WxG=Uj?TGb-`Ir~z1kI(74i7Z z^Ne4ImcM_pt$wf63;)a8ex0S*7!R^faAaZPU|T3IH(~2k z4ny-Fl@B^Yv^WE8y38-sNBqBVST88}@>PxKj@1##ZHssNs5q=`nZETz@Jq|E2P+RZ zM0%WF?(=nOebDSull_K5ZOej9mULxow|*$FQqsucfq-q^&2!FDCUYk*ShUe)#)@<7 z-JB{*Zg%)B+}ig~;gP)InIm&2^ass&>DDwUAm@n6nj8ta3G7Sw%%o-a+-jJzzDP~U z@S)el$-jR}``h$OJdU+mB~`aTS4Y64;Lw|7&&b$AlMkeE?e35fZs4C&Ym#x@?Agi_ z2i7eUy}qPD^noeMt!paLUz>Bb2h5zgy!c6|&52;v>iOQ8Z*EN7@%|$-=lisV?ZWy0 keC5^uUR><9spo7M2Xp@q|7nsFXRW&B9%XmsXY&7>03G9XMgRZ+ literal 0 HcmV?d00001 diff --git a/tools/generate_modes_libjpeg.c b/tools/generate_modes_libjpeg.c new file mode 100644 index 0000000..88f9745 --- /dev/null +++ b/tools/generate_modes_libjpeg.c @@ -0,0 +1,184 @@ +/* + * Writes the fixtures of tests/extended_modes.rs: synthetic pictures coded by + * libjpeg-turbo (3.1.0 was used) in the modes `cjpeg` has no switches for, or + * not in this combination. With `raw` it prints the FNV-1a hash of what + * libjpeg-turbo decodes a file to (samples as little-endian u16, in the + * library's own CMYK for four components), which is what the tests expect. + * + * cmake -S libjpeg-turbo-3.1.0 -B b -DENABLE_SHARED=0 && make -C b jpeg-static + * cc -O2 -o modes generate_modes_libjpeg.c -Ilibjpeg-turbo-3.1.0/src -Ib b/libjpeg.a -lm + * ./modes gen + * ./modes raw ... + */ +#include +#include +#include +#include +#include "jpeglib.h" + +typedef struct { + const char *name; + int w, h, components, precision, hsamp, vsamp, progressive, arithmetic; + int restart, separate_scans, dac, predictor, point_transform, ycck; +} Picture; + +static const Picture pictures[] = { + /* w h n P H V prog ari rst sep dac psv pt ycck */ + { "seq8_420_huffman", 35, 23, 3, 8, 2, 2, 0, 0, 3, 0, 0, 0, 0, 0 }, + { "seq8_420_arithmetic", 35, 23, 3, 8, 2, 2, 0, 1, 3, 0, 1, 0, 0, 0 }, + { "prog8_422_huffman", 35, 23, 3, 8, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, + { "prog8_422_arithmetic", 35, 23, 3, 8, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0 }, + { "seq12_420_huffman", 35, 23, 3, 12, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0 }, + { "seq12_440_separate", 35, 23, 3, 12, 1, 2, 0, 0, 2, 1, 0, 0, 0, 0 }, + { "prog12_422_huffman", 35, 23, 3, 12, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, + { "seq12_grey_arithmetic", 35, 23, 1, 12, 1, 1, 0, 1, 3, 0, 1, 0, 0, 0 }, + { "prog12_420_arithmetic", 35, 23, 3, 12, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0 }, + { "seq12_ycck", 19, 11, 4, 12, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1 }, + { "lossless14_pair", 24, 16, 2, 14, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0 }, + { "lossless12_pair_scans", 24, 16, 2, 12, 1, 1, 0, 0, 1, 1, 0, 6, 1, 0 }, +}; + +static unsigned random_state; + +static int sample(const Picture *p, int x, int y, int c) +{ + int max = (1 << p->precision) - 1; + double v = 0.5 + 0.3 * sin(x * (0.11 + 0.05 * c) + c) * cos(y * 0.13) + + 0.15 * (((x / 7 + y / 5 + c) & 1) ? 1 : -1); + random_state = random_state * 1103515245u + 12345u; + v += ((int)((random_state >> 16) % 2001) - 1000) / 12000.0; + int s = (int)(v * max + 0.5); + if ((x * 31 + y * 17) % 97 == 0) s = max; + if ((x * 13 + y * 37) % 101 == 0) s = 0; + return s < 0 ? 0 : s > max ? max : s; +} + +static void generate(const char *directory, const Picture *p) +{ + struct jpeg_compress_struct c; + struct jpeg_error_mgr e; + jpeg_scan_info scans[4]; + char path[1024]; + snprintf(path, sizeof path, "%s/%s.jpg", directory, p->name); + FILE *f = fopen(path, "wb"); + + random_state = 12345; + c.err = jpeg_std_error(&e); + jpeg_create_compress(&c); + jpeg_stdio_dest(&c, f); + c.image_width = p->w; + c.image_height = p->h; + c.input_components = p->components; + c.in_color_space = p->components == 1 ? JCS_GRAYSCALE : + p->components == 2 ? JCS_UNKNOWN : + p->components == 3 ? JCS_RGB : JCS_CMYK; + c.data_precision = p->precision; + jpeg_set_defaults(&c); + c.data_precision = p->precision; + if (p->predictor) { + jpeg_enable_lossless(&c, p->predictor, p->point_transform); + } else { + jpeg_set_quality(&c, 90, TRUE); + if (p->ycck) jpeg_set_colorspace(&c, JCS_YCCK); + for (int i = 0; i < p->components; i++) { + int full = i == 0 || i == 3; + c.comp_info[i].h_samp_factor = full ? p->hsamp : 1; + c.comp_info[i].v_samp_factor = full ? p->vsamp : 1; + } + } + c.arith_code = p->arithmetic; + c.optimize_coding = !p->arithmetic; + if (p->dac) + for (int i = 0; i < NUM_ARITH_TBLS; i++) { + c.arith_dc_L[i] = 1; + c.arith_dc_U[i] = 4; + c.arith_ac_K[i] = 12; + } + if (p->progressive) jpeg_simple_progression(&c); + if (p->separate_scans) { + memset(scans, 0, sizeof scans); + for (int i = 0; i < p->components; i++) { + scans[i].comps_in_scan = 1; + scans[i].component_index[0] = i; + scans[i].Ss = p->predictor; + scans[i].Se = p->predictor ? 0 : 63; + scans[i].Al = p->point_transform; + } + c.scan_info = scans; + c.num_scans = p->components; + } + if (p->predictor) c.restart_in_rows = p->restart; + else c.restart_interval = p->restart; + + jpeg_start_compress(&c, TRUE); + for (int y = 0; y < p->h; y++) { + JSAMPLE row8[256]; + J12SAMPLE row12[256]; + J16SAMPLE row16[256]; + for (int i = 0; i < p->w * p->components; i++) { + int s = sample(p, i / p->components, y, i % p->components); + row8[i] = s; + row12[i] = s; + row16[i] = s; + } + JSAMPROW r8 = row8; + J12SAMPROW r12 = row12; + J16SAMPROW r16 = row16; + if (p->precision <= 8) jpeg_write_scanlines(&c, &r8, 1); + else if (p->precision <= 12) jpeg12_write_scanlines(&c, &r12, 1); + else jpeg16_write_scanlines(&c, &r16, 1); + } + jpeg_finish_compress(&c); + jpeg_destroy_compress(&c); + fclose(f); +} + +static void print_hash(const char *path) +{ + struct jpeg_decompress_struct c; + struct jpeg_error_mgr e; + FILE *f = fopen(path, "rb"); + unsigned long long hash = 0xcbf29ce484222325ull; + + c.err = jpeg_std_error(&e); + jpeg_create_decompress(&c); + jpeg_stdio_src(&c, f); + jpeg_read_header(&c, TRUE); + if (c.num_components == 4) c.out_color_space = JCS_CMYK; + jpeg_start_decompress(&c); + while (c.output_scanline < c.output_height) { + JSAMPLE row8[1024]; + J12SAMPLE row12[1024]; + J16SAMPLE row16[1024]; + JSAMPROW r8 = row8; + J12SAMPROW r12 = row12; + J16SAMPROW r16 = row16; + if (c.data_precision <= 8) jpeg_read_scanlines(&c, &r8, 1); + else if (c.data_precision <= 12) jpeg12_read_scanlines(&c, &r12, 1); + else jpeg16_read_scanlines(&c, &r16, 1); + for (unsigned i = 0; i < c.output_width * c.output_components; i++) { + unsigned s = c.data_precision <= 8 ? row8[i] : + c.data_precision <= 12 ? (unsigned)row12[i] : row16[i]; + hash = (hash ^ (s & 0xff)) * 0x100000001b3ull; + hash = (hash ^ (s >> 8)) * 0x100000001b3ull; + } + } + printf("%s %dx%dx%d %016llx\n", path, c.output_width, c.output_height, + c.output_components, hash); + jpeg_finish_decompress(&c); + jpeg_destroy_decompress(&c); + fclose(f); +} + +int main(int argc, char **argv) +{ + if (argc == 3 && !strcmp(argv[1], "gen")) { + for (size_t i = 0; i < sizeof pictures / sizeof *pictures; i++) + generate(argv[2], &pictures[i]); + } else if (argc > 2 && !strcmp(argv[1], "raw")) { + for (int i = 2; i < argc; i++) print_hash(argv[i]); + } else { + return 1; + } + return 0; +}