| 1 | //! Colour to sRGB (ICC and CICP through moxcms), HDR tone-mapping and EXIF orientation. |
| 2 | |
| 3 | use image::DynamicImage; |
| 4 | use image::metadata::Orientation; |
| 5 | use moxcms::{ |
| 6 | CicpColorPrimaries, CicpProfile, ColorProfile, DataColorSpace, Layout, MatrixCoefficients, |
| 7 | TransferCharacteristics, TransformOptions, |
| 8 | }; |
| 9 | |
| 10 | /// An sRGB-bound transform for RGBA8 pixels, or `None` when the source already is sRGB (or |
| 11 | /// the profile can't be used, in which case the pixels are shown as they are). |
| 12 | pub struct ToSrgb(std::sync::Arc<moxcms::Transform8BitExecutor>); |
| 13 | |
| 14 | impl ToSrgb { |
| 15 | pub fn from_icc(icc: &[u8]) -> Option<Self> { |
| 16 | let src = match ColorProfile::new_from_slice(icc) { |
| 17 | Ok(p) => p, |
| 18 | Err(e) => { |
| 19 | log::debug!("ICC profile ignored: {e:?}"); |
| 20 | return None; |
| 21 | } |
| 22 | }; |
| 23 | if src.color_space != DataColorSpace::Rgb { |
| 24 | return None; |
| 25 | } |
| 26 | Self::from_profile(&src) |
| 27 | } |
| 28 | |
| 29 | /// From H.273 code points (AVIF/HEIF `nclx`). sRGB/BT.709 and unspecified need nothing. |
| 30 | pub fn from_cicp(primaries: u8, transfer: u8) -> Option<Self> { |
| 31 | let primaries = CicpColorPrimaries::try_from(primaries).ok()?; |
| 32 | if matches!( |
| 33 | primaries, |
| 34 | CicpColorPrimaries::Bt709 | CicpColorPrimaries::Unspecified |
| 35 | ) { |
| 36 | return None; |
| 37 | } |
| 38 | let transfer = TransferCharacteristics::try_from(transfer) |
| 39 | .ok() |
| 40 | .filter(|t| !matches!(t, TransferCharacteristics::Unspecified)) |
| 41 | .unwrap_or(TransferCharacteristics::Srgb); |
| 42 | let profile = ColorProfile::new_from_cicp(CicpProfile { |
| 43 | color_primaries: primaries, |
| 44 | transfer_characteristics: transfer, |
| 45 | matrix_coefficients: MatrixCoefficients::Identity, |
| 46 | full_range: true, |
| 47 | }); |
| 48 | Self::from_profile(&profile) |
| 49 | } |
| 50 | |
| 51 | fn from_profile(src: &ColorProfile) -> Option<Self> { |
| 52 | let dst = ColorProfile::new_srgb(); |
| 53 | match src.create_transform_8bit( |
| 54 | Layout::Rgba, |
| 55 | &dst, |
| 56 | Layout::Rgba, |
| 57 | TransformOptions::default(), |
| 58 | ) { |
| 59 | Ok(t) => Some(Self(t)), |
| 60 | Err(e) => { |
| 61 | log::debug!("colour transform unavailable: {e:?}"); |
| 62 | None |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | /// Convert RGBA8 pixels in place; alpha is untouched. |
| 68 | pub fn apply(&self, pixels: &mut [u8]) { |
| 69 | let src = pixels.to_vec(); |
| 70 | if let Err(e) = self.0.transform(&src, pixels) { |
| 71 | log::debug!("colour transform failed: {e:?}"); |
| 72 | pixels.copy_from_slice(&src); |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | fn srgb_encode(v: f32) -> f32 { |
| 78 | if v <= 0.003_130_8 { |
| 79 | v * 12.92 |
| 80 | } else { |
| 81 | 1.055 * v.powf(1.0 / 2.4) - 0.055 |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | /// Narkowicz's ACES fit: filmic highlights, unchanged blacks. |
| 86 | fn aces(x: f32) -> f32 { |
| 87 | ((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14)).clamp(0.0, 1.0) |
| 88 | } |
| 89 | |
| 90 | /// Linear float RGBA (EXR, Radiance HDR, float TIFF) to sRGB RGBA8. Images whose values stay |
| 91 | /// within 0..1 are only encoded; brighter ones are tone-mapped. |
| 92 | pub fn tonemap(rgba: &[f32]) -> Vec<u8> { |
| 93 | let peak = rgba |
| 94 | .chunks_exact(4) |
| 95 | .flat_map(|p| &p[..3]) |
| 96 | .copied() |
| 97 | .filter(|v| v.is_finite()) |
| 98 | .fold(0.0f32, f32::max); |
| 99 | let hdr = peak > 1.0; |
| 100 | let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; |
| 101 | let mut out = Vec::with_capacity(rgba.len()); |
| 102 | for p in rgba.chunks_exact(4) { |
| 103 | for &c in &p[..3] { |
| 104 | let c = if c.is_finite() { c.max(0.0) } else { 0.0 }; |
| 105 | let c = if hdr { aces(c) } else { c }; |
| 106 | out.push(to8(srgb_encode(c))); |
| 107 | } |
| 108 | out.push(to8(if p[3].is_finite() { p[3] } else { 1.0 })); |
| 109 | } |
| 110 | out |
| 111 | } |
| 112 | |
| 113 | /// Whether the image holds float samples that need tone-mapping rather than a plain cast. |
| 114 | pub fn is_float(img: &DynamicImage) -> bool { |
| 115 | matches!( |
| 116 | img, |
| 117 | DynamicImage::ImageRgb32F(_) | DynamicImage::ImageRgba32F(_) |
| 118 | ) |
| 119 | } |
| 120 | |
| 121 | /// Straight RGBA8 from any decoded image, tone-mapping float data. |
| 122 | pub fn to_rgba8(img: DynamicImage) -> ([u32; 2], Vec<u8>) { |
| 123 | let size = [img.width(), img.height()]; |
| 124 | if is_float(&img) { |
| 125 | let f = img.into_rgba32f(); |
| 126 | (size, tonemap(f.as_raw())) |
| 127 | } else { |
| 128 | (size, img.into_rgba8().into_raw()) |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | /// Rotate/flip RGBA8 pixels upright. |
| 133 | pub fn orient(size: [u32; 2], pixels: Vec<u8>, o: Orientation) -> ([u32; 2], Vec<u8>) { |
| 134 | if o == Orientation::NoTransforms { |
| 135 | return (size, pixels); |
| 136 | } |
| 137 | let Some(buf) = image::RgbaImage::from_raw(size[0], size[1], pixels) else { |
| 138 | return (size, Vec::new()); |
| 139 | }; |
| 140 | let mut img = DynamicImage::ImageRgba8(buf); |
| 141 | img.apply_orientation(o); |
| 142 | let out = img.into_rgba8(); |
| 143 | ([out.width(), out.height()], out.into_raw()) |
| 144 | } |
| 145 | |
| 146 | /// RGBA8 from interleaved 8-bit samples with 1–4 channels (grey, grey+alpha, RGB, RGBA). |
| 147 | pub fn expand(samples: &[u8], channels: usize) -> Vec<u8> { |
| 148 | match channels { |
| 149 | 4 => samples.to_vec(), |
| 150 | 3 => samples |
| 151 | .chunks_exact(3) |
| 152 | .flat_map(|p| [p[0], p[1], p[2], 255]) |
| 153 | .collect(), |
| 154 | 2 => samples |
| 155 | .chunks_exact(2) |
| 156 | .flat_map(|p| [p[0], p[0], p[0], p[1]]) |
| 157 | .collect(), |
| 158 | _ => samples.iter().flat_map(|&g| [g, g, g, 255]).collect(), |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | #[cfg(test)] |
| 163 | mod tests { |
| 164 | use super::*; |
| 165 | |
| 166 | #[test] |
| 167 | fn tonemapping() { |
| 168 | // In-range linear data is only sRGB-encoded. |
| 169 | let px = tonemap(&[0.0, 0.2158, 1.0, 0.5]); |
| 170 | assert_eq!(px, [0, 128, 255, 128]); |
| 171 | // HDR highlights roll off instead of clipping, and stay ordered. |
| 172 | let px = tonemap(&[1.0, 4.0, 40.0, 1.0, f32::NAN, -1.0, 0.0, f32::INFINITY]); |
| 173 | assert!(px[0] < px[1] && px[1] <= px[2] && px[2] == 255, "{px:?}"); |
| 174 | assert_eq!(&px[4..8], [0, 0, 0, 255]); |
| 175 | } |
| 176 | |
| 177 | #[test] |
| 178 | fn orientation_turns_pixels() { |
| 179 | // 2×1: red, green. Rotate 90° clockwise → 1×2: red on top. |
| 180 | let px = vec![255, 0, 0, 255, 0, 255, 0, 255]; |
| 181 | let (size, out) = orient([2, 1], px, Orientation::Rotate90); |
| 182 | assert_eq!(size, [1, 2]); |
| 183 | assert_eq!(&out[..4], [255, 0, 0, 255]); |
| 184 | let (size, out) = orient([2, 1], out.clone(), Orientation::NoTransforms); |
| 185 | assert_eq!((size, out.len()), ([2, 1], 8)); |
| 186 | } |
| 187 | |
| 188 | #[test] |
| 189 | fn cicp_and_icc() { |
| 190 | assert!(ToSrgb::from_cicp(1, 13).is_none(), "BT.709 is already sRGB"); |
| 191 | // Display P3 primaries with the sRGB curve: pure P3 red is outside sRGB. |
| 192 | let t = ToSrgb::from_cicp(12, 13).expect("P3 transform"); |
| 193 | let mut px = [255, 0, 0, 200]; |
| 194 | t.apply(&mut px); |
| 195 | assert_eq!(px[0], 255); |
| 196 | assert!(px[3] == 200); |
| 197 | assert!(ToSrgb::from_icc(b"not a profile").is_none()); |
| 198 | assert_eq!(expand(&[7, 9], 2), [7, 7, 7, 9]); |
| 199 | } |
| 200 | } |