Skip to main content

ColorOutput

Enum ColorOutput 

Source
#[non_exhaustive]
pub enum ColorOutput { AsCoded, Srgb, }
Expand description

What color space a JP2 file’s color channels come out in: the DecodeOptions::color option.

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

AsCoded

The samples as the codestream coded them, after the palette and the channel definitions. Jp2Metadata::color says how to read them; an ICC profile is passed through, not applied.

§

Srgb

sRGB. A restricted ICC profile (a monochrome or a three-component matrix/TRC input profile) is applied at its rendering intent, as OpenJPEG applies it with LittleCMS. sYCC is converted to RGB, with sub-sampled chroma (2x1 or 2x2) replicated to full resolution first. The color channels are the ones the cdef box labels color 1, 2 and 3, wherever they sit. Other channels (opacity, say) are untouched. No conversion changes a channel’s bit depth: a 12-bit file comes out as 12-bit sRGB, and a caller who wants 8-bit samples scales them (see the example below).

These pass through as coded, with the metadata as declared, except a three-channel 4:2:0 or 4:2:2 image (below):

  • sRGB and grayscale;
  • one or two channels, whatever the color space, as OpenJPEG reads them as gray, or gray and opacity; only a monochrome profile converts them;
  • an ICC profile that LittleCMS refuses to open or to build a transform from, or whose color space is not RGB, gray or YCbCr, as OpenJPEG leaves it. Jp2Metadata::color stays ColorSpace::RestrictedIcc, so a caller can tell nothing was converted;
  • an RGB profile when any of the first four channels differs from the first in depth, sign or sub-sampling (OpenJPEG’s “AFL test”).

Anything else that cannot be converted is Error::Unsupported:

  • three or more channels with no color space (a raw codestream included) or another enumerated color space;
  • a three-channel 4:2:0 or 4:2:2 image (luma at 1x1, both chroma channels at 2x2 or both at 2x1) that is not declared sYCC, which OpenJPEG converts as sYCC whatever the file declares;
  • color channels that are missing, or that differ in depth, sign or sub-sampling outside the cases above;
  • signed sYCC, sYCC in another layout, and samples a profile is not applied at (8- or 16-bit unsigned for RGB, 8-bit unsigned for gray);
  • a YCbCr profile, a profile LittleCMS would apply through a lookup table or the Lab connection space, and a monochrome profile on more than two channels.

Replicated chroma, or a tinted gray channel, past the sample limit is Error::Limit. These errors apply only when Srgb is asked for: ColorOutput::AsCoded decodes the same files. The table of outcomes lists every case against what OpenJPEG does, and the profiles LittleCMS refuses.

When the samples are converted, Jp2Metadata::color says what they now are: ColorSpace::Srgb, or ColorSpace::Grayscale for a monochrome profile, with no ICC profile. A monochrome profile whose output is not neutral (absolute colorimetric with a tinted white point) gives three sRGB channels in place of the gray one, as OpenJPEG does. read_header doesn’t predict that; read_header_with with the same options does.

An ICC conversion matches opj_decompress -force-rgb (OpenJPEG 2.5.0 with LittleCMS 2.14 on x86-64 Linux, glibc 2.39) sample for sample. The output is the same on every platform whose fma is correctly rounded; CI checks this on x86-64 Linux, macOS on aarch64 and wasm32-wasip1. MinGW’s fma (*-pc-windows-gnu) may not be correctly rounded (rust-lang/rust#140515), and i586 targets use x87 arithmetic, which is not exact IEEE, so the output there can differ. The sYCC conversion uses the IEC 61966-2-1 constants and rounds, and is within an MSE of 0.03 of the ISO references. OpenJPEG shortens the constants and truncates, so the two differ by an MSE of about 0.38 to 0.49 a channel.

§Example: an 8-bit RGBA buffer

Samples are i32 at each channel’s own depth and sign, so a caller that wants 8-bit RGBA does three things. It scales each sample to 8 bits, adding half the range first when the channel is signed. It finds the opacity channel by its ChannelType on Jp2Metadata::channels, not by position. And it repeats a gray (one color channel) image’s value for red, green and blue. This handles those three for a JP2 file whose channels share one grid; an image without opacity gets 255, and so does one whose opacity is ChannelType::PremultipliedOpacity, which this recipe does not handle.

use rust_j2k::{ChannelType, ColorOutput, DecodeOptions, Image, decode_with};

/// One sample at its channel's depth and sign, as 8 bits.
fn to_u8(sample: i32, bit_depth: u8, signed: bool) -> u8 {
    let max = (1i64 << bit_depth) - 1;
    let offset = if signed { 1i64 << (bit_depth - 1) } else { 0 };
    let unsigned = (i64::from(sample) + offset).clamp(0, max);
    ((unsigned * 255 + max / 2) / max) as u8
}

/// Interleaved RGBA, or `None` when the channels do not fit that shape
/// (two colors, or channels on different grids).
fn rgba8(image: &Image) -> Option<Vec<u8>> {
    let first = image.components.first()?;
    let same_grid = image
        .components
        .iter()
        .all(|c| (c.width, c.height) == (first.width, first.height));
    // A raw codestream has no labels: take every channel as a color.
    let kinds: Vec<ChannelType> = match &image.jp2 {
        Some(jp2) => jp2.channels.iter().map(|c| c.kind).collect(),
        None => vec![ChannelType::Color; image.components.len()],
    };
    let colors: Vec<usize> = (0..kinds.len())
        .filter(|&i| kinds[i] == ChannelType::Color)
        .collect();
    let alpha = kinds.iter().position(|&k| k == ChannelType::Opacity);
    let (r, g, b) = match colors.as_slice() {
        [gray] => (*gray, *gray, *gray),
        [r, g, b, ..] => (*r, *g, *b),
        _ => return None,
    };
    if !same_grid {
        return None;
    }
    let mut out = Vec::with_capacity(first.samples.len() * 4);
    for i in 0..first.samples.len() {
        for channel in [Some(r), Some(g), Some(b), alpha] {
            out.push(match channel {
                Some(c) => {
                    let c = &image.components[c];
                    to_u8(c.samples[i], c.bit_depth, c.signed)
                }
                None => 255,
            });
        }
    }
    Some(out)
}

let bytes = std::fs::read("image.jp2")?;
// For a 16x12 RGBA file.
let options = DecodeOptions::default().with_color(ColorOutput::Srgb);
let image = decode_with(&bytes, &options).expect("a 16x12 RGBA file");
let rgba = rgba8(&image).expect("red, green, blue and opacity");
assert_eq!(rgba.len(), 16 * 12 * 4);

// A gray image repeats its value, and has no opacity channel.
use rust_j2k::Component;
let gray = Image::new(2, 1, vec![Component::new(2, 1, 12, false, 1, 1, vec![0, 4095])]);
assert_eq!(rgba8(&gray), Some(vec![0, 0, 0, 255, 255, 255, 255, 255]));

Trait Implementations§

Source§

impl Clone for ColorOutput

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ColorOutput

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ColorOutput

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Eq for ColorOutput

Source§

impl PartialEq for ColorOutput

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for ColorOutput

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.