1use 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
55const MAX_ENTRIES: u16 = 1024;
57
58#[derive(Debug, Clone, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct PaletteColumn {
62 pub bit_depth: u8,
64 pub signed: bool,
66}
67
68impl PaletteColumn {
69 fn entry_bytes(&self) -> usize {
74 usize::from(self.bit_depth).div_ceil(8).min(4)
75 }
76
77 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#[derive(Debug, Clone, PartialEq, Eq)]
102#[non_exhaustive]
103pub struct Palette {
104 entries: u16,
106 columns: Vec<PaletteColumn>,
108 values: Vec<i32>,
111}
112
113impl Palette {
114 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 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 #[must_use]
180 pub fn columns(&self) -> &[PaletteColumn] {
181 &self.columns
182 }
183
184 #[must_use]
186 pub fn entry_count(&self) -> usize {
187 usize::from(self.entries)
188 }
189
190 #[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 self.values.get(index * width..(index + 1) * width)
199 }
200
201 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
209fn 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#[derive(Debug, Clone, PartialEq, Eq)]
228#[non_exhaustive]
229pub struct ChannelMapping {
230 pub component: u16,
232 pub kind: MappingKind,
234}
235
236#[derive(Debug, Clone, PartialEq, Eq)]
238#[non_exhaustive]
239pub enum MappingKind {
240 Direct,
242 Palette {
245 column: u8,
247 },
248 Reserved {
252 mtyp: u8,
254 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
272fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub(crate) enum Source {
290 Direct { component: u16 },
292 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#[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#[derive(Debug, Clone, PartialEq, Eq)]
320pub(crate) enum PalettePlan {
321 None,
325 Skipped {
330 index_components: Vec<bool>,
331 palette: Palette,
332 mapping: Vec<ChannelMapping>,
333 },
334 Apply {
336 palette: Palette,
337 channels: Vec<PlannedChannel>,
338 },
339}
340
341pub(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 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
407fn 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
418fn 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
434fn 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 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
522fn 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
555fn 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 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 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 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 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 #[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 #[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 #[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 #[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}