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::FileFormat(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::FileFormat(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::FileFormat(
131                "the `pclr` box declares 0 palette columns".into(),
132            ));
133        }
134        let Some((bi, table)) = rest.split_at_checked(usize::from(npc)) else {
135            return Err(Error::FileFormat(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.checked_mul(usize::from(entries)).ok_or_else(|| {
150            Error::FileFormat("the `pclr` box's entry table size overflows".into())
151        })?;
152        if table.len() < needed {
153            return Err(Error::FileFormat(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".into()))?;
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::FileFormat(
355            "the file has more than one `pclr` box".into(),
356        ));
357    }
358    if cmaps.len() > 1 {
359        return Err(Error::FileFormat(
360            "the file has more than one `cmap` box".into(),
361        ));
362    }
363    let Some(pclr) = pclrs.first() else {
364        if cmaps.is_empty() {
365            return Ok(PalettePlan::None);
366        }
367        return Err(Error::FileFormat(
368            "the file has a `cmap` box but no `pclr` box".into(),
369        ));
370    };
371    if cmap_before_pclr(header) {
372        return Err(Error::FileFormat(
373            "the `cmap` box comes before the `pclr` box it maps".into(),
374        ));
375    }
376    let palette = Palette::parse(pclr)?;
377    let Some(cmap) = cmaps.first() else {
378        return Ok(PalettePlan::None);
379    };
380    let entries = parse_cmap(cmap, palette.columns.len())?;
381    if raw_channels {
382        let mut index_components = vec![false; siz.components.len()];
383        for &(component, mtyp, _) in &entries {
384            if let (1, Some(slot)) = (mtyp, index_components.get_mut(usize::from(component))) {
385                *slot = true;
386            }
387        }
388        // The mapping the default decode would use, with OpenJPEG's
389        // correction. A `cmap` the default decode would refuse has no such
390        // mapping, so it is reported as written.
391        let mapping = match map_channels(&entries, palette.columns.len(), siz.components.len()) {
392            Ok(sources) => sources.into_iter().map(public_source).collect(),
393            Err(_) => public_mapping(&entries),
394        };
395        return Ok(PalettePlan::Skipped {
396            index_components,
397            palette,
398            mapping,
399        });
400    }
401    let sources = map_channels(&entries, palette.columns.len(), siz.components.len())?;
402    let channels: Vec<PlannedChannel> = sources
403        .into_iter()
404        .enumerate()
405        .map(|(i, source)| plan_channel(i, source, &palette, siz))
406        .collect::<Result<_>>()?;
407    check_budget(&channels, siz, reduction, cap)?;
408    Ok(PalettePlan::Apply { palette, channels })
409}
410
411/// Whether the first `cmap` comes before the first `pclr` in read order (every
412/// `jp2h`, then the header boxes misplaced after it). OpenJPEG needs the
413/// palette first to know how many `cmap` entries to read.
414fn cmap_before_pclr(header: &Jp2Header<'_>) -> bool {
415    let position = |kind: &[u8; 4]| header.children.iter().position(|c| &c.kind == kind);
416    match (position(b"cmap"), position(b"pclr")) {
417        (Some(cmap), Some(pclr)) => cmap < pclr,
418        _ => false,
419    }
420}
421
422/// Parse a `cmap` box into `(CMP, MTYP, PCOL)` triples, one per palette
423/// column. Bytes after the last of them are ignored, as OpenJPEG does.
424fn parse_cmap(payload: &[u8], count: usize) -> Result<Vec<(u16, u8, u8)>> {
425    let needed = count * 4;
426    let Some(body) = payload.get(..needed) else {
427        return Err(Error::FileFormat(format!(
428            "the `cmap` box holds {} bytes; mapping {count} palette columns needs {needed}",
429            payload.len()
430        )));
431    };
432    Ok(body
433        .chunks_exact(4)
434        .map(|e| (u16::from_be_bytes([e[0], e[1]]), e[2], e[3]))
435        .collect())
436}
437
438/// Check the `cmap` entries the way `opj_jp2_check_color` does, and turn them
439/// into channel sources.
440///
441/// OpenJPEG tracks which columns are used: a palette channel uses its column,
442/// and a direct channel (whose `PCOL` is 0) marks column 0. A malformed entry,
443/// a column used by two palette channels, or a palette channel `i` whose
444/// column `i` ends up unused is [`Error::FileFormat`]; those come first, so a
445/// malformed file reports its fault. A palette channel `i` that looks up
446/// another column is then [`Error::Unsupported`] (OpenJPEG's "implementation
447/// limitation"). A single-component file that still leaves a column unused is
448/// read as the identity mapping.
449fn map_channels(
450    entries: &[(u16, u8, u8)],
451    columns: usize,
452    components: usize,
453) -> Result<Vec<Source>> {
454    let mut used = vec![false; columns];
455    for (i, &(component, mtyp, pcol)) in entries.iter().enumerate() {
456        if usize::from(component) >= components {
457            return Err(Error::FileFormat(format!(
458                "`cmap` channel {i} maps component {component}, but the codestream has {components}"
459            )));
460        }
461        let column = usize::from(pcol);
462        if mtyp > 1 {
463            return Err(Error::FileFormat(format!(
464                "`cmap` channel {i} has mapping type {mtyp}; only 0 (direct) and 1 (palette) exist"
465            )));
466        }
467        if column >= columns {
468            return Err(Error::FileFormat(format!(
469                "`cmap` channel {i} names palette column {pcol}, but the palette has {columns}"
470            )));
471        }
472        if mtyp == 1 && used[column] {
473            return Err(Error::FileFormat(format!(
474                "`cmap` maps palette column {pcol} twice"
475            )));
476        }
477        if mtyp == 0 && pcol != 0 {
478            return Err(Error::FileFormat(format!(
479                "`cmap` channel {i} uses component {component} directly but names palette \
480                 column {pcol}; a direct channel's `PCOL` must be 0"
481            )));
482        }
483        used[column] = true;
484    }
485    for (i, &(_, mtyp, _)) in entries.iter().enumerate() {
486        if mtyp != 0 && !used[i] {
487            return Err(Error::FileFormat(format!(
488                "`cmap` channel {i} is a palette channel but palette column {i} is not mapped"
489            )));
490        }
491    }
492    for (i, &(_, mtyp, pcol)) in entries.iter().enumerate() {
493        if mtyp == 1 && usize::from(pcol) != i {
494            return Err(Error::Unsupported(format!(
495                "`cmap` channel {i} looks up palette column {pcol}; only channel i from \
496                 column i is decoded"
497            )));
498        }
499    }
500
501    // OpenJPEG's correction for a broken single-component `cmap` ("Component
502    // mapping seems wrong. Trying to correct."): every channel becomes a
503    // lookup in its own column.
504    let correct = components == 1 && used.contains(&false);
505    entries
506        .iter()
507        .enumerate()
508        .map(|(i, &(component, mtyp, pcol))| {
509            Ok(if correct {
510                let column = u8::try_from(i).map_err(|_| {
511                    Error::Inconsistent(format!("palette column {i} exceeds `NPC`"))
512                })?;
513                Source::Palette { component, column }
514            } else if mtyp == 0 {
515                Source::Direct { component }
516            } else {
517                Source::Palette {
518                    component,
519                    column: pcol,
520                }
521            })
522        })
523        .collect()
524}
525
526/// Channel `i`'s sample format. A palette channel takes its column's `Bi`; a
527/// direct channel takes `Bi` of column `i`, as OpenJPEG labels it (`i` is
528/// below `NPC`, since `cmap` holds one entry per column). The sub-sampling is
529/// the source component's.
530fn plan_channel(i: usize, source: Source, palette: &Palette, siz: &Siz) -> Result<PlannedChannel> {
531    let label = match source {
532        Source::Direct { .. } => i,
533        Source::Palette { column, .. } => usize::from(column),
534    };
535    let column = palette
536        .columns
537        .get(label)
538        .ok_or_else(|| Error::Inconsistent(format!("no palette column {label}")))?;
539    if !column.fits_i32() {
540        return Err(Error::Unsupported(format!(
541            "palette channel {i} has depth {} ({}), which exceeds the i32 sample container",
542            column.bit_depth,
543            if column.signed { "signed" } else { "unsigned" }
544        )));
545    }
546    let component = siz
547        .components
548        .get(usize::from(source.component()))
549        .ok_or_else(|| Error::Inconsistent("`cmap` component past `SIZ`".into()))?;
550    Ok(PlannedChannel {
551        source,
552        bit_depth: column.bit_depth,
553        signed: column.signed,
554        x_sampling: component.x_sampling,
555        y_sampling: component.y_sampling,
556    })
557}
558
559/// Hold the expanded channels to `cap` samples, from the SIZ extents at
560/// `reduction`, before any tile is decoded or plane allocated. The limit
561/// bounds the expanded channels alone: the decoded components are held while
562/// the channels are built from them, so the peak is about twice the limit
563/// (see [`crate::samples`]).
564fn check_budget(channels: &[PlannedChannel], siz: &Siz, reduction: u8, cap: u64) -> Result<()> {
565    let mut total: u64 = 0;
566    for channel in channels {
567        let index = usize::from(channel.source.component());
568        let (width, height) = siz
569            .component_extent_at(index, reduction)
570            .ok_or_else(|| Error::Inconsistent(format!("`SIZ` declares no component {index}")))?;
571        total = total.saturating_add(u64::from(width) * u64::from(height));
572    }
573    if total > cap {
574        let what = format!(
575            "palette expansion to {} channels{}",
576            channels.len(),
577            samples::at(reduction)
578        );
579        return Err(samples::over(&what, total, cap));
580    }
581    Ok(())
582}
583
584impl PalettePlan {
585    /// The format of each output channel, from the plan and SIZ alone: the
586    /// palette's channels when it applies, otherwise the codestream's
587    /// components as coded.
588    pub(crate) fn output_channels(&self, siz: &Siz, reduction: u8) -> Vec<ComponentInfo> {
589        match self {
590            PalettePlan::Apply { channels, .. } => channels
591                .iter()
592                .map(|c| {
593                    ComponentInfo::on_grid(
594                        siz,
595                        c.bit_depth,
596                        c.signed,
597                        c.x_sampling,
598                        c.y_sampling,
599                        reduction,
600                    )
601                })
602                .collect(),
603            PalettePlan::None | PalettePlan::Skipped { .. } => {
604                ComponentInfo::of_siz(siz, reduction)
605            }
606        }
607    }
608
609    /// The output channels from the decoded components, in SIZ order. Each
610    /// channel is built on its source component's grid. A direct channel
611    /// takes its component's plane when no later channel reads it.
612    pub(crate) fn apply(&self, mut components: Vec<Component>) -> Result<Vec<Component>> {
613        let PalettePlan::Apply { palette, channels } = self else {
614            return Ok(components);
615        };
616        let mut reads_left = vec![0usize; components.len()];
617        for channel in channels {
618            let index = usize::from(channel.source.component());
619            let slot = reads_left.get_mut(index).ok_or_else(|| {
620                Error::Inconsistent(format!(
621                    "`cmap` names component {index}, which was not decoded"
622                ))
623            })?;
624            *slot += 1;
625        }
626
627        let mut out = Vec::with_capacity(channels.len());
628        for channel in channels {
629            let index = usize::from(channel.source.component());
630            reads_left[index] -= 1;
631            let from = &mut components[index];
632            let samples = match channel.source {
633                Source::Direct { .. } if reads_left[index] == 0 => {
634                    std::mem::take(&mut from.samples)
635                }
636                Source::Direct { .. } => from.samples.clone(),
637                Source::Palette { column, .. } => from
638                    .samples
639                    .iter()
640                    .map(|&k| palette.lookup(k, usize::from(column)))
641                    .collect(),
642            };
643            out.push(Component::new(
644                from.width,
645                from.height,
646                channel.bit_depth,
647                channel.signed,
648                channel.x_sampling,
649                channel.y_sampling,
650                samples,
651            ));
652        }
653        Ok(out)
654    }
655
656    /// Record the plan on the file's metadata: whether the palette was
657    /// applied, and, when the caller skipped it, which raw channels are index
658    /// planes. An index plane is `Unspecified` with no association: it is not
659    /// a color until it goes through the palette.
660    pub(crate) fn describe(&self, metadata: &mut Jp2Metadata) {
661        metadata.palette_applied = matches!(self, PalettePlan::Apply { .. });
662        match self {
663            PalettePlan::None => {}
664            PalettePlan::Apply { palette, channels } => {
665                metadata.palette = Some(palette.clone());
666                metadata.channel_mapping =
667                    Some(channels.iter().map(|c| public_source(c.source)).collect());
668            }
669            PalettePlan::Skipped {
670                palette, mapping, ..
671            } => {
672                metadata.palette = Some(palette.clone());
673                metadata.channel_mapping = Some(mapping.clone());
674            }
675        }
676        if let PalettePlan::Skipped {
677            index_components, ..
678        } = self
679        {
680            for (channel, &index) in metadata.channels.iter_mut().zip(index_components) {
681                if index {
682                    *channel = ChannelDefinition {
683                        kind: ChannelType::Unspecified,
684                        association: Association::None,
685                    };
686                }
687            }
688        }
689    }
690}
691
692#[cfg(test)]
693mod tests {
694    use super::*;
695    use crate::codestream::markers::SizComponent;
696
697    fn pclr(entries: u16, bi: &[u8], table: &[u8]) -> Vec<u8> {
698        let mut out = entries.to_be_bytes().to_vec();
699        out.push(u8::try_from(bi.len()).unwrap());
700        out.extend_from_slice(bi);
701        out.extend_from_slice(table);
702        out
703    }
704
705    #[test]
706    fn entries_are_read_at_their_byte_widths() {
707        // 2 entries, columns of 8, 12 and 1 bits: 1 + 2 + 1 bytes per row.
708        let palette =
709            Palette::parse(&pclr(2, &[7, 11, 0], &[1, 0x0A, 0xBC, 1, 2, 0x0F, 0xFF, 0])).unwrap();
710        assert_eq!(palette.values, [1, 0xABC, 1, 2, 0xFFF, 0]);
711        assert_eq!(
712            palette.columns,
713            [
714                PaletteColumn {
715                    bit_depth: 8,
716                    signed: false
717                },
718                PaletteColumn {
719                    bit_depth: 12,
720                    signed: false
721                },
722                PaletteColumn {
723                    bit_depth: 1,
724                    signed: false
725                },
726            ]
727        );
728    }
729
730    /// OpenJPEG reads a column deeper than 32 bits at a 4-byte stride, so a
731    /// 38-bit column's table is 4 bytes per entry.
732    #[test]
733    fn a_deep_column_is_read_at_a_four_byte_stride() {
734        let palette = Palette::parse(&pclr(2, &[37], &[0, 0, 0, 7, 0xFF, 0xFF, 0xFF, 0xFF]))
735            .expect("4 bytes per entry is enough");
736        assert_eq!(palette.values, [7, -1]);
737        assert!(matches!(
738            Palette::parse(&pclr(2, &[37], &[0; 7])),
739            Err(Error::FileFormat(_))
740        ));
741    }
742
743    /// Measured with `opj_decompress` 2.5.0: a signed 12-bit column holding
744    /// `0xFFF` decodes to 4095, not -1, and a 12-bit entry `0xF000` keeps its
745    /// high bits.
746    #[test]
747    fn entries_are_unsigned_and_unmasked_as_in_openjpeg() {
748        let palette = Palette::parse(&pclr(1, &[0x8B, 11], &[0x0F, 0xFF, 0xF0, 0x00])).unwrap();
749        assert!(palette.columns[0].signed);
750        assert_eq!(palette.values, [4095, 0xF000]);
751    }
752
753    #[test]
754    fn indices_clamp_to_the_palette() {
755        let palette = Palette::parse(&pclr(3, &[7], &[10, 20, 30])).unwrap();
756        let looked: Vec<i32> = [-5, 0, 1, 2, 3, 1000, i32::MIN, i32::MAX]
757            .iter()
758            .map(|&k| palette.lookup(k, 0))
759            .collect();
760        assert_eq!(looked, [10, 10, 20, 30, 30, 30, 10, 30]);
761    }
762
763    fn siz(width: u32, height: u32) -> Siz {
764        Siz {
765            x_size: width,
766            y_size: height,
767            x_offset: 0,
768            y_offset: 0,
769            tile_width: width,
770            tile_height: height,
771            tile_x_offset: 0,
772            tile_y_offset: 0,
773            components: vec![SizComponent {
774                bit_depth: 8,
775                signed: false,
776                x_sampling: 1,
777                y_sampling: 1,
778            }],
779        }
780    }
781
782    /// 255 channels over a 600x500 component is 76.5 M samples, over a
783    /// 2^26 limit: refused from SIZ alone. A reduced decode, or fewer
784    /// channels, fits.
785    #[test]
786    fn the_expansion_is_held_to_the_sample_budget() {
787        let channel = |column| PlannedChannel {
788            source: Source::Palette {
789                component: 0,
790                column,
791            },
792            bit_depth: 8,
793            signed: false,
794            x_sampling: 1,
795            y_sampling: 1,
796        };
797        let channels: Vec<PlannedChannel> = (0..=254).map(channel).collect();
798        let siz = siz(600, 500);
799        assert!(matches!(
800            check_budget(&channels, &siz, 0, 1 << 26),
801            Err(Error::Limit(_))
802        ));
803        assert!(check_budget(&channels, &siz, 1, 1 << 26).is_ok());
804        assert!(check_budget(&channels[..200], &siz, 0, 1 << 26).is_ok());
805    }
806
807    /// A direct channel moves its component's plane when nothing later reads
808    /// it, and copies it otherwise; either way the samples are the component's.
809    #[test]
810    fn a_direct_channel_moves_or_copies_its_plane() {
811        let palette = Palette::parse(&pclr(2, &[7, 7], &[10, 20, 30, 40])).unwrap();
812        let direct = PlannedChannel {
813            source: Source::Direct { component: 0 },
814            bit_depth: 8,
815            signed: false,
816            x_sampling: 1,
817            y_sampling: 1,
818        };
819        let lookup = PlannedChannel {
820            source: Source::Palette {
821                component: 0,
822                column: 1,
823            },
824            ..direct
825        };
826        let index = Component::new(2, 1, 8, false, 1, 1, vec![0, 1]);
827        for channels in [
828            vec![direct, lookup],
829            vec![lookup, direct],
830            vec![direct, direct],
831        ] {
832            let plan = PalettePlan::Apply {
833                palette: palette.clone(),
834                channels: channels.clone(),
835            };
836            let out = plan.apply(vec![index.clone()]).unwrap();
837            for (channel, got) in channels.iter().zip(&out) {
838                let want = match channel.source {
839                    Source::Direct { .. } => vec![0, 1],
840                    Source::Palette { .. } => vec![20, 40],
841                };
842                assert_eq!(got.samples, want, "{channels:?}");
843            }
844        }
845    }
846
847    #[test]
848    fn entries_are_big_endian_and_cast_to_i32() {
849        assert_eq!(entry_value(&[0x01, 0x02, 0x03, 0x04]), 0x0102_0304);
850        assert_eq!(entry_value(&[0xFF, 0xFF, 0xFF, 0xFF]), -1);
851        assert_eq!(entry_value(&[0x0A, 0xBC]), 0xABC);
852    }
853}