Skip to main content

rust_j2k/jp2/
palette.rs

1//! Palette expansion: the Palette box (I.5.3.4, `pclr`) and the Component
2//! Mapping box (I.5.3.5, `cmap`).
3//!
4//! A palette turns a decoded component of indices into output channels: each
5//! `cmap` entry says which component feeds a channel and whether the channel is
6//! that component as coded (`MTYP 0`) or its samples looked up in one palette
7//! column (`MTYP 1`). OpenJPEG 2.5.0 (`opj_jp2_read_pclr`, `opj_jp2_read_cmap`,
8//! `opj_jp2_check_color`, `opj_jp2_apply_pclr`) is the reference. This module
9//! follows it on what is accepted and on the output samples, with the two
10//! exceptions listed after these rules:
11//!
12//! - The `cmap` box holds one entry per palette column (`NPC` entries); a
13//!   shorter box is an error and bytes past the last entry are ignored.
14//! - A `cmap` must come after the `pclr` in file order; at most one of each.
15//! - A palette column mapped by two channels, or a palette channel `i` whose
16//!   column `i` no channel maps (a direct channel counts as mapping column 0),
17//!   is an error.
18//! - A palette channel `i` must look up column `i`. OpenJPEG has no general
19//!   mapping, so another column is [`Error::Unsupported`].
20//! - A single-component file whose mapping leaves a palette column unused is
21//!   read as the identity mapping (channel `i` from column `i`), OpenJPEG's
22//!   correction for files with a broken `cmap`.
23//! - A palette index is clamped to `0..NE`.
24//! - An entry is read as OpenJPEG reads it: at most 4 bytes, unsigned, so a
25//!   signed column is not sign-extended and stray high bits are kept.
26//! - A palette channel takes its depth and sign from its column's `Bi`; a
27//!   direct channel `i` takes them from `Bi` of column `i`. Samples may fall
28//!   outside that declared range.
29//!
30//! The exceptions:
31//!
32//! - A palette column deeper than the `i32` sample container (over 31 bits
33//!   unsigned, 32 signed) is [`Error::Unsupported`] when the palette is
34//!   applied, as such a codestream component is. OpenJPEG decodes it.
35//! - Each channel is built on its own source component's grid, so palette and
36//!   direct channels from components of different sub-sampling decode
37//!   correctly. OpenJPEG sizes every channel by the first one's grid and
38//!   crashes or reads uninitialized memory.
39//!
40//! [`plan`] reads the boxes and the main header into a [`PalettePlan`] before
41//! any tile is decoded; [`PalettePlan::apply`] then builds the channels from
42//! the decoded components. The box layout is checked whenever a palette is
43//! present. The mapping, the column depths, and the sample limit are checked
44//! only when the palette is applied, so a caller asking for the raw channels
45//! gets them whatever the `cmap` says, as OpenJPEG does with its "ignore
46//! palette" flag. The budget bounds the expanded channels; with the decoded
47//! components still held, the peak is about twice it (`check_budget`).
48
49use super::header::Jp2Header;
50use super::metadata::{Association, ChannelDefinition, ChannelType, Jp2Metadata};
51use crate::codestream::markers::Siz;
52use crate::samples;
53use crate::{Component, ComponentInfo, Error, Result};
54
55/// The most entries a palette may hold (I.5.3.4: `NE` is 1..=1024).
56const MAX_ENTRIES: u16 = 1024;
57
58/// One palette column's sample format, from its `Bi` byte.
59#[derive(Debug, Clone, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct PaletteColumn {
62    /// Bit depth, `(Bi & 0x7F) + 1`: 1 to 128.
63    pub bit_depth: u8,
64    /// Whether the column's values are signed (`Bi & 0x80`).
65    pub signed: bool,
66}
67
68impl PaletteColumn {
69    /// Bytes per stored entry as OpenJPEG reads the table: the depth rounded
70    /// up to whole bytes, but at most 4. A column deeper than 32 bits is
71    /// therefore read at a 4-byte stride; such a column is never applied (see
72    /// [`PaletteColumn::fits_i32`]), so this only decides how long the table must be.
73    fn entry_bytes(&self) -> usize {
74        usize::from(self.bit_depth).div_ceil(8).min(4)
75    }
76
77    /// Whether the column's range fits the `i32` sample container (signed up
78    /// to 32 bits, unsigned up to 31), as the codestream's components must.
79    fn fits_i32(&self) -> bool {
80        if self.signed {
81            self.bit_depth <= 32
82        } else {
83            self.bit_depth <= 31
84        }
85    }
86}
87
88/// A JP2 file's palette, from its `pclr` box: a table of `NE` entries (1 to
89/// 1024), each a row of one value per column (1 to 255 columns).
90///
91/// Entry `j`, column `i` is `entry(j)[i]`. A value is the entry's stored
92/// bytes (the column's depth rounded up to whole bytes, at most 4) read as a
93/// big-endian unsigned number and cast to `i32`, as OpenJPEG does: a signed
94/// column's values are not sign-extended. The decoder clamps each index to
95/// `0..entry_count()`; [`entry`](Self::entry) does not, and returns `None`
96/// past the last entry.
97///
98/// The table is at most 1024 entries by 255 columns of `i32`, about 1 MiB, and
99/// is bounded by the bytes the `pclr` box holds. It is `#[non_exhaustive]` and
100/// built only by the decoder.
101#[derive(Debug, Clone, PartialEq, Eq)]
102#[non_exhaustive]
103pub struct Palette {
104    /// `NE`, 1..=1024.
105    entries: u16,
106    /// One per column (`NPC`, 1..=255).
107    columns: Vec<PaletteColumn>,
108    /// `NE * NPC` values, entry-major: entry `j` column `i` at
109    /// `j * NPC + i`.
110    values: Vec<i32>,
111}
112
113impl Palette {
114    /// Parse a `pclr` box: `NE` (2 bytes), `NPC` (1 byte), `NPC` `Bi` bytes,
115    /// then `NE` rows of `NPC` entries (see [`PaletteColumn::entry_bytes`]).
116    pub(super) fn parse(payload: &[u8]) -> Result<Self> {
117        let &[ne0, ne1, npc, ref rest @ ..] = payload else {
118            return Err(Error::file_format(format!(
119                "the `pclr` box holds {} bytes, fewer than its 3-byte header",
120                payload.len()
121            )));
122        };
123        let entries = u16::from_be_bytes([ne0, ne1]);
124        if !(1..=MAX_ENTRIES).contains(&entries) {
125            return Err(Error::file_format(format!(
126                "the `pclr` box declares {entries} entries; a palette holds 1 to {MAX_ENTRIES}"
127            )));
128        }
129        if npc == 0 {
130            return Err(Error::file_format(
131                "the `pclr` box declares 0 palette columns",
132            ));
133        }
134        let Some((bi, table)) = rest.split_at_checked(usize::from(npc)) else {
135            return Err(Error::file_format(format!(
136                "the `pclr` box declares {npc} columns but ends inside their `Bi` bytes"
137            )));
138        };
139        let columns: Vec<PaletteColumn> = bi
140            .iter()
141            .map(|&b| PaletteColumn {
142                bit_depth: (b & 0x7F) + 1,
143                signed: b & 0x80 != 0,
144            })
145            .collect();
146
147        // Bound the table by the bytes the box holds before allocating it.
148        let row_bytes: usize = columns.iter().map(|c| c.entry_bytes()).sum();
149        let needed = row_bytes
150            .checked_mul(usize::from(entries))
151            .ok_or_else(|| Error::file_format("the `pclr` box's entry table size overflows"))?;
152        if table.len() < needed {
153            return Err(Error::file_format(format!(
154                "the `pclr` box's {entries} x {npc} entries need {needed} bytes but it holds {}",
155                table.len()
156            )));
157        }
158
159        let mut values = Vec::with_capacity(usize::from(entries) * columns.len());
160        let mut at = 0;
161        for _ in 0..entries {
162            for column in &columns {
163                let width = column.entry_bytes();
164                let bytes = table
165                    .get(at..at + width)
166                    .ok_or_else(|| Error::inconsistent("palette entry past its table"))?;
167                at += width;
168                values.push(entry_value(bytes));
169            }
170        }
171        Ok(Palette {
172            entries,
173            columns,
174            values,
175        })
176    }
177
178    /// Each column's depth and sign (`NPC` of them), in column order.
179    #[must_use]
180    pub fn columns(&self) -> &[PaletteColumn] {
181        &self.columns
182    }
183
184    /// The number of entries, `NE`.
185    #[must_use]
186    pub fn entry_count(&self) -> usize {
187        usize::from(self.entries)
188    }
189
190    /// Entry `index`: one value per column, or `None` past the last entry.
191    #[must_use]
192    pub fn entry(&self, index: usize) -> Option<&[i32]> {
193        let width = self.columns.len();
194        if index >= self.entry_count() {
195            return None;
196        }
197        // `index < NE <= 65535`, so this cannot overflow.
198        self.values.get(index * width..(index + 1) * width)
199    }
200
201    /// The value of entry `index` (clamped to `0..NE`) in `column`.
202    fn lookup(&self, index: i32, column: usize) -> i32 {
203        let top = i32::from(self.entries) - 1;
204        let row = index.clamp(0, top) as usize;
205        self.values[row * self.columns.len() + column]
206    }
207}
208
209/// An entry's stored bytes (1 to 4 of them), big-endian and unsigned, then
210/// reinterpreted as `i32` as OpenJPEG's `(OPJ_INT32)` cast does.
211fn entry_value(bytes: &[u8]) -> i32 {
212    let value = bytes.iter().fold(0u32, |acc, &b| (acc << 8) | u32::from(b));
213    value as i32
214}
215
216/// One channel of a file's component mapping (`cmap` box): where an output
217/// channel's samples come from.
218///
219/// The decoder's output channels follow these entries in order, before any
220/// `cdef` reordering. The mapping reported is the one the default decode
221/// applies, whatever the options: for a one-component file whose `cmap`
222/// leaves a palette column unused, OpenJPEG reads the mapping as every channel
223/// looking up its own column, and so does this decoder, so that is what is
224/// reported. Only a `cmap` the default decode refuses is reported as written
225/// (and only under [`raw_channels`](crate::DecodeOptions::raw_channels),
226/// which does not check it).
227#[derive(Debug, Clone, PartialEq, Eq)]
228#[non_exhaustive]
229pub struct ChannelMapping {
230    /// `CMP`: the codestream component this channel reads.
231    pub component: u16,
232    /// `MTYP` and `PCOL`: how the component becomes the channel.
233    pub kind: MappingKind,
234}
235
236/// How a mapped channel is made from its component (`MTYP`).
237#[derive(Debug, Clone, PartialEq, Eq)]
238#[non_exhaustive]
239pub enum MappingKind {
240    /// `MTYP` 0: the component's samples as coded.
241    Direct,
242    /// `MTYP` 1: the component's samples are indexes into this palette
243    /// column (`PCOL`).
244    Palette {
245        /// The column to look up, counting from 0.
246        column: u8,
247    },
248    /// An `MTYP` other than 0 and 1, which the standard reserves. Only
249    /// reported under [`raw_channels`](crate::DecodeOptions::raw_channels),
250    /// which does not check the mapping; a normal decode refuses such a file.
251    Reserved {
252        /// The `MTYP` value.
253        mtyp: u8,
254        /// The `PCOL` value.
255        pcol: u8,
256    },
257}
258
259fn public_source(source: Source) -> ChannelMapping {
260    match source {
261        Source::Direct { component } => ChannelMapping {
262            component,
263            kind: MappingKind::Direct,
264        },
265        Source::Palette { component, column } => ChannelMapping {
266            component,
267            kind: MappingKind::Palette { column },
268        },
269    }
270}
271
272/// `cmap` entries as public data, in order.
273fn public_mapping(entries: &[(u16, u8, u8)]) -> Vec<ChannelMapping> {
274    entries
275        .iter()
276        .map(|&(component, mtyp, pcol)| ChannelMapping {
277            component,
278            kind: match mtyp {
279                0 => MappingKind::Direct,
280                1 => MappingKind::Palette { column: pcol },
281                mtyp => MappingKind::Reserved { mtyp, pcol },
282            },
283        })
284        .collect()
285}
286
287/// Where one output channel's samples come from.
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub(crate) enum Source {
290    /// `MTYP 0`: codestream component `component` as coded.
291    Direct { component: u16 },
292    /// `MTYP 1`: codestream component `component`'s samples looked up in
293    /// palette column `column`.
294    Palette { component: u16, column: u8 },
295}
296
297impl Source {
298    fn component(self) -> u16 {
299        match self {
300            Source::Direct { component } | Source::Palette { component, .. } => component,
301        }
302    }
303}
304
305/// One output channel of a palettized file, known from the boxes and the main
306/// header alone: its source and its sample format. The grid size comes from
307/// the source component.
308#[derive(Debug, Clone, Copy, PartialEq, Eq)]
309pub(crate) struct PlannedChannel {
310    pub(crate) source: Source,
311    pub(crate) bit_depth: u8,
312    pub(crate) signed: bool,
313    pub(crate) x_sampling: u8,
314    pub(crate) y_sampling: u8,
315}
316
317/// What the palette boxes do to a file's channels. Computed before any tile is
318/// decoded, so a header-only read can report the output channels too.
319#[derive(Debug, Clone, PartialEq, Eq)]
320pub(crate) enum PalettePlan {
321    /// No palette applies: no `pclr`, or a `pclr` without a `cmap` (I.5.3.4:
322    /// both or neither, so the palette is dropped). The channels are the
323    /// components as coded.
324    None,
325    /// The caller asked for the raw channels of a file whose palette would
326    /// have applied. `index_components[k]` is set for each component a
327    /// palette channel would have looked up, so it can be labeled as an
328    /// index plane rather than a color.
329    Skipped {
330        index_components: Vec<bool>,
331        palette: Palette,
332        mapping: Vec<ChannelMapping>,
333    },
334    /// The palette applies: one output channel per palette column.
335    Apply {
336        palette: Palette,
337        channels: Vec<PlannedChannel>,
338    },
339}
340
341/// Read the file's palette boxes into a [`PalettePlan`], for a decode at
342/// `reduction` resolution levels down. The box layout is always checked; the
343/// mapping, the column depths and the expanded sample count only when the
344/// palette is applied.
345pub(crate) fn plan(
346    header: &Jp2Header<'_>,
347    siz: &Siz,
348    reduction: u8,
349    cap: u64,
350    raw_channels: bool,
351) -> Result<PalettePlan> {
352    let (pclrs, cmaps) = (header.pclr(), header.cmap());
353    if pclrs.len() > 1 {
354        return Err(Error::file_format("the file has more than one `pclr` box"));
355    }
356    if cmaps.len() > 1 {
357        return Err(Error::file_format("the file has more than one `cmap` box"));
358    }
359    let Some(pclr) = pclrs.first() else {
360        if cmaps.is_empty() {
361            return Ok(PalettePlan::None);
362        }
363        return Err(Error::file_format(
364            "the file has a `cmap` box but no `pclr` box",
365        ));
366    };
367    if cmap_before_pclr(header) {
368        return Err(Error::file_format(
369            "the `cmap` box comes before the `pclr` box it maps",
370        ));
371    }
372    let palette = Palette::parse(pclr)?;
373    let Some(cmap) = cmaps.first() else {
374        return Ok(PalettePlan::None);
375    };
376    let entries = parse_cmap(cmap, palette.columns.len())?;
377    if raw_channels {
378        let mut index_components = vec![false; siz.components.len()];
379        for &(component, mtyp, _) in &entries {
380            if let (1, Some(slot)) = (mtyp, index_components.get_mut(usize::from(component))) {
381                *slot = true;
382            }
383        }
384        // The mapping the default decode would use, with OpenJPEG's
385        // correction. A `cmap` the default decode would refuse has no such
386        // mapping, so it is reported as written.
387        let mapping = match map_channels(&entries, palette.columns.len(), siz.components.len()) {
388            Ok(sources) => sources.into_iter().map(public_source).collect(),
389            Err(_) => public_mapping(&entries),
390        };
391        return Ok(PalettePlan::Skipped {
392            index_components,
393            palette,
394            mapping,
395        });
396    }
397    let sources = map_channels(&entries, palette.columns.len(), siz.components.len())?;
398    let channels: Vec<PlannedChannel> = sources
399        .into_iter()
400        .enumerate()
401        .map(|(i, source)| plan_channel(i, source, &palette, siz))
402        .collect::<Result<_>>()?;
403    check_budget(&channels, siz, reduction, cap)?;
404    Ok(PalettePlan::Apply { palette, channels })
405}
406
407/// Whether the first `cmap` comes before the first `pclr` in read order (every
408/// `jp2h`, then the header boxes misplaced after it). OpenJPEG needs the
409/// palette first to know how many `cmap` entries to read.
410fn cmap_before_pclr(header: &Jp2Header<'_>) -> bool {
411    let position = |kind: &[u8; 4]| header.children.iter().position(|c| &c.kind == kind);
412    match (position(b"cmap"), position(b"pclr")) {
413        (Some(cmap), Some(pclr)) => cmap < pclr,
414        _ => false,
415    }
416}
417
418/// Parse a `cmap` box into `(CMP, MTYP, PCOL)` triples, one per palette
419/// column. Bytes after the last of them are ignored, as OpenJPEG does.
420fn parse_cmap(payload: &[u8], count: usize) -> Result<Vec<(u16, u8, u8)>> {
421    let needed = count * 4;
422    let Some(body) = payload.get(..needed) else {
423        return Err(Error::file_format(format!(
424            "the `cmap` box holds {} bytes; mapping {count} palette columns needs {needed}",
425            payload.len()
426        )));
427    };
428    Ok(body
429        .chunks_exact(4)
430        .map(|e| (u16::from_be_bytes([e[0], e[1]]), e[2], e[3]))
431        .collect())
432}
433
434/// Check the `cmap` entries the way `opj_jp2_check_color` does, and turn them
435/// into channel sources.
436///
437/// OpenJPEG tracks which columns are used: a palette channel uses its column,
438/// and a direct channel (whose `PCOL` is 0) marks column 0. A malformed entry,
439/// a column used by two palette channels, or a palette channel `i` whose
440/// column `i` ends up unused is [`Error::FileFormat`]; those come first, so a
441/// malformed file reports its fault. A palette channel `i` that looks up
442/// another column is then [`Error::Unsupported`] (OpenJPEG's "implementation
443/// limitation"). A single-component file that still leaves a column unused is
444/// read as the identity mapping.
445fn map_channels(
446    entries: &[(u16, u8, u8)],
447    columns: usize,
448    components: usize,
449) -> Result<Vec<Source>> {
450    let mut used = vec![false; columns];
451    for (i, &(component, mtyp, pcol)) in entries.iter().enumerate() {
452        if usize::from(component) >= components {
453            return Err(Error::file_format(format!(
454                "`cmap` channel {i} maps component {component}, but the codestream has {components}"
455            )));
456        }
457        let column = usize::from(pcol);
458        if mtyp > 1 {
459            return Err(Error::file_format(format!(
460                "`cmap` channel {i} has mapping type {mtyp}; only 0 (direct) and 1 (palette) exist"
461            )));
462        }
463        if column >= columns {
464            return Err(Error::file_format(format!(
465                "`cmap` channel {i} names palette column {pcol}, but the palette has {columns}"
466            )));
467        }
468        if mtyp == 1 && used[column] {
469            return Err(Error::file_format(format!(
470                "`cmap` maps palette column {pcol} twice"
471            )));
472        }
473        if mtyp == 0 && pcol != 0 {
474            return Err(Error::file_format(format!(
475                "`cmap` channel {i} uses component {component} directly but names palette \
476                 column {pcol}; a direct channel's `PCOL` must be 0"
477            )));
478        }
479        used[column] = true;
480    }
481    for (i, &(_, mtyp, _)) in entries.iter().enumerate() {
482        if mtyp != 0 && !used[i] {
483            return Err(Error::file_format(format!(
484                "`cmap` channel {i} is a palette channel but palette column {i} is not mapped"
485            )));
486        }
487    }
488    for (i, &(_, mtyp, pcol)) in entries.iter().enumerate() {
489        if mtyp == 1 && usize::from(pcol) != i {
490            return Err(Error::unsupported(format!(
491                "`cmap` channel {i} looks up palette column {pcol}; only channel i from \
492                 column i is decoded"
493            )));
494        }
495    }
496
497    // OpenJPEG's correction for a broken single-component `cmap` ("Component
498    // mapping seems wrong. Trying to correct."): every channel becomes a
499    // lookup in its own column.
500    let correct = components == 1 && used.contains(&false);
501    entries
502        .iter()
503        .enumerate()
504        .map(|(i, &(component, mtyp, pcol))| {
505            Ok(if correct {
506                let column = u8::try_from(i).map_err(|_| {
507                    Error::inconsistent(format!("palette column {i} exceeds `NPC`"))
508                })?;
509                Source::Palette { component, column }
510            } else if mtyp == 0 {
511                Source::Direct { component }
512            } else {
513                Source::Palette {
514                    component,
515                    column: pcol,
516                }
517            })
518        })
519        .collect()
520}
521
522/// Channel `i`'s sample format. A palette channel takes its column's `Bi`; a
523/// direct channel takes `Bi` of column `i`, as OpenJPEG labels it (`i` is
524/// below `NPC`, since `cmap` holds one entry per column). The sub-sampling is
525/// the source component's.
526fn plan_channel(i: usize, source: Source, palette: &Palette, siz: &Siz) -> Result<PlannedChannel> {
527    let label = match source {
528        Source::Direct { .. } => i,
529        Source::Palette { column, .. } => usize::from(column),
530    };
531    let column = palette
532        .columns
533        .get(label)
534        .ok_or_else(|| Error::inconsistent(format!("no palette column {label}")))?;
535    if !column.fits_i32() {
536        return Err(Error::unsupported(format!(
537            "palette channel {i} has depth {} ({}), which exceeds the i32 sample container",
538            column.bit_depth,
539            if column.signed { "signed" } else { "unsigned" }
540        )));
541    }
542    let component = siz
543        .components
544        .get(usize::from(source.component()))
545        .ok_or_else(|| Error::inconsistent("`cmap` component past `SIZ`"))?;
546    Ok(PlannedChannel {
547        source,
548        bit_depth: column.bit_depth,
549        signed: column.signed,
550        x_sampling: component.x_sampling,
551        y_sampling: component.y_sampling,
552    })
553}
554
555/// Hold the expanded channels to `cap` samples, from the SIZ extents at
556/// `reduction`, before any tile is decoded or plane allocated. The limit
557/// bounds the expanded channels alone: the decoded components are held while
558/// the channels are built from them, so the peak is about twice the limit
559/// (see [`crate::samples`]).
560fn check_budget(channels: &[PlannedChannel], siz: &Siz, reduction: u8, cap: u64) -> Result<()> {
561    let mut total: u64 = 0;
562    for channel in channels {
563        let index = usize::from(channel.source.component());
564        let (width, height) = siz
565            .component_extent_at(index, reduction)
566            .ok_or_else(|| Error::inconsistent(format!("`SIZ` declares no component {index}")))?;
567        total = total.saturating_add(u64::from(width) * u64::from(height));
568    }
569    if total > cap {
570        let what = format!(
571            "palette expansion to {} channels{}",
572            channels.len(),
573            samples::at(reduction)
574        );
575        return Err(samples::over(&what, total, cap));
576    }
577    Ok(())
578}
579
580impl PalettePlan {
581    /// The format of each output channel, from the plan and SIZ alone: the
582    /// palette's channels when it applies, otherwise the codestream's
583    /// components as coded.
584    pub(crate) fn output_channels(&self, siz: &Siz, reduction: u8) -> Vec<ComponentInfo> {
585        match self {
586            PalettePlan::Apply { channels, .. } => channels
587                .iter()
588                .map(|c| {
589                    ComponentInfo::on_grid(
590                        siz,
591                        c.bit_depth,
592                        c.signed,
593                        c.x_sampling,
594                        c.y_sampling,
595                        reduction,
596                    )
597                })
598                .collect(),
599            PalettePlan::None | PalettePlan::Skipped { .. } => {
600                ComponentInfo::of_siz(siz, reduction)
601            }
602        }
603    }
604
605    /// The output channels from the decoded components, in SIZ order. Each
606    /// channel is built on its source component's grid. A direct channel
607    /// takes its component's plane when no later channel reads it.
608    pub(crate) fn apply(&self, mut components: Vec<Component>) -> Result<Vec<Component>> {
609        let PalettePlan::Apply { palette, channels } = self else {
610            return Ok(components);
611        };
612        let mut reads_left = vec![0usize; components.len()];
613        for channel in channels {
614            let index = usize::from(channel.source.component());
615            let slot = reads_left.get_mut(index).ok_or_else(|| {
616                Error::inconsistent(format!(
617                    "`cmap` names component {index}, which was not decoded"
618                ))
619            })?;
620            *slot += 1;
621        }
622
623        let mut out = Vec::with_capacity(channels.len());
624        for channel in channels {
625            let index = usize::from(channel.source.component());
626            reads_left[index] -= 1;
627            let from = &mut components[index];
628            let samples = match channel.source {
629                Source::Direct { .. } if reads_left[index] == 0 => {
630                    std::mem::take(&mut from.samples)
631                }
632                Source::Direct { .. } => from.samples.clone(),
633                Source::Palette { column, .. } => from
634                    .samples
635                    .iter()
636                    .map(|&k| palette.lookup(k, usize::from(column)))
637                    .collect(),
638            };
639            out.push(Component::new(
640                from.width,
641                from.height,
642                channel.bit_depth,
643                channel.signed,
644                channel.x_sampling,
645                channel.y_sampling,
646                samples,
647            ));
648        }
649        Ok(out)
650    }
651
652    /// Record the plan on the file's metadata: whether the palette was
653    /// applied, and, when the caller skipped it, which raw channels are index
654    /// planes. An index plane is `Unspecified` with no association: it is not
655    /// a color until it goes through the palette.
656    pub(crate) fn describe(&self, metadata: &mut Jp2Metadata) {
657        metadata.palette_applied = matches!(self, PalettePlan::Apply { .. });
658        match self {
659            PalettePlan::None => {}
660            PalettePlan::Apply { palette, channels } => {
661                metadata.palette = Some(palette.clone());
662                metadata.channel_mapping =
663                    Some(channels.iter().map(|c| public_source(c.source)).collect());
664            }
665            PalettePlan::Skipped {
666                palette, mapping, ..
667            } => {
668                metadata.palette = Some(palette.clone());
669                metadata.channel_mapping = Some(mapping.clone());
670            }
671        }
672        if let PalettePlan::Skipped {
673            index_components, ..
674        } = self
675        {
676            for (channel, &index) in metadata.channels.iter_mut().zip(index_components) {
677                if index {
678                    *channel = ChannelDefinition {
679                        kind: ChannelType::Unspecified,
680                        association: Association::None,
681                    };
682                }
683            }
684        }
685    }
686}
687
688#[cfg(test)]
689mod tests {
690    use super::*;
691    use crate::codestream::markers::SizComponent;
692
693    fn pclr(entries: u16, bi: &[u8], table: &[u8]) -> Vec<u8> {
694        let mut out = entries.to_be_bytes().to_vec();
695        out.push(u8::try_from(bi.len()).unwrap());
696        out.extend_from_slice(bi);
697        out.extend_from_slice(table);
698        out
699    }
700
701    #[test]
702    fn entries_are_read_at_their_byte_widths() {
703        // 2 entries, columns of 8, 12 and 1 bits: 1 + 2 + 1 bytes per row.
704        let palette =
705            Palette::parse(&pclr(2, &[7, 11, 0], &[1, 0x0A, 0xBC, 1, 2, 0x0F, 0xFF, 0])).unwrap();
706        assert_eq!(palette.values, [1, 0xABC, 1, 2, 0xFFF, 0]);
707        assert_eq!(
708            palette.columns,
709            [
710                PaletteColumn {
711                    bit_depth: 8,
712                    signed: false
713                },
714                PaletteColumn {
715                    bit_depth: 12,
716                    signed: false
717                },
718                PaletteColumn {
719                    bit_depth: 1,
720                    signed: false
721                },
722            ]
723        );
724    }
725
726    /// OpenJPEG reads a column deeper than 32 bits at a 4-byte stride, so a
727    /// 38-bit column's table is 4 bytes per entry.
728    #[test]
729    fn a_deep_column_is_read_at_a_four_byte_stride() {
730        let palette = Palette::parse(&pclr(2, &[37], &[0, 0, 0, 7, 0xFF, 0xFF, 0xFF, 0xFF]))
731            .expect("4 bytes per entry is enough");
732        assert_eq!(palette.values, [7, -1]);
733        assert!(matches!(
734            Palette::parse(&pclr(2, &[37], &[0; 7])),
735            Err(Error::FileFormat(_))
736        ));
737    }
738
739    /// Measured with `opj_decompress` 2.5.0: a signed 12-bit column holding
740    /// `0xFFF` decodes to 4095, not -1, and a 12-bit entry `0xF000` keeps its
741    /// high bits.
742    #[test]
743    fn entries_are_unsigned_and_unmasked_as_in_openjpeg() {
744        let palette = Palette::parse(&pclr(1, &[0x8B, 11], &[0x0F, 0xFF, 0xF0, 0x00])).unwrap();
745        assert!(palette.columns[0].signed);
746        assert_eq!(palette.values, [4095, 0xF000]);
747    }
748
749    #[test]
750    fn indices_clamp_to_the_palette() {
751        let palette = Palette::parse(&pclr(3, &[7], &[10, 20, 30])).unwrap();
752        let looked: Vec<i32> = [-5, 0, 1, 2, 3, 1000, i32::MIN, i32::MAX]
753            .iter()
754            .map(|&k| palette.lookup(k, 0))
755            .collect();
756        assert_eq!(looked, [10, 10, 20, 30, 30, 30, 10, 30]);
757    }
758
759    fn siz(width: u32, height: u32) -> Siz {
760        Siz {
761            x_size: width,
762            y_size: height,
763            x_offset: 0,
764            y_offset: 0,
765            tile_width: width,
766            tile_height: height,
767            tile_x_offset: 0,
768            tile_y_offset: 0,
769            components: vec![SizComponent {
770                bit_depth: 8,
771                signed: false,
772                x_sampling: 1,
773                y_sampling: 1,
774            }],
775        }
776    }
777
778    /// 255 channels over a 600x500 component is 76.5 M samples, over a
779    /// 2^26 limit: refused from SIZ alone. A reduced decode, or fewer
780    /// channels, fits.
781    #[test]
782    fn the_expansion_is_held_to_the_sample_budget() {
783        let channel = |column| PlannedChannel {
784            source: Source::Palette {
785                component: 0,
786                column,
787            },
788            bit_depth: 8,
789            signed: false,
790            x_sampling: 1,
791            y_sampling: 1,
792        };
793        let channels: Vec<PlannedChannel> = (0..=254).map(channel).collect();
794        let siz = siz(600, 500);
795        assert!(matches!(
796            check_budget(&channels, &siz, 0, 1 << 26),
797            Err(Error::Limit(_))
798        ));
799        assert!(check_budget(&channels, &siz, 1, 1 << 26).is_ok());
800        assert!(check_budget(&channels[..200], &siz, 0, 1 << 26).is_ok());
801    }
802
803    /// A direct channel moves its component's plane when nothing later reads
804    /// it, and copies it otherwise; either way the samples are the component's.
805    #[test]
806    fn a_direct_channel_moves_or_copies_its_plane() {
807        let palette = Palette::parse(&pclr(2, &[7, 7], &[10, 20, 30, 40])).unwrap();
808        let direct = PlannedChannel {
809            source: Source::Direct { component: 0 },
810            bit_depth: 8,
811            signed: false,
812            x_sampling: 1,
813            y_sampling: 1,
814        };
815        let lookup = PlannedChannel {
816            source: Source::Palette {
817                component: 0,
818                column: 1,
819            },
820            ..direct
821        };
822        let index = Component::new(2, 1, 8, false, 1, 1, vec![0, 1]);
823        for channels in [
824            vec![direct, lookup],
825            vec![lookup, direct],
826            vec![direct, direct],
827        ] {
828            let plan = PalettePlan::Apply {
829                palette: palette.clone(),
830                channels: channels.clone(),
831            };
832            let out = plan.apply(vec![index.clone()]).unwrap();
833            for (channel, got) in channels.iter().zip(&out) {
834                let want = match channel.source {
835                    Source::Direct { .. } => vec![0, 1],
836                    Source::Palette { .. } => vec![20, 40],
837                };
838                assert_eq!(got.samples, want, "{channels:?}");
839            }
840        }
841    }
842
843    #[test]
844    fn entries_are_big_endian_and_cast_to_i32() {
845        assert_eq!(entry_value(&[0x01, 0x02, 0x03, 0x04]), 0x0102_0304);
846        assert_eq!(entry_value(&[0xFF, 0xFF, 0xFF, 0xFF]), -1);
847        assert_eq!(entry_value(&[0x0A, 0xBC]), 0xABC);
848    }
849}