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::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 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 #[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::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 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
411fn 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
422fn 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
438fn 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 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
526fn 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
559fn 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 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 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 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 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 #[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 #[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 #[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 #[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}