Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

fix(codecs): keep EXR color channels within one layer (#5866)

Jason Xiang37beb1845425
diff --git a/crates/codecs/src/codecs/exr.rs b/crates/codecs/src/codecs/exr.rs
index a55810b4b..1b268ac55 100644
--- a/crates/codecs/src/codecs/exr.rs
+++ b/crates/codecs/src/codecs/exr.rs
@@ -15,7 +15,7 @@ use half::f16;
use crate::Format;
use crate::error::CodecError;
use crate::fidelity::Plan;
-use crate::image::{ChannelLayout, DecodeWarning, ExrChannelInfo, ExrPartInfo, Image, SampleType, base_channel_name};
+use crate::image::{ChannelLayout, DecodeWarning, ExrChannelInfo, ExrPartInfo, Image, SampleType, base_channel_name, exr_color_channels};
use crate::options::{EncodeOptions, ExrCompression, Limits};
const F: Format = Format::OpenExr;
@@ -123,20 +123,9 @@ pub(super) fn read_layer(bytes: &[u8], index: usize) -> Result<Layer<AnyChannels
fn layer_to_image(layer: &Layer<AnyChannels<FlatSamples>>) -> Result<Image, CodecError> {
let (w, h) = (layer.size.0, layer.size.1);
let channels = &layer.channel_data.list;
- let find = |n: &str| channels.iter().find(|c| base_channel_name(&c.name.to_string()) == n);
- let (color, layout): (Vec<_>, ChannelLayout) = if let (Some(r), Some(g), Some(b)) = (find("R"), find("G"), find("B")) {
- match find("A") {
- Some(a) => (vec![r, g, b, a], ChannelLayout::Rgba),
- None => (vec![r, g, b], ChannelLayout::Rgb),
- }
- } else if let Some(y) = find("Y").or_else(|| (channels.len() == 1).then(|| &channels[0])) {
- match find("A") {
- Some(a) => (vec![y, a], ChannelLayout::GrayA),
- None => (vec![y], ChannelLayout::Gray),
- }
- } else {
- return Err(CodecError::unsupported(F, "no R/G/B or Y channels"));
- };
+ let names: Vec<_> = channels.iter().map(|c| c.name.to_string()).collect();
+ let (layout, selected) = exr_color_channels(names.iter().map(String::as_str)).ok_or_else(|| CodecError::unsupported(F, "no R/G/B or Y channels"))?;
+ let color: Vec<_> = selected.iter().map(|i| channels.get(*i).ok_or_else(|| err("selected channel is missing"))).collect::<Result<_, _>>()?;
let all_f16 = color.iter().all(|c| matches!(c.sample_data, FlatSamples::F16(_)));
let sample = if all_f16 { SampleType::F16 } else { SampleType::F32 };
let npx = w * h;
diff --git a/crates/codecs/src/image.rs b/crates/codecs/src/image.rs
index 98168d59d..5a03e7d28 100644
--- a/crates/codecs/src/image.rs
+++ b/crates/codecs/src/image.rs
@@ -321,18 +321,73 @@ pub struct ExrPartInfo {
impl ExrPartInfo {
/// How much this part looks like a colour image the plain [`Image`] decode can show:
- /// 4 RGBA, 3 RGB, 2 YA, 1 any-single-channel, 0 anything else (e.g. `Z` beside `A`).
+ /// 4 RGBA, 3 RGB, 2 YA, 1 Y or any-single-channel, 0 anything else (e.g. `Z` beside `A`).
+ /// The colour and alpha channels must share a complete layer prefix. The highest-ranked
+ /// group wins; equal groups prefer unprefixed channels, then the first prefix alphabetically.
/// The auto-pick takes the highest rank; ties go to the earlier part.
pub fn color_rank(&self) -> u8 {
- let has = |n: &str| self.channels.iter().any(|c| base_channel_name(&c.name) == n);
- if has("R") && has("G") && has("B") {
- return if has("A") { 4 } else { 3 };
+ exr_color_channels(self.channels.iter().map(|c| c.name.as_str())).map_or(0, |(layout, _)| layout.channels() as u8)
+ }
+}
+
+/// One selection policy for header ranking/probing and flat decoding: never synthesize
+/// RGB(A) or YA from separate layers. OpenEXR layers use the full prefix before the last
+/// dot, including nested layers; a leading or trailing dot alone does not name a layer.
+pub(crate) fn exr_color_channels<'a>(names: impl IntoIterator<Item = &'a str>) -> Option<(ChannelLayout, Vec<usize>)> {
+ #[derive(Default)]
+ struct Group {
+ r: Option<usize>,
+ g: Option<usize>,
+ b: Option<usize>,
+ a: Option<usize>,
+ y: Option<usize>,
+ }
+
+ // Sorted prefixes make rank ties deterministic independently of channel order, with
+ // the empty (unprefixed) group first. Unsupported channels cannot complete a group.
+ let mut groups = std::collections::BTreeMap::<&str, Group>::new();
+ let mut count = 0usize;
+ for (index, name) in names.into_iter().enumerate() {
+ count = count.saturating_add(1);
+ let (prefix, base) = name.rsplit_once('.').filter(|(prefix, base)| !prefix.is_empty() && !base.is_empty()).unwrap_or(("", name));
+ if !matches!(base, "R" | "G" | "B" | "A" | "Y") {
+ continue;
}
- if has("Y") {
- return if has("A") { 2 } else { 1 };
+ let group = groups.entry(prefix).or_default();
+ let component = match base {
+ "R" => &mut group.r,
+ "G" => &mut group.g,
+ "B" => &mut group.b,
+ "A" => &mut group.a,
+ "Y" => &mut group.y,
+ _ => continue,
+ };
+ component.get_or_insert(index);
+ }
+
+ let mut best = None;
+ let mut best_rank = 0;
+ for group in groups.values() {
+ let candidate = if let (Some(r), Some(g), Some(b)) = (group.r, group.g, group.b) {
+ match group.a {
+ Some(a) => (ChannelLayout::Rgba, vec![r, g, b, a]),
+ None => (ChannelLayout::Rgb, vec![r, g, b]),
+ }
+ } else if let Some(y) = group.y {
+ match group.a {
+ Some(a) => (ChannelLayout::GrayA, vec![y, a]),
+ None => (ChannelLayout::Gray, vec![y]),
+ }
+ } else {
+ continue;
+ };
+ let rank = candidate.0.channels();
+ if rank > best_rank {
+ best = Some(candidate);
+ best_rank = rank;
}
- u8::from(self.channels.len() == 1)
}
+ best.or_else(|| (count == 1).then(|| (ChannelLayout::Gray, vec![0])))
}
/// Strip an optional `layer.` prefix from a channel name (`diffuse.R` → `R`).
diff --git a/crates/codecs/tests/exr_multipart.rs b/crates/codecs/tests/exr_multipart.rs
index f106d3779..421d49471 100644
--- a/crates/codecs/tests/exr_multipart.rs
+++ b/crates/codecs/tests/exr_multipart.rs
@@ -8,7 +8,9 @@ use exr::prelude::{
WritableImage,
};
use photocraft_codecs::f16;
-use photocraft_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, Format, Limits, SampleType, decode, decode_as_with, decode_exr_part, exr_info};
+use photocraft_codecs::{
+ ChannelLayout, DecodeOptions, DecodeWarning, Format, Limits, SampleType, decode, decode_as_with, decode_exr_part, exr_info, probe_size,
+};
fn layer_f32(name: &str, comp: Compression, chans: &[(&str, Vec<f32>)]) -> Layer<AnyChannels<FlatSamples>> {
let n = chans.iter().find(|(_, v)| !v.is_empty()).map_or(0, |(_, v)| v.len());
@@ -226,3 +228,107 @@ fn decoding_one_part_does_not_decode_the_others() {
assert_eq!((img.width(), img.height()), (4, 4));
assert!(img.to_normalized().iter().all(|v| near(*v, 0.75)), "wrong pixels");
}
+
+fn channel_group_file(channels: &[(&str, f32)]) -> Vec<u8> {
+ let channels: Vec<_> = channels.iter().map(|(name, value)| (*name, vec![*value; 4])).collect();
+ write_image(vec![layer_f32("groups", Compression::ZIP1, &channels)])
+}
+
+fn assert_channel_group(bytes: &[u8], layout: ChannelLayout, expected: &[f32]) {
+ assert_eq!(exr_info(bytes, &Limits::default()).unwrap()[0].color_rank(), expected.len() as u8);
+ assert_eq!(probe_size(bytes).unwrap(), (2, 2));
+ for img in [decode(bytes).unwrap(), decode_exr_part(bytes, 0, &DecodeOptions::default()).unwrap()] {
+ assert_eq!(img.layout(), layout);
+ assert_eq!(img.to_normalized(), expected.repeat(4));
+ }
+}
+
+#[test]
+fn flat_decode_keeps_rgb_channels_in_one_group() {
+ // A partial group sorts before the nested beauty layer, but cannot donate its R.
+ let bytes = channel_group_file(&[("aaa.R", 9.0), ("beauty.diffuse.R", 0.25), ("beauty.diffuse.G", 0.5), ("beauty.diffuse.B", 2.0)]);
+ assert_channel_group(&bytes, ChannelLayout::Rgb, &[0.25, 0.5, 2.0]);
+}
+
+#[test]
+fn flat_decode_does_not_borrow_another_groups_alpha() {
+ for alpha in ["A", "aaa.A", "beauty.other.A"] {
+ let bytes = channel_group_file(&[(alpha, 0.125), ("beauty.R", 0.25), ("beauty.G", 0.5), ("beauty.B", 2.0)]);
+ assert_channel_group(&bytes, ChannelLayout::Rgb, &[0.25, 0.5, 2.0]);
+ let bytes = channel_group_file(&[(alpha, 0.125), ("beauty.Y", 0.5)]);
+ assert_channel_group(&bytes, ChannelLayout::Gray, &[0.5]);
+ }
+}
+
+#[test]
+fn flat_decode_rejects_rgb_split_between_groups() {
+ for channels in [
+ [("aaa.R", 0.25), ("bbb.G", 0.5), ("ccc.B", 2.0)],
+ [("beauty.R", 0.25), ("beauty.diffuse.G", 0.5), ("beauty.diffuse.B", 2.0)],
+ [(".R", 0.25), ("G", 0.5), ("B", 2.0)],
+ ] {
+ let bytes = channel_group_file(&channels);
+ assert_eq!(exr_info(&bytes, &Limits::default()).unwrap()[0].color_rank(), 0);
+ assert!(probe_size(&bytes).is_err());
+ assert!(decode(&bytes).is_err());
+ assert!(decode_exr_part(&bytes, 0, &DecodeOptions::default()).is_err());
+ }
+}
+
+#[test]
+fn auto_pick_and_probe_skip_incoherent_rgb_parts() {
+ let bytes = write_image(vec![
+ layer_f32("split", Compression::ZIP1, &[("aaa.R", vec![9.0; 4]), ("bbb.G", vec![8.0; 4]), ("ccc.B", vec![7.0; 4])]),
+ layer_f32("luminance", Compression::ZIP1, &[("Y", vec![0.5; 16]), ("A", vec![0.75; 16])]),
+ ]);
+ let parts = exr_info(&bytes, &Limits::default()).unwrap();
+ assert_eq!(parts.iter().map(|part| part.color_rank()).collect::<Vec<_>>(), [0, 2]);
+ assert_eq!(probe_size(&bytes).unwrap(), (4, 4));
+ let img = decode(&bytes).unwrap();
+ assert_eq!((img.width(), img.height(), img.layout()), (4, 4, ChannelLayout::GrayA));
+ assert_eq!(img.to_f32_samples().unwrap(), [0.5, 0.75].repeat(16));
+}
+
+#[test]
+fn flat_decode_prefers_the_highest_ranked_complete_group() {
+ let bytes =
+ channel_group_file(&[("aaa.R", 9.0), ("aaa.G", 8.0), ("aaa.B", 7.0), ("beauty.R", 0.25), ("beauty.G", 0.5), ("beauty.B", 2.0), ("beauty.A", 0.75)]);
+ assert_channel_group(&bytes, ChannelLayout::Rgba, &[0.25, 0.5, 2.0, 0.75]);
+ let bytes = channel_group_file(&[("aaa.Y", 9.0), ("beauty.Y", 0.5), ("beauty.A", 0.75)]);
+ assert_channel_group(&bytes, ChannelLayout::GrayA, &[0.5, 0.75]);
+}
+
+#[test]
+fn flat_decode_breaks_group_ties_by_prefix() {
+ let bytes = channel_group_file(&[("z.R", 9.0), ("z.G", 8.0), ("z.B", 7.0), ("beauty.R", 0.25), ("beauty.G", 0.5), ("beauty.B", 2.0)]);
+ assert_channel_group(&bytes, ChannelLayout::Rgb, &[0.25, 0.5, 2.0]);
+ // Even a prefix that sorts before the unprefixed channel names loses a rank tie.
+ let bytes = channel_group_file(&[("0.R", 9.0), ("0.G", 8.0), ("0.B", 7.0), ("R", 0.25), ("G", 0.5), ("B", 2.0)]);
+ assert_channel_group(&bytes, ChannelLayout::Rgb, &[0.25, 0.5, 2.0]);
+}
+
+#[test]
+fn flat_decode_preserves_luminance_and_lone_channel_fallbacks() {
+ for prefix in ["", "beauty."] {
+ let y = format!("{prefix}Y");
+ let a = format!("{prefix}A");
+ assert_channel_group(&channel_group_file(&[(&y, 2.0), (&a, 0.75)]), ChannelLayout::GrayA, &[2.0, 0.75]);
+ assert_channel_group(&channel_group_file(&[(&y, 2.0)]), ChannelLayout::Gray, &[2.0]);
+ }
+ for name in ["depth.Z", "A", "beauty.A"] {
+ // A lone alpha is one grayscale channel, not the same samples duplicated as YA.
+ assert_channel_group(&channel_group_file(&[(name, 9.0)]), ChannelLayout::Gray, &[9.0]);
+ }
+}
+
+#[test]
+fn half_float_group_does_not_use_unrelated_float_channels() {
+ let mut layer = layer_f32("mixed", Compression::ZIP1, &[("aaa.R", vec![9.0; 4]), ("aaa.A", vec![0.125; 4])]);
+ for (name, value) in [("beauty.R", 0.25), ("beauty.G", 0.5), ("beauty.B", 2.0), ("beauty.A", 0.75)] {
+ layer.channel_data.list.push(AnyChannel::new(name, FlatSamples::F16(vec![f16::from_f32(value); 4])));
+ }
+ layer.channel_data = AnyChannels::sort(layer.channel_data.list);
+ let bytes = write_image(vec![layer]);
+ assert_channel_group(&bytes, ChannelLayout::Rgba, &[0.25, 0.5, 2.0, 0.75]);
+ assert_eq!(decode(&bytes).unwrap().sample_type(), SampleType::F16);
+}