use crate::bit_writer::BitWriter;
use crate::color_encoding::write_color_encoding_with_icc;
use crate::encode_image::{
EncodeConfig, encode_image, encode_image_10bit, encode_image_12bit, encode_image_16bit,
encode_image_gray, encode_image_gray_10bit, encode_image_gray_12bit, encode_image_gray_16bit,
};
use crate::iso_gain_map::IsoGainMap;
use crate::{ColorEncoding, EncodeError};
use std::fmt;
pub(crate) const JHGM_VERSION: u8 = 0;
#[derive(Clone)]
pub enum GainMapPixels {
Gray8(Vec<u8>),
Rgb8(Vec<u8>),
Gray16 { data: Vec<u16>, bits: u8 },
Rgb16 { data: Vec<u16>, bits: u8 },
}
impl GainMapPixels {
pub fn channels(&self) -> usize {
match self {
Self::Gray8(_) | Self::Gray16 { .. } => 1,
Self::Rgb8(_) | Self::Rgb16 { .. } => 3,
}
}
pub fn bits(&self) -> u8 {
match self {
Self::Gray8(_) | Self::Rgb8(_) => 8,
Self::Gray16 { bits, .. } | Self::Rgb16 { bits, .. } => *bits,
}
}
pub fn len(&self) -> usize {
match self {
Self::Gray8(v) | Self::Rgb8(v) => v.len(),
Self::Gray16 { data, .. } | Self::Rgb16 { data, .. } => data.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl fmt::Debug for GainMapPixels {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let kind = match self {
Self::Gray8(_) => "Gray8",
Self::Rgb8(_) => "Rgb8",
Self::Gray16 { .. } => "Gray16",
Self::Rgb16 { .. } => "Rgb16",
};
write!(
f,
"GainMapPixels::{kind} {{ samples: {}, bits: {} }}",
self.len(),
self.bits()
)
}
}
#[derive(Debug, Clone)]
pub struct GainMap {
pub width: usize,
pub height: usize,
pub pixels: GainMapPixels,
pub metadata: IsoGainMap,
pub color_encoding: ColorEncoding,
pub alternate_color_encoding: Option<ColorEncoding>,
pub alternate_icc_profile: Option<Vec<u8>>,
pub distance: Option<f32>,
pub lossless: bool,
}
impl GainMap {
fn new(pixels: GainMapPixels, width: usize, height: usize, metadata: IsoGainMap) -> Self {
Self {
width,
height,
pixels,
metadata,
color_encoding: ColorEncoding::default(),
alternate_color_encoding: None,
alternate_icc_profile: None,
distance: None,
lossless: false,
}
}
pub fn gray8(pixels: Vec<u8>, width: usize, height: usize, metadata: IsoGainMap) -> Self {
Self::new(GainMapPixels::Gray8(pixels), width, height, metadata)
}
pub fn rgb8(pixels: Vec<u8>, width: usize, height: usize, metadata: IsoGainMap) -> Self {
Self::new(GainMapPixels::Rgb8(pixels), width, height, metadata)
}
pub fn gray16(
pixels: Vec<u16>,
bits: u8,
width: usize,
height: usize,
metadata: IsoGainMap,
) -> Self {
Self::new(
GainMapPixels::Gray16 { data: pixels, bits },
width,
height,
metadata,
)
}
pub fn rgb16(
pixels: Vec<u16>,
bits: u8,
width: usize,
height: usize,
metadata: IsoGainMap,
) -> Self {
Self::new(
GainMapPixels::Rgb16 { data: pixels, bits },
width,
height,
metadata,
)
}
pub fn with_distance(mut self, distance: f32) -> Self {
self.distance = Some(distance);
self
}
pub fn with_lossless(mut self, lossless: bool) -> Self {
self.lossless = lossless;
self
}
pub fn with_color_encoding(mut self, enc: ColorEncoding) -> Self {
self.color_encoding = enc;
self
}
pub fn with_alternate_color_encoding(mut self, enc: ColorEncoding) -> Self {
self.alternate_color_encoding = Some(enc);
self
}
pub fn with_alternate_icc_profile(mut self, icc: Vec<u8>) -> Self {
self.alternate_icc_profile = Some(icc);
self
}
fn validate(&self) -> Result<(), EncodeError> {
if self.width == 0 || self.height == 0 {
return Err(EncodeError::GainMap("gain map dimensions must be non-zero"));
}
let expected = self
.width
.checked_mul(self.height)
.and_then(|n| n.checked_mul(self.pixels.channels()))
.ok_or(EncodeError::SizeOverflow)?;
if self.pixels.len() != expected {
return Err(EncodeError::GainMapSizeMismatch {
expected,
actual: self.pixels.len(),
});
}
if !matches!(self.pixels.bits(), 8 | 10 | 12 | 16) {
return Err(EncodeError::GainMap(
"gain map bit depth must be 8, 10, 12 or 16",
));
}
if let Some(d) = self.distance
&& (!d.is_finite() || d <= 0.0)
{
return Err(EncodeError::InvalidDistance(d));
}
if matches!(self.alternate_icc_profile.as_deref(), Some(&[])) {
return Err(EncodeError::GainMap("alternate ICC profile is empty"));
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub(crate) struct EncodedGainMap {
pub(crate) bundle: Vec<u8>,
pub(crate) needs_level_10: bool,
}
pub(crate) fn encode_gain_map(base: &EncodeConfig) -> Result<Option<EncodedGainMap>, EncodeError> {
let Some(gm) = base.gain_map.as_ref() else {
return Ok(None);
};
gm.validate()?;
let distance = gm
.distance
.unwrap_or(if base.lossless { 1.0 } else { base.distance });
let cfg = EncodeConfig {
distance,
color_encoding: gm.color_encoding,
icc_profile: None,
exif: None,
xmp: None,
brotli_compression: None,
orientation: base.orientation,
lossless: gm.lossless,
fill_invisible: base.fill_invisible,
progressive: false,
patches: base.patches,
#[cfg(feature = "splines")]
splines: false,
#[cfg(feature = "splines")]
dots: false,
progressive_passes: None,
progressive_shifts: None,
intensity_target: None,
min_nits: 0.0,
relative_to_max_display: false,
linear_below: 0.0,
num_threads: base.num_threads,
speed: base.speed,
arbiter: base.arbiter,
decoding_speed: base.decoding_speed,
lossy_modular: base.lossy_modular,
learned_rate: base.learned_rate,
gain_map: None,
coding_transform: crate::CodingTransform::Xyb,
};
let (w, h) = (gm.width, gm.height);
let encoded = match &gm.pixels {
GainMapPixels::Gray8(p) => encode_image_gray(p, w, h, &cfg)?,
GainMapPixels::Rgb8(p) => encode_image(p, w, h, &cfg)?,
GainMapPixels::Gray16 { data, bits } => match bits {
10 => encode_image_gray_10bit(data, w, h, &cfg)?,
12 => encode_image_gray_12bit(data, w, h, &cfg)?,
_ => encode_image_gray_16bit(data, w, h, &cfg)?,
},
GainMapPixels::Rgb16 { data, bits } => match bits {
10 => encode_image_10bit(data, w, h, &cfg)?,
12 => encode_image_12bit(data, w, h, &cfg)?,
_ => encode_image_16bit(data, w, h, &cfg)?,
},
};
let (codestream, needs_level_10) = strip_container(encoded)?;
let metadata = gm.metadata.to_metadata()?;
let bundle = write_jhgm_bundle(
&metadata,
gm.alternate_color_encoding.as_ref(),
gm.alternate_icc_profile.as_deref(),
&codestream,
)?;
Ok(Some(EncodedGainMap {
bundle,
needs_level_10,
}))
}
static CONTAINER_SIGNATURE: [u8; 12] = [
0, 0, 0, 0x0C, b'J', b'X', b'L', b' ', 0x0D, 0x0A, 0x87, 0x0A,
];
fn strip_container(bytes: Vec<u8>) -> Result<(Vec<u8>, bool), EncodeError> {
if !bytes.starts_with(&CONTAINER_SIGNATURE) {
return Ok((bytes, false));
}
let mut level_10 = false;
let mut codestream = None;
let mut pos = 0usize;
while pos + 8 <= bytes.len() {
let small = u32::from_be_bytes(bytes[pos..pos + 4].try_into().unwrap()) as usize;
let kind: &[u8; 4] = bytes[pos + 4..pos + 8].try_into().unwrap();
let (header, size) = if small == 1 {
if pos + 16 > bytes.len() {
break;
}
let large = u64::from_be_bytes(bytes[pos + 8..pos + 16].try_into().unwrap());
(
16usize,
usize::try_from(large).map_err(|_| EncodeError::SizeOverflow)?,
)
} else if small == 0 {
(8usize, bytes.len() - pos) } else {
(8usize, small)
};
if size < header || pos + size > bytes.len() {
break;
}
let payload = &bytes[pos + header..pos + size];
match kind {
b"jxll" => level_10 = payload.first().copied() == Some(10),
b"jxlc" => codestream = Some(payload.to_vec()),
_ => {}
}
pos += size;
}
match codestream {
Some(c) => Ok((c, level_10)),
None => Err(EncodeError::GainMap(
"internal: gain map container without a jxlc box",
)),
}
}
fn color_encoding_bytes(enc: &ColorEncoding) -> Vec<u8> {
let mut w = BitWriter::new();
write_color_encoding_with_icc(enc, false, false, &mut w);
w.zero_pad_to_byte();
w.into_bytes()
}
pub(crate) fn compress_icc(icc: &[u8]) -> Vec<u8> {
let mut pool = Vec::with_capacity(1024);
let mut w = BitWriter::new();
crate::icc_codec::write_icc_stream(icc, &mut pool, &mut w);
w.zero_pad_to_byte();
w.into_bytes()
}
pub(crate) fn write_jhgm_bundle(
metadata: &[u8],
color_encoding: Option<&ColorEncoding>,
alt_icc: Option<&[u8]>,
codestream: &[u8],
) -> Result<Vec<u8>, EncodeError> {
let metadata_size = u16::try_from(metadata.len())
.map_err(|_| EncodeError::GainMap("gain map metadata exceeds 65535 bytes"))?;
let enc_bytes = color_encoding.map(color_encoding_bytes).unwrap_or_default();
let enc_size = u8::try_from(enc_bytes.len())
.map_err(|_| EncodeError::GainMap("gain map color encoding exceeds 255 bytes"))?;
let icc_bytes = alt_icc.map(compress_icc).unwrap_or_default();
let icc_size = u32::try_from(icc_bytes.len())
.map_err(|_| EncodeError::GainMap("compressed alternate ICC exceeds 4 GiB"))?;
let mut out = Vec::with_capacity(
1 + 2 + metadata.len() + 1 + enc_bytes.len() + 4 + icc_bytes.len() + codestream.len(),
);
out.push(JHGM_VERSION);
out.extend_from_slice(&metadata_size.to_be_bytes());
out.extend_from_slice(metadata);
out.push(enc_size);
out.extend_from_slice(&enc_bytes);
out.extend_from_slice(&icc_size.to_be_bytes());
out.extend_from_slice(&icc_bytes);
out.extend_from_slice(codestream);
Ok(out)
}
#[cfg(test)]
pub(crate) struct ParsedBundle<'a> {
pub version: u8,
pub metadata: &'a [u8],
pub color_encoding: &'a [u8],
pub alt_icc: &'a [u8],
pub codestream: &'a [u8],
}
#[cfg(test)]
pub(crate) fn parse_jhgm_bundle(b: &[u8]) -> Option<ParsedBundle<'_>> {
let mut pos = 0usize;
let version = *b.get(pos)?;
pos += 1;
let md_size = u16::from_be_bytes(b.get(pos..pos + 2)?.try_into().ok()?) as usize;
pos += 2;
let metadata = b.get(pos..pos + md_size)?;
pos += md_size;
let ce_size = *b.get(pos)? as usize;
pos += 1;
let color_encoding = b.get(pos..pos + ce_size)?;
pos += ce_size;
let icc_size = u32::from_be_bytes(b.get(pos..pos + 4)?.try_into().ok()?) as usize;
pos += 4;
let alt_icc = b.get(pos..pos + icc_size)?;
pos += icc_size;
let codestream = b.get(pos..)?;
Some(ParsedBundle {
version,
metadata,
color_encoding,
alt_icc,
codestream,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::GainMapFloats;
fn metadata() -> IsoGainMap {
IsoGainMap::from_floats(&GainMapFloats {
max: [2.0; 3],
alternate_hdr_headroom: 2.0,
..GainMapFloats::default()
})
.unwrap()
}
fn fake_icc() -> Vec<u8> {
let mut icc = vec![0u8; 132];
icc[0..4].copy_from_slice(&(132u32).to_be_bytes());
icc[4..8].copy_from_slice(b"jixl");
icc[12..16].copy_from_slice(b"mntr");
icc[16..20].copy_from_slice(b"RGB ");
icc[20..24].copy_from_slice(b"XYZ ");
icc[36..40].copy_from_slice(b"acsp");
icc
}
#[test]
fn bundle_layout_matches_libjxl() {
let md = metadata().to_metadata().unwrap();
let enc = ColorEncoding::bt2020_pq();
let icc = fake_icc();
let codestream = vec![0xFF, 0x0A, 1, 2, 3, 4, 5];
let bundle = write_jhgm_bundle(&md, Some(&enc), Some(&icc), &codestream).unwrap();
let p = parse_jhgm_bundle(&bundle).unwrap();
assert_eq!(p.version, JHGM_VERSION);
assert_eq!(p.metadata, md.as_slice());
assert_eq!(p.color_encoding, color_encoding_bytes(&enc).as_slice());
assert!(!p.color_encoding.is_empty() && p.color_encoding.len() < 8);
assert_eq!(p.alt_icc, compress_icc(&icc).as_slice());
assert!(!p.alt_icc.is_empty());
assert_eq!(p.codestream, codestream.as_slice());
assert_eq!(
bundle.len(),
8 + md.len() + p.color_encoding.len() + p.alt_icc.len() + codestream.len()
);
}
#[test]
fn absent_optional_parts_are_zero_sized() {
let md = metadata().to_metadata().unwrap();
let bundle = write_jhgm_bundle(&md, None, None, &[0xFF, 0x0A]).unwrap();
let p = parse_jhgm_bundle(&bundle).unwrap();
assert!(p.color_encoding.is_empty());
assert!(p.alt_icc.is_empty());
assert_eq!(p.codestream, &[0xFF, 0x0A]);
assert_eq!(bundle[1 + 2 + md.len()], 0); assert_eq!(&bundle[1 + 2 + md.len() + 1..][..4], &[0, 0, 0, 0]); }
#[test]
fn strip_container_handles_bare_and_wrapped_streams() {
let bare = vec![0xFF, 0x0A, 9, 9];
assert_eq!(
strip_container(bare.clone()).unwrap(),
(bare.clone(), false)
);
let wrapped =
crate::encode_image::wrap_jxl_container(bare.clone(), 10, None, None, None, None)
.unwrap();
assert_eq!(strip_container(wrapped).unwrap(), (bare.clone(), true));
let wrapped5 =
crate::encode_image::wrap_jxl_container(bare.clone(), 5, None, None, None, None)
.unwrap();
assert_eq!(strip_container(wrapped5).unwrap(), (bare, false));
}
#[test]
fn validation_catches_bad_gain_maps() {
let m = metadata();
assert!(matches!(
GainMap::gray8(vec![0; 3], 2, 2, m).validate(),
Err(EncodeError::GainMapSizeMismatch {
expected: 4,
actual: 3
})
));
assert!(GainMap::rgb8(vec![0; 12], 2, 2, m).validate().is_ok());
assert!(GainMap::gray16(vec![0; 4], 9, 2, 2, m).validate().is_err());
assert!(GainMap::gray8(vec![], 0, 2, m).validate().is_err());
assert!(
GainMap::gray8(vec![0; 4], 2, 2, m)
.with_distance(0.0)
.validate()
.is_err()
);
assert!(
GainMap::gray8(vec![0; 4], 2, 2, m)
.with_alternate_icc_profile(vec![])
.validate()
.is_err()
);
}
}