rusty_pdf_core 0.1.0

Pure-Rust PDF reader core: objects, classic and stream cross-reference tables, object streams, incremental updates, broken-xref repair, RC4 and AES-128/256 decryption, stream filters, page tree, content streams, editing and save. Hostile input errors or stays bounded. No C, no unsafe.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! Image XObjects and inline images to samples.
//!
//! Everything here is bounded by the image's own declared size: the pixel
//! count is checked against [`ImageOptions::max_pixels`] before anything is
//! allocated, and decompression stops at the number of bytes those
//! dimensions justify.
//!
//! The result is samples in the image's own colour space. Colour management
//! (ICC, tint transforms) belongs to the renderer; [`Image::to_rgb8`] and
//! [`Image::to_gray8`] are the plain device conversions, which is what OCR
//! and thumbnails need.

use crate::document::Document;
use crate::error::{Error, Result};
use crate::filters::{self, Cap};
use crate::object::{Dictionary, Object, Stream};

/// Bounds and policy for decoding one image.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ImageOptions {
    /// Largest image decoded, in pixels. Default 100,000,000: a 600 ppi
    /// tabloid page with room to spare.
    pub max_pixels: usize,
    /// What to do when the data holds fewer samples than the dimensions
    /// need: `false` (the default) is an error; `true` fills the missing
    /// samples with zero, as viewers do.
    pub pad_short_data: bool,
}

impl Default for ImageOptions {
    fn default() -> Self {
        Self { max_pixels: 100_000_000, pad_short_data: false }
    }
}

impl ImageOptions {
    /// Default options with `max_pixels`.
    #[must_use]
    pub fn with_max_pixels(max_pixels: usize) -> Self {
        Self { max_pixels, ..Self::default() }
    }
}

/// What an image's samples mean.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ColorSpace {
    /// One component, 0 black to 255 white (DeviceGray, CalGray, a
    /// one-component ICC profile).
    Gray,
    /// Three components (DeviceRGB, CalRGB, a three-component ICC profile).
    Rgb,
    /// Four components, 0 no ink to 255 full ink (DeviceCMYK, a
    /// four-component ICC profile).
    Cmyk,
    /// One component: an index into `palette`, which holds one entry of
    /// `base` per index.
    Indexed {
        /// The colour space of the palette entries.
        base: Box<ColorSpace>,
        /// `base.components()` bytes per entry.
        palette: Vec<u8>,
    },
    /// A space this crate does not convert: Lab, Separation, DeviceN.
    Other {
        /// The colour-space family name.
        name: Vec<u8>,
        /// Components per sample.
        components: usize,
    },
}

impl ColorSpace {
    /// Components per sample.
    #[must_use]
    pub fn components(&self) -> usize {
        match self {
            Self::Gray | Self::Indexed { .. } => 1,
            Self::Rgb => 3,
            Self::Cmyk => 4,
            Self::Other { components, .. } => *components,
        }
    }
}

/// A decoded image.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Image {
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
    /// What the samples mean.
    pub color_space: ColorSpace,
    /// A stencil mask (`/ImageMask true`): one component, and the page is
    /// painted with the current colour **where the sample is 0**.
    pub stencil: bool,
    /// `width * height * color_space.components()` bytes, rows top to
    /// bottom, 8 bits per component whatever the file used, `/Decode`
    /// applied. For [`ColorSpace::Indexed`] the bytes are palette indexes.
    pub samples: Vec<u8>,
    /// An alpha channel carried inside the image data (JPEG 2000 with
    /// `/SMaskInData`), `width * height` bytes.
    pub alpha: Option<Vec<u8>>,
}

fn image_error<T>(m: impl Into<String>) -> Result<T> {
    Err(Error::Image(m.into()))
}

fn cmyk_to_rgb(c: u8, m: u8, y: u8, k: u8) -> [u8; 3] {
    let k = 255 - u16::from(k);
    // (255 - x) * k / 255 is at most 255.
    [c, m, y].map(|v| ((255 - u16::from(v)) * k / 255) as u8)
}

fn luma(r: u8, g: u8, b: u8) -> u8 {
    // Rec. 601 weights in 1/256ths; the sum is at most 255 * 256.
    ((u32::from(r) * 77 + u32::from(g) * 150 + u32::from(b) * 29) >> 8) as u8
}

impl Image {
    /// The image as 8-bit RGB, by the device conversions (CMYK without a
    /// profile, palette looked up). Fails for [`ColorSpace::Other`].
    pub fn to_rgb8(&self) -> Result<Vec<u8>> {
        convert_rgb(&self.color_space, &self.samples)
    }

    /// The image as 8-bit gray. Fails for [`ColorSpace::Other`].
    pub fn to_gray8(&self) -> Result<Vec<u8>> {
        if self.color_space == ColorSpace::Gray {
            return Ok(self.samples.clone());
        }
        let rgb = self.to_rgb8()?;
        Ok(rgb.as_chunks::<3>().0.iter().map(|p| luma(p[0], p[1], p[2])).collect())
    }
}

fn convert_rgb(space: &ColorSpace, samples: &[u8]) -> Result<Vec<u8>> {
    match space {
        ColorSpace::Gray => Ok(samples.iter().flat_map(|g| [*g; 3]).collect()),
        ColorSpace::Rgb => Ok(samples.to_vec()),
        ColorSpace::Cmyk => Ok(samples
            .as_chunks::<4>().0.iter()
            .flat_map(|p| cmyk_to_rgb(p[0], p[1], p[2], p[3]))
            .collect()),
        ColorSpace::Indexed { base, palette } => {
            let n = base.components();
            let mut entries = Vec::with_capacity(samples.len() * n);
            for index in samples {
                let at = usize::from(*index) * n;
                match palette.get(at..at + n) {
                    Some(entry) => entries.extend_from_slice(entry),
                    // An index past the palette paints the first entry's
                    // black; viewers differ, none fail.
                    None => entries.extend(std::iter::repeat_n(0, n)),
                }
            }
            convert_rgb(base, &entries)
        }
        ColorSpace::Other { name, .. } => image_error(format!(
            "colour space {} needs a colour-managed conversion",
            String::from_utf8_lossy(name)
        )),
    }
}

/// A dictionary entry by its full name or its inline-image abbreviation.
fn entry<'a>(doc: &'a Document, dict: &'a Dictionary, long: &[u8], short: &[u8]) -> Result<&'a Object> {
    match doc.lookup(dict, long)? {
        Object::Null => doc.lookup(dict, short),
        o => Ok(o),
    }
}

fn dimension(doc: &Document, dict: &Dictionary, long: &'static [u8], short: &[u8]) -> Result<usize> {
    let name = String::from_utf8_lossy(long);
    let v = entry(doc, dict, long, short)?
        .as_i64()
        .map_err(|_| Error::Image(format!("missing /{name}")))?;
    usize::try_from(v)
        .ok()
        .filter(|v| *v > 0)
        .ok_or_else(|| Error::Image(format!("/{name} {v} is not a positive size")))
}

/// Resolve a colour-space object. `resources` supplies named colour spaces,
/// which inline images may use.
fn color_space(doc: &Document, object: &Object, resources: Option<&Dictionary>, depth: u8) -> Result<ColorSpace> {
    if depth > 4 {
        return image_error("colour spaces nested too deeply");
    }
    let object = doc.resolve(object)?;
    let by_name = |name: &[u8]| -> Result<ColorSpace> {
        match name {
            b"DeviceGray" | b"G" | b"CalGray" => Ok(ColorSpace::Gray),
            b"DeviceRGB" | b"RGB" | b"CalRGB" => Ok(ColorSpace::Rgb),
            b"DeviceCMYK" | b"CMYK" => Ok(ColorSpace::Cmyk),
            other => {
                let named = resources
                    .and_then(|r| doc.lookup_dict(r, b"ColorSpace"))
                    .and_then(|spaces| spaces.get(other));
                match named {
                    Some(o) => color_space(doc, o, None, depth + 1),
                    None => image_error(format!("unknown colour space {}", String::from_utf8_lossy(other))),
                }
            }
        }
    };
    let items = match object {
        Object::Name(n) => return by_name(n),
        Object::Array(a) => a,
        _ => return image_error("unrecognised colour space"),
    };
    let family = match items.first().map(|o| doc.resolve(o)).transpose()? {
        Some(Object::Name(n)) => n.as_slice(),
        _ => return image_error("unrecognised colour space"),
    };
    let arg = |i: usize| -> Result<&Object> {
        match items.get(i) {
            Some(o) => doc.resolve(o),
            None => image_error("colour space array is too short"),
        }
    };
    match family {
        b"ICCBased" => {
            // `/N` feeds the row-size arithmetic: only the sizes a profile
            // can have are accepted.
            let n = arg(1)?.as_dict().ok().and_then(|d| doc.lookup(d, b"N").ok()).and_then(|o| o.as_i64().ok());
            match n {
                Some(1) => Ok(ColorSpace::Gray),
                Some(3) | None => Ok(ColorSpace::Rgb),
                Some(4) => Ok(ColorSpace::Cmyk),
                Some(other) => image_error(format!("ICC colour space with {other} components")),
            }
        }
        b"Indexed" | b"I" => {
            let base = color_space(doc, arg(1)?, resources, depth + 1)?;
            if matches!(base, ColorSpace::Indexed { .. }) {
                return image_error("an Indexed colour space cannot be based on another");
            }
            let hival = arg(2)?.as_i64().ok().and_then(|v| usize::try_from(v).ok()).unwrap_or(255).min(255);
            let wanted = (hival + 1) * base.components();
            let mut palette = match arg(3)? {
                Object::String(s, _) => s.clone(),
                Object::Stream(s) => doc.decode_partial(s, Cap::clip(wanted))?.data,
                _ => return image_error("Indexed colour space has no lookup table"),
            };
            palette.truncate(wanted);
            Ok(ColorSpace::Indexed { base: Box::new(base), palette })
        }
        b"Separation" => Ok(ColorSpace::Other { name: family.to_vec(), components: 1 }),
        b"DeviceN" => {
            let n = arg(1)?.as_array().map(<[Object]>::len).unwrap_or(0);
            if (1..=32).contains(&n) {
                Ok(ColorSpace::Other { name: family.to_vec(), components: n })
            } else {
                image_error("DeviceN colour space with an unusable component count")
            }
        }
        b"Lab" => Ok(ColorSpace::Other { name: family.to_vec(), components: 3 }),
        b"Pattern" => image_error("an image cannot use a Pattern colour space"),
        other => by_name(other),
    }
}

/// Spread packed samples of `bits` each into one byte per sample.
/// `scale` stretches the value range to 0..=255 (not for palette indexes).
fn unpack(raw: &[u8], width: usize, height: usize, components: usize, bits: usize, scale: bool) -> Vec<u8> {
    let per_row = width * components;
    let row_bytes = (per_row * bits).div_ceil(8);
    let mut out = Vec::with_capacity(per_row * height);
    for row in raw.chunks(row_bytes).take(height) {
        match bits {
            8 => out.extend_from_slice(&row[..per_row.min(row.len())]),
            16 => out.extend(row.as_chunks::<2>().0.iter().take(per_row).map(|p| p[0])),
            _ => {
                let max = (1u16 << bits) - 1;
                for s in 0..per_row {
                    let bit = s * bits;
                    let Some(byte) = row.get(bit / 8) else { break };
                    let v = u16::from(byte >> (8 - bits - bit % 8)) & max;
                    // v <= max, so v * 255 / max <= 255.
                    out.push(if scale { (v * 255 / max) as u8 } else { v as u8 });
                }
            }
        }
        // A short final row is padded by the caller's length check.
    }
    out
}

/// Apply a `/Decode` array to 8-bit samples.
fn apply_decode(samples: &mut [u8], decode: &[f64], components: usize) {
    if decode.len() < components * 2 {
        return;
    }
    let maps: Vec<Option<[u8; 256]>> = (0..components)
        .map(|c| {
            let (lo, hi) = (decode[c * 2], decode[c * 2 + 1]);
            // The default range needs no work.
            if (lo, hi) == (0.0, 1.0) || !lo.is_finite() || !hi.is_finite() {
                return None;
            }
            let mut table = [0u8; 256];
            for (v, slot) in table.iter_mut().enumerate() {
                // v is 0..=255.
                #[allow(clippy::cast_precision_loss)]
                let x = lo + (v as f64 / 255.0) * (hi - lo);
                // Clamped to 0..=255 before the cast.
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                {
                    *slot = (x.clamp(0.0, 1.0) * 255.0).round() as u8;
                }
            }
            Some(table)
        })
        .collect();
    if maps.iter().all(Option::is_none) {
        return;
    }
    for pixel in samples.chunks_exact_mut(components) {
        for (sample, map) in pixel.iter_mut().zip(&maps) {
            if let Some(table) = map {
                *sample = table[usize::from(*sample)];
            }
        }
    }
}

impl Document {
    /// Decode an image XObject to samples.
    ///
    /// Handles raw, Flate, LZW and run-length samples at 1, 2, 4, 8 or 16
    /// bits, and the image codecs enabled by crate features: JPEG (`dct`),
    /// JPEG 2000 (`jpx`), JBIG2 (`jbig2`) and CCITT fax (`ccitt`).
    pub fn decode_image(&self, stream: &Stream, options: &ImageOptions) -> Result<Image> {
        self.decode_image_with(stream, None, options)
    }

    /// [`decode_image`](Self::decode_image) for an inline image, whose
    /// colour space may be a name defined in the page's `resources`.
    pub fn decode_image_with(
        &self,
        stream: &Stream,
        resources: Option<&Dictionary>,
        options: &ImageOptions,
    ) -> Result<Image> {
        let dict = &stream.dict;
        let width = dimension(self, dict, b"Width", b"W")?;
        let height = dimension(self, dict, b"Height", b"H")?;
        let pixels = width
            .checked_mul(height)
            .filter(|p| *p <= options.max_pixels)
            .ok_or(Error::Limit { what: "image pixels", limit: options.max_pixels as u64 })?;
        let (Ok(w32), Ok(h32)) = (u32::try_from(width), u32::try_from(height)) else {
            return image_error("image dimensions out of range");
        };
        let stencil = entry(self, dict, b"ImageMask", b"IM")?.as_bool().unwrap_or(false);
        let declared_space = match entry(self, dict, b"ColorSpace", b"CS")? {
            _ if stencil => Some(ColorSpace::Gray),
            Object::Null => None,
            o => Some(color_space(self, o, resources, 0)?),
        };
        let decode: Vec<f64> = match entry(self, dict, b"Decode", b"D")? {
            Object::Array(a) => a.iter().filter_map(|o| self.resolve(o).ok()?.as_f64().ok()).collect(),
            _ => Vec::new(),
        };

        // Encoded image data cannot be justified exactly from the
        // dimensions. Eight bytes per pixel is beyond what any codec here
        // produces for an image worth decoding.
        let encoded_cap = pixels.saturating_mul(8).saturating_add(1 << 20).min(self.limits.max_stream_bytes);
        let has_codec = self.filter_chain(dict)?.iter().any(|(name, _)| filters::is_image_filter(name));

        let (space, mut samples, alpha) = if has_codec {
            let partial = self.decode_partial(stream, Cap::strict(encoded_cap))?;
            let Some((codec, parms)) = partial.image else {
                return image_error("image codec is not the last filter");
            };
            if !partial.complete {
                return image_error("encoded image data is damaged");
            }
            let geometry = Geometry { width, height, pixels };
            match filters::canonical_name(&codec) {
                b"DCTDecode" => self.decode_dct(&partial.data, parms.as_ref(), declared_space, geometry)?,
                b"JPXDecode" => self.decode_jpx(&partial.data, dict, declared_space, geometry)?,
                bilevel => {
                    let packed = if bilevel == b"CCITTFaxDecode" {
                        decode_ccitt(&partial.data, parms.as_ref(), geometry)?
                    } else {
                        self.decode_jbig2(&partial.data, parms.as_ref(), geometry)?
                    };
                    let space = declared_space.unwrap_or(ColorSpace::Gray);
                    if space.components() != 1 {
                        return image_error("a bi-level image needs a one-component colour space");
                    }
                    let scale = !matches!(space, ColorSpace::Indexed { .. });
                    (space, unpack(&packed, width, height, 1, 1, scale), None)
                }
            }
        } else {
            let Some(space) = declared_space else {
                return image_error("missing /ColorSpace");
            };
            let bits = if stencil {
                1
            } else {
                match entry(self, dict, b"BitsPerComponent", b"BPC")?.as_i64() {
                    Ok(b @ (1 | 2 | 4 | 8 | 16)) => usize::try_from(b).unwrap_or(8),
                    Ok(other) => return image_error(format!("{other} bits per component is not supported")),
                    Err(_) => return image_error("missing /BitsPerComponent"),
                }
            };
            let components = space.components();
            let expected = width
                .checked_mul(components)
                .and_then(|v| v.checked_mul(bits))
                .map(|row_bits| row_bits.div_ceil(8))
                .and_then(|row| row.checked_mul(height))
                .ok_or_else(|| Error::Image("image size overflows".into()))?;
            let partial = self.decode_partial(stream, Cap::clip(expected))?;
            if partial.data.len() < expected && !options.pad_short_data {
                return image_error(format!("{} bytes of samples, {expected} needed", partial.data.len()));
            }
            let scale = !matches!(space, ColorSpace::Indexed { .. });
            (space, unpack(&partial.data, width, height, components, bits, scale), None)
        };

        let components = space.components();
        let wanted = pixels
            .checked_mul(components)
            .ok_or_else(|| Error::Image("image size overflows".into()))?;
        if samples.len() < wanted && !options.pad_short_data {
            return image_error(format!("{} samples decoded, {wanted} needed", samples.len()));
        }
        samples.resize(wanted, 0);
        if !matches!(space, ColorSpace::Indexed { .. }) {
            apply_decode(&mut samples, &decode, components);
        }
        Ok(Image { width: w32, height: h32, color_space: space, stencil, samples, alpha })
    }

    #[cfg(feature = "dct")]
    fn decode_dct(
        &self,
        data: &[u8],
        parms: Option<&Dictionary>,
        declared: Option<ColorSpace>,
        g: Geometry,
    ) -> Result<Decoded> {
        use rusty_jpeg::{ColorTransform, Decoder, PixelFormat};
        let fail = |e: &dyn std::fmt::Display| Error::Image(format!("JPEG: {e}"));
        let mut decoder = Decoder::new(data);
        decoder.set_max_decoding_buffer_size(g.pixels.saturating_mul(8).saturating_add(1 << 16));
        decoder.read_info().map_err(|e| fail(&e))?;
        let header = decoder.frame_header().ok_or_else(|| Error::Image("JPEG has no frame".into()))?;
        if (usize::from(header.width), usize::from(header.height)) != (g.width, g.height) {
            return image_error("JPEG dimensions disagree with /Width and /Height");
        }
        // `/ColorTransform` overrides what the file's markers say.
        let transform = parms.and_then(|p| p.get_i64(b"ColorTransform"));
        match (header.components, transform) {
            (3, Some(0)) => decoder.set_color_transform(ColorTransform::None),
            (3, Some(_)) => decoder.set_color_transform(ColorTransform::YCbCr),
            (4, Some(0)) => decoder.set_color_transform(ColorTransform::CMYK),
            (4, Some(_)) => decoder.set_color_transform(ColorTransform::YCCK),
            _ => {}
        }
        let mut pixels = decoder.decode().map_err(|e| fail(&e))?;
        let info = decoder.info().ok_or_else(|| Error::Image("JPEG pixel format is not supported".into()))?;
        let space = match info.pixel_format {
            PixelFormat::L8 => ColorSpace::Gray,
            PixelFormat::L16 => {
                // Big-endian 16-bit samples: keep the high byte.
                pixels = pixels.as_chunks::<2>().0.iter().map(|p| p[0]).collect();
                ColorSpace::Gray
            }
            PixelFormat::RGB24 => ColorSpace::Rgb,
            PixelFormat::CMYK32 => {
                // The decoder returns 255 minus the stored value for
                // four-component files. The filter's output is the stored
                // value; a file that stores inverted inks says so with
                // `/Decode [1 0 1 0 1 0 1 0]`.
                for v in &mut pixels {
                    *v = 255 - *v;
                }
                ColorSpace::Cmyk
            }
        };
        let space = match declared {
            Some(d) if d.components() == space.components() => d,
            Some(_) => return image_error("JPEG component count disagrees with /ColorSpace"),
            None => space,
        };
        Ok((space, pixels, None))
    }

    #[cfg(feature = "jpx")]
    fn decode_jpx(
        &self,
        data: &[u8],
        dict: &Dictionary,
        declared: Option<ColorSpace>,
        g: Geometry,
    ) -> Result<Decoded> {
        let fail = |e: &dyn std::fmt::Display| Error::Image(format!("JPEG 2000: {e}"));
        // A palette inside the JPEG 2000 data is expanded, unless the PDF
        // declares an /Indexed space: then the samples are indexes into the
        // PDF's own palette, which takes precedence (ISO 32000-1, 7.4.9).
        let indexed = matches!(declared, Some(ColorSpace::Indexed { .. }));
        let mut options = rusty_jpx::DecodeOptions::new().with_apply_palette(!indexed);
        // Up to four colour channels and one of opacity.
        options.limits.max_samples = (g.pixels as u64).saturating_mul(5);
        let image = rusty_jpx::decode_jpx_with(data, &options).map_err(|e| fail(&e))?;
        if (image.width as usize, image.height as usize) != (g.width, g.height) {
            return image_error("JPEG 2000 dimensions disagree with /Width and /Height");
        }
        // One component as 8-bit samples at full size. Palette indexes are
        // kept as they are; everything else is stretched to 0..=255.
        let plane = |index: usize, scale: bool| -> Result<Vec<u8>> {
            let c = &image.components[index];
            let data = image
                .upsampled(index)
                .ok_or_else(|| Error::Image("JPEG 2000 component has no samples".into()))?;
            Ok(data.iter().map(|v| jpx_sample(*v, c.bits, c.signed, scale)).collect())
        };
        let color: Vec<usize> = (0..image.components.len())
            .filter(|i| image.components[*i].role == rusty_jpx::ChannelRole::Color)
            .collect();
        let color = if color.is_empty() { (0..image.components.len()).collect() } else { color };
        let space = match (declared, color.len()) {
            (Some(d), n) if d.components() <= n => d,
            (Some(_), _) => return image_error("JPEG 2000 has fewer components than /ColorSpace needs"),
            (None, 1) => ColorSpace::Gray,
            (None, 3) => ColorSpace::Rgb,
            (None, 4) => ColorSpace::Cmyk,
            (None, n) => return image_error(format!("JPEG 2000 with {n} colour components and no /ColorSpace")),
        };
        let n = space.components();
        let scale = !matches!(space, ColorSpace::Indexed { .. });
        let planes = color.iter().take(n).map(|i| plane(*i, scale)).collect::<Result<Vec<_>>>()?;
        let mut samples = Vec::with_capacity(g.pixels * n);
        for i in 0..g.pixels {
            for p in &planes {
                samples.push(p.get(i).copied().unwrap_or(0));
            }
        }
        let wants_alpha = self.lookup(dict, b"SMaskInData")?.as_i64().unwrap_or(0) != 0;
        let alpha = if wants_alpha {
            let opacity = (0..image.components.len()).find(|i| {
                matches!(
                    image.components[*i].role,
                    rusty_jpx::ChannelRole::Opacity | rusty_jpx::ChannelRole::PremultipliedOpacity
                )
            });
            opacity.map(|i| plane(i, true)).transpose()?
        } else {
            None
        };
        Ok((space, samples, alpha))
    }

    #[cfg(feature = "jbig2")]
    fn decode_jbig2(&self, data: &[u8], parms: Option<&Dictionary>, g: Geometry) -> Result<Vec<u8>> {
        let globals = match parms.and_then(|p| p.get(b"JBIG2Globals")) {
            Some(o) => match self.resolve(o)? {
                Object::Stream(s) => Some(self.decode_stream(s, self.limits.max_stream_bytes.min(64 << 20))?),
                _ => None,
            },
            None => None,
        };
        // rusty_jbig2 counts a bitmap's pixels with its rows rounded up to
        // whole bytes, so the page's own budget is rounded the same way.
        // Symbols and regions are never larger than the page they build.
        let page_pixels = (g.width.div_ceil(8) as u64 * 8).saturating_mul(g.height as u64);
        let limits = rusty_jbig2::Limits::default().with_max_pixels(page_pixels.max(1 << 16));
        let options = rusty_jbig2::DecodeOptions::new().with_limits(limits);
        let bitmap = rusty_jbig2::decode_jbig2_with(data, globals.as_deref(), &options)
            .map_err(|e| Error::Image(format!("JBIG2: {e}")))?;
        if (bitmap.width as usize, bitmap.height as usize) != (g.width, g.height) {
            return image_error("JBIG2 dimensions disagree with /Width and /Height");
        }
        Ok(bitmap.into_pdf_samples())
    }

    #[cfg(not(feature = "dct"))]
    fn decode_dct(&self, _: &[u8], _: Option<&Dictionary>, _: Option<ColorSpace>, _: Geometry) -> Result<Decoded> {
        Err(Error::UnsupportedFilter("DCTDecode (the `dct` feature is off)".into()))
    }

    #[cfg(not(feature = "jpx"))]
    fn decode_jpx(&self, _: &[u8], _: &Dictionary, _: Option<ColorSpace>, _: Geometry) -> Result<Decoded> {
        Err(Error::UnsupportedFilter("JPXDecode (the `jpx` feature is off)".into()))
    }

    #[cfg(not(feature = "jbig2"))]
    fn decode_jbig2(&self, _: &[u8], _: Option<&Dictionary>, _: Geometry) -> Result<Vec<u8>> {
        Err(Error::UnsupportedFilter("JBIG2Decode (the `jbig2` feature is off)".into()))
    }
}

/// One JPEG 2000 sample as a byte: stretched from its bit depth to
/// 0..=255, or, for a palette index (`scale == false`), kept as the index.
#[cfg_attr(not(feature = "jpx"), allow(dead_code))]
fn jpx_sample(v: i32, bits: u8, signed: bool, scale: bool) -> u8 {
    let bits = u32::from(bits.clamp(1, 31));
    let offset = if signed { 1i64 << (bits - 1) } else { 0 };
    let max = (1i64 << bits) - 1;
    let v = (i64::from(v) + offset).clamp(0, max);
    if scale {
        // v <= max, so the quotient is at most 255.
        (v * 255 / max) as u8
    } else {
        u8::try_from(v).unwrap_or(u8::MAX)
    }
}

/// Colour space, samples, alpha.
type Decoded = (ColorSpace, Vec<u8>, Option<Vec<u8>>);

#[derive(Debug, Clone, Copy)]
struct Geometry {
    width: usize,
    height: usize,
    pixels: usize,
}

/// Widest CCITT row accepted: far past a 600 ppi tabloid page. `/Columns`
/// sizes the decoder's line buffers, so it must be a plausible row width,
/// not whatever the file says.
const MAX_CCITT_COLUMNS: usize = 100_000;

/// CCITT fax data to packed 1-bit rows of `width` pixels, as the filter
/// outputs them (0 is black unless `/BlackIs1`).
#[cfg(feature = "ccitt")]
fn decode_ccitt(data: &[u8], parms: Option<&Dictionary>, g: Geometry) -> Result<Vec<u8>> {
    use rusty_tiff::ccitt::{self, Coding, Options};
    let int = |key: &[u8]| parms.and_then(|p| p.get_i64(key));
    let flag = |key: &[u8]| parms.and_then(|p| p.get_bool(key)).unwrap_or(false);
    let k = int(b"K").unwrap_or(0);
    let columns = match int(b"Columns") {
        None => 1728,
        Some(c) => usize::try_from(c)
            .ok()
            .filter(|c| (1..=MAX_CCITT_COLUMNS).contains(c))
            .ok_or_else(|| Error::Image(format!("CCITT /Columns {c} out of range")))?,
    };
    let coding = match k {
        k if k < 0 => Coding::Group4,
        0 => Coding::Group3_1D,
        _ => Coding::Group3_2D,
    };
    let (Ok(columns32), Ok(rows32)) = (u32::try_from(columns), u32::try_from(g.height)) else {
        return image_error("CCITT dimensions out of range");
    };
    let stride = columns.div_ceil(8);
    let mut options = Options::new(coding, columns32).with_rows(rows32);
    options.encoded_byte_align = flag(b"EncodedByteAlign");
    options.black_is_1 = flag(b"BlackIs1");
    options.max_output_bytes = stride.saturating_mul(g.height).saturating_add(stride);
    let rows = ccitt::decode(data, &options).map_err(|e| Error::Image(format!("CCITT: {e}")))?;
    let out_stride = g.width.div_ceil(8);
    if stride == out_stride {
        return Ok(rows);
    }
    // `/Columns` differs from `/Width`: each row is cut or padded with white.
    let white = if options.black_is_1 { 0x00 } else { 0xFF };
    let mut out = Vec::with_capacity(out_stride * g.height);
    for row in rows.chunks(stride).take(g.height) {
        let keep = row.len().min(out_stride);
        out.extend_from_slice(&row[..keep]);
        out.extend(std::iter::repeat_n(white, out_stride - keep));
    }
    Ok(out)
}

#[cfg(not(feature = "ccitt"))]
fn decode_ccitt(_: &[u8], _: Option<&Dictionary>, _: Geometry) -> Result<Vec<u8>> {
    let _ = MAX_CCITT_COLUMNS;
    Err(Error::UnsupportedFilter("CCITTFaxDecode (the `ccitt` feature is off)".into()))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unpack_scales_small_samples() {
        // 2 bits per sample: 0, 1, 2, 3 -> 0, 85, 170, 255.
        assert_eq!(unpack(&[0b0001_1011], 4, 1, 1, 2, true), [0, 85, 170, 255]);
        assert_eq!(unpack(&[0b0001_1011], 4, 1, 1, 2, false), [0, 1, 2, 3]);
        assert_eq!(unpack(&[0b1010_0000], 3, 1, 1, 1, true), [255, 0, 255]);
        assert_eq!(unpack(&[0x12, 0x34, 0xAB, 0xCD], 2, 1, 1, 16, true), [0x12, 0xAB]);
        // Rows are byte aligned.
        assert_eq!(unpack(&[0b1000_0000, 0b0100_0000], 2, 2, 1, 1, true), [255, 0, 0, 255]);
    }

    #[test]
    fn jpx_samples_keep_palette_indexes() {
        // A 4-bit index stays an index; a 4-bit level is stretched.
        assert_eq!(jpx_sample(3, 4, false, false), 3);
        assert_eq!(jpx_sample(3, 4, false, true), 51);
        assert_eq!(jpx_sample(15, 4, false, true), 255);
        // Signed samples are offset to unsigned first.
        assert_eq!(jpx_sample(-128, 8, true, true), 0);
        assert_eq!(jpx_sample(127, 8, true, true), 255);
        // An index past 255 cannot be represented and saturates.
        assert_eq!(jpx_sample(4000, 12, false, false), 255);
    }

    #[test]
    fn decode_arrays() {
        let mut s = [0, 100, 255];
        apply_decode(&mut s, &[1.0, 0.0], 1);
        assert_eq!(s, [255, 155, 0]);
        let mut s = [10, 20, 30];
        apply_decode(&mut s, &[0.0, 1.0, 1.0, 0.0, 0.0, 1.0], 3);
        assert_eq!(s, [10, 235, 30]);
    }

    #[test]
    fn device_conversions() {
        assert_eq!(cmyk_to_rgb(0, 0, 0, 0), [255, 255, 255]);
        assert_eq!(cmyk_to_rgb(0, 0, 0, 255), [0, 0, 0]);
        assert_eq!(cmyk_to_rgb(255, 0, 0, 0), [0, 255, 255]);
        assert_eq!(luma(255, 255, 255), 255);
        assert_eq!(luma(0, 0, 0), 0);
        let indexed = ColorSpace::Indexed { base: Box::new(ColorSpace::Rgb), palette: vec![1, 2, 3, 4, 5, 6] };
        assert_eq!(convert_rgb(&indexed, &[1, 0, 9]).unwrap(), [4, 5, 6, 1, 2, 3, 0, 0, 0]);
    }
}