Skip to content

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

EXR: multi-part files open the colour part; exr_info lists them all (#2116)

Elvis33LEf9ea13a85775
diff --git a/crates/codecs/README.md b/crates/codecs/README.md
index 6e85d7f24..af6b4b776 100644
--- a/crates/codecs/README.md
+++ b/crates/codecs/README.md
@@ -151,7 +151,13 @@ the same.
* **TIFF encode** writes classic TIFF, or BigTIFF when `EncodeOptions::tiff_bigtiff` is set or
the file could pass 4 GiB.
* **EXR**
- * Reads the first valid layer at full resolution, from its data window.
+ * Multi-part files (a Maya/Arnold render writes one part per AOV) open the part that
+ looks most like a colour image — RGBA beats RGB beats YA beats a single channel, so a
+ depth-only part no longer fails the file — with `DecodeWarning::MoreParts` naming how
+ many parts exist. `exr_info` lists every part (name, view, size, channels, deep/tiled)
+ without decoding pixels, and `decode_exr_part` decodes a chosen one. Deep parts stay
+ with the deep decoder: a file that has any is refused here with a pointer to it.
+ * Reads at full resolution, from the data window.
* Channel names are matched by suffix, so `layer.R` counts as `R`.
* Subsampled channels are unsupported.
* Deep data (scanlines or single-level tiles, compressed NONE, RLE or ZIPS) opens as a flat
diff --git a/crates/codecs/src/codecs/exr.rs b/crates/codecs/src/codecs/exr.rs
index d1ec9297f..57197ee7a 100644
--- a/crates/codecs/src/codecs/exr.rs
+++ b/crates/codecs/src/codecs/exr.rs
@@ -1,9 +1,12 @@
//! OpenEXR via the pure-Rust `exr` crate: F16/F32, Y/YA/RGB/RGBA channels,
-//! lossless compression. Reads the first valid layer at full resolution;
-//! pixel data is taken from the data window.
+//! lossless compression. Multi-part files (a Maya/Arnold render writes one part
+//! per AOV) open the part that looks most like a colour image, with a warning
+//! naming how many parts exist; [`info`] lists every part and [`decode_part`]
+//! decodes a chosen one. Pixel data is taken from the data window.
use std::io::Cursor;
+use exr::meta::MetaData;
use exr::prelude::{
AnyChannel, AnyChannels, Blocks, Compression, Encoding, FlatSamples, Layer, LayerAttributes, LineOrder, ReadChannels, ReadLayers, WritableImage, read,
};
@@ -12,7 +15,7 @@ use half::f16;
use crate::Format;
use crate::error::CodecError;
use crate::fidelity::Plan;
-use crate::image::{ChannelLayout, Image, SampleType};
+use crate::image::{ChannelLayout, DecodeWarning, ExrChannelInfo, ExrPartInfo, Image, SampleType, base_channel_name};
use crate::options::{EncodeOptions, ExrCompression, Limits};
const F: Format = Format::OpenExr;
@@ -30,40 +33,78 @@ fn map_exr(e: exr::error::Error) -> CodecError {
}
}
-/// Strip an optional `layer.` prefix from a channel name.
-fn base_name(name: &str) -> &str {
- name.rsplit('.').next().unwrap_or(name)
-}
-
-pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError> {
- // Check declared sizes before any pixel allocation.
- let meta = exr::meta::MetaData::read_from_buffered(Cursor::new(bytes), false).map_err(err)?;
+/// Read the headers without the `exr` crate's validation (it rejects deep parts outright),
+/// after checking every part's declared size against the limits, before any pixel allocation.
+fn read_meta(bytes: &[u8], limits: &Limits) -> Result<MetaData, CodecError> {
+ let meta = MetaData::read_from_buffered(Cursor::new(bytes), false).map_err(err)?;
+ // Flat decoding reads every part at once, so the parts' sizes are also capped together.
+ let mut total: u64 = 0;
for header in meta.headers.iter() {
let size = header.layer_size;
let (w, h) = (u32::try_from(size.0).unwrap_or(u32::MAX), u32::try_from(size.1).unwrap_or(u32::MAX));
let bpp = header.channels.list.len().max(1) as u64 * 4;
limits.check_bytes(w, h, bpp)?;
+ total = total.saturating_add(u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bpp));
}
+ if total > limits.max_alloc {
+ return Err(CodecError::LimitExceeded(format!("{total} bytes across {} parts exceed max_alloc {}", meta.headers.len(), limits.max_alloc)));
+ }
+ Ok(meta)
+}
- // Deep parts are rejected by the `exr` crate's reader; walk their chunks ourselves and
- // composite the samples into the flat image (a warning says what was lost).
- if meta.requirements.has_deep_data {
- let deep = super::deep_exr::decode_deep(&meta, bytes, limits)?;
- return super::deep_exr::flatten(&deep);
+/// Header facts of one part, in file order.
+fn part_info(index: usize, header: &exr::meta::header::Header) -> ExrPartInfo {
+ let (w, h) = (u32::try_from(header.layer_size.0).unwrap_or(u32::MAX), u32::try_from(header.layer_size.1).unwrap_or(u32::MAX));
+ let sample = |t: exr::meta::attribute::SampleType| match t {
+ exr::meta::attribute::SampleType::F16 => SampleType::F16,
+ // U32 channels (Arnold ID buffers) are listed as F32: exact up to 2^24.
+ exr::meta::attribute::SampleType::F32 | exr::meta::attribute::SampleType::U32 => SampleType::F32,
+ };
+ ExrPartInfo {
+ index,
+ name: header.own_attributes.layer_name.as_ref().map(|n| n.to_string()),
+ view: header.own_attributes.view_name.as_ref().map(|v| v.to_string()),
+ width: w,
+ height: h,
+ deep: header.deep,
+ tiled: matches!(header.blocks, exr::meta::BlockDescription::Tiles(_)),
+ channels: header.channels.list.iter().map(|c| ExrChannelInfo { name: c.name.to_string(), sample: sample(c.sample_type) }).collect(),
}
+}
+
+/// Lists every part of the file (header facts only, no pixel data): what a multi-part
+/// chooser offers, and what [`decode_part`] takes an index into.
+pub(crate) fn info(bytes: &[u8], limits: &Limits) -> Result<Vec<ExrPartInfo>, CodecError> {
+ let meta = read_meta(bytes, limits)?;
+ Ok(meta.headers.iter().enumerate().map(|(i, h)| part_info(i, h)).collect())
+}
+
+/// The part plain [`decode`] opens: the highest [`ExrPartInfo::color_rank`], earliest wins.
+fn pick_part(meta: &MetaData) -> usize {
+ let mut best = 0;
+ let mut best_rank = meta.headers.first().map_or(0, |h| part_info(0, h).color_rank());
+ for (i, header) in meta.headers.iter().enumerate().skip(1) {
+ let rank = part_info(i, header).color_rank();
+ if rank > best_rank {
+ best = i;
+ best_rank = rank;
+ }
+ }
+ best
+}
+
+/// Decode the flat layers via the `exr` crate (it handles every flat compression) and
+/// return the requested part's layer.
+fn read_layer(bytes: &[u8], index: usize) -> Result<Layer<AnyChannels<FlatSamples>>, CodecError> {
+ let image =
+ read().no_deep_data().largest_resolution_level().all_channels().all_layers().all_attributes().from_buffered(Cursor::new(bytes)).map_err(map_exr)?;
+ image.layer_data.into_iter().nth(index).ok_or_else(|| err(format!("part {index} is missing from the file")))
+}
- let image = read()
- .no_deep_data()
- .largest_resolution_level()
- .all_channels()
- .first_valid_layer()
- .all_attributes()
- .from_buffered(Cursor::new(bytes))
- .map_err(map_exr)?;
- let layer = &image.layer_data;
+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_name(c.name.to_string().as_str()) == n);
+ 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),
@@ -108,6 +149,38 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
Ok(img)
}
+pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError> {
+ let meta = read_meta(bytes, limits)?;
+
+ // Deep parts are rejected by the `exr` crate's reader; walk their chunks ourselves and
+ // composite the samples into the flat image (a warning says what was lost).
+ if meta.requirements.has_deep_data {
+ let deep = super::deep_exr::decode_deep(&meta, bytes, limits)?;
+ return super::deep_exr::flatten(&deep);
+ }
+
+ let pick = pick_part(&meta);
+ let mut img = layer_to_image(&read_layer(bytes, pick)?)?;
+ if meta.headers.len() > 1 {
+ let total = u32::try_from(meta.headers.len()).ok();
+ img.warnings.push(DecodeWarning::MoreParts { total });
+ }
+ Ok(img)
+}
+
+/// Decode one part of a multi-part file by its index into [`info`]'s list. A file with
+/// deep parts is not mixed: the deep decoder composites those instead.
+pub(crate) fn decode_part(bytes: &[u8], index: usize, limits: &Limits) -> Result<Image, CodecError> {
+ let meta = read_meta(bytes, limits)?;
+ if meta.requirements.has_deep_data {
+ return Err(CodecError::unsupported(F, "this file has deep parts; the deep decoder composites those (mixing flat and deep parts is not supported)"));
+ }
+ if index >= meta.headers.len() {
+ return Err(err(format!("part index {index} is out of range ({} parts)", meta.headers.len())));
+ }
+ layer_to_image(&read_layer(bytes, index)?)
+}
+
pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Vec<u8>, CodecError> {
let img = src.converted(plan.layout, plan.sample);
let (w, h) = (img.width() as usize, img.height() as usize);
diff --git a/crates/codecs/src/image.rs b/crates/codecs/src/image.rs
index 1ded97308..c0323b612 100644
--- a/crates/codecs/src/image.rs
+++ b/crates/codecs/src/image.rs
@@ -148,6 +148,8 @@ pub enum DecodeWarning {
MoreFrames { total: Option<u32> },
/// Only the first page of a multi-page file was decoded; `total` counts every page when known.
MorePages { total: Option<u32> },
+ /// Only one part of a multi-part file was decoded; `total` counts every part when known.
+ MoreParts { total: Option<u32> },
/// The image data ends early (truncated or damaged file); the decoder filled in the rest
/// (a baseline JPEG's missing rows come out grey).
Truncated { format: Format },
@@ -163,6 +165,8 @@ impl fmt::Display for DecodeWarning {
DecodeWarning::MoreFrames { total: None } => write!(f, "only the first frame of the animation was imported"),
DecodeWarning::MorePages { total: Some(n) } => write!(f, "only the first of {n} pages was imported"),
DecodeWarning::MorePages { total: None } => write!(f, "only the first page of the file was imported"),
+ DecodeWarning::MoreParts { total: Some(n) } => write!(f, "only one of {n} EXR parts was imported"),
+ DecodeWarning::MoreParts { total: None } => write!(f, "only one EXR part of the file was imported"),
DecodeWarning::Truncated { format } => {
write!(f, "{} data ends early (the file is truncated or damaged); part of the image is missing", format.name())
}
@@ -221,6 +225,58 @@ impl DeepImage {
}
}
+/// One channel of an [`ExrPartInfo`]: the name as in the file (a Maya/Arnold AOV layer
+/// keeps its prefix, e.g. `diffuse.R`) and the sample type that part stores it with.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ExrChannelInfo {
+ pub name: String,
+ pub sample: SampleType,
+}
+
+/// One part of a multi-part OpenEXR file (what a Maya/Arnold render writes per AOV):
+/// header facts only, no pixel data. [`crate::exr_info`] lists them, and the index is
+/// what [`crate::decode_exr_part`] decodes; [`crate::decode_as_with`] opens the part
+/// the ranking in [`ExrPartInfo::color_rank`] prefers.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ExrPartInfo {
+ /// Index into the part list, in file order.
+ pub index: usize,
+ /// The part `name` attribute, when the file records one (Arnold names parts after AOVs).
+ pub name: Option<String>,
+ /// The part `view` attribute for stereo files (`left`/`right`).
+ pub view: Option<String>,
+ pub width: u32,
+ pub height: u32,
+ /// True for `deepscanline`/`deeptile` parts; those are composited by the deep
+ /// decoder ([`crate::decode_deep_exr`]), not decoded part by part.
+ pub deep: bool,
+ /// True when the part is stored as tiles instead of scanlines.
+ pub tiled: bool,
+ /// The part's channels in file order.
+ pub channels: Vec<ExrChannelInfo>,
+}
+
+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`).
+ /// 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 };
+ }
+ if has("Y") {
+ return if has("A") { 2 } else { 1 };
+ }
+ u8::from(self.channels.len() == 1)
+ }
+}
+
+/// Strip an optional `layer.` prefix from a channel name (`diffuse.R` → `R`).
+pub(crate) fn base_channel_name(name: &str) -> &str {
+ name.rsplit('.').next().unwrap_or(name)
+}
+
/// A single flat raster image.
#[derive(Debug, Clone, PartialEq)]
pub struct Image {
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index d75e169cf..e1b240ba4 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -29,7 +29,7 @@ pub use crate::codecs::tiff_ifd::{TiffInfo, TiffPage, TiffPageKind};
pub use crate::error::CodecError;
pub use crate::fidelity::{FidelityWarning, fidelity_warnings, fidelity_warnings_with};
pub use crate::format::{ASYMMETRIC_EXCEPTIONS, Format, FormatCaps, caps, detect, from_extension};
-pub use crate::image::{ChannelLayout, DecodeWarning, DeepChannel, DeepImage, Image, Metadata, SampleType};
+pub use crate::image::{ChannelLayout, DecodeWarning, DeepChannel, DeepImage, ExrChannelInfo, ExrPartInfo, Image, Metadata, SampleType};
pub use crate::options::{DecodeOptions, EncodeOptions, ExrCompression, Limits, PngCompression, TiffCompression};
pub use crate::orientation::{exif_orientation, upright_exif, upright_xmp};
pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_resolution, xmp_resolution};
@@ -130,6 +130,21 @@ fn finish_decode(img: Image, o: u16, opts: &DecodeOptions) -> Result<Image, Code
img.oriented(o)
}
+/// Lists the parts of an OpenEXR file without decoding pixels: header facts per part
+/// (name, view, size, channels, deep/tiled), what a multi-part chooser — a Maya/Arnold
+/// render writes one part per AOV — offers. The indices are what [`decode_exr_part`]
+/// takes; [`decode_as_with`] opens the part with the highest [`ExrPartInfo::color_rank`].
+pub fn exr_info(bytes: &[u8], limits: &Limits) -> Result<Vec<ExrPartInfo>, CodecError> {
+ exr::info(bytes, limits)
+}
+
+/// Decodes part `part` (an index into [`exr_info`]'s list) of an OpenEXR file.
+/// Deep parts stay with [`decode_deep_exr`]; a file that has any is refused here.
+pub fn decode_exr_part(bytes: &[u8], part: usize, opts: &DecodeOptions) -> Result<Image, CodecError> {
+ let img = exr::decode_part(bytes, part, &opts.limits)?;
+ finish_decode(img, 1, opts)
+}
+
/// Deep OpenEXR samples (`deepscanline`/`deeptile`): the structured per-pixel sample lists
/// (colour, alpha and Z per sample), for callers that composite deep data themselves —
/// [`decode_as_with`] instead flattens a deep file into a normal [`Image`] with a
diff --git a/crates/codecs/tests/exr_multipart.rs b/crates/codecs/tests/exr_multipart.rs
new file mode 100644
index 000000000..c8f9a3bc3
--- /dev/null
+++ b/crates/codecs/tests/exr_multipart.rs
@@ -0,0 +1,199 @@
+//! Multi-part EXR (a Maya/Arnold render writes one part per AOV): the `exr` crate
+//! writes synthetic files with several parts, the info/decode tests check the part
+//! listing, the colour-ranked auto-pick and part-by-index decoding, and malformed
+//! inputs must error, never panic.
+
+use exr::prelude::{
+ AnyChannel, AnyChannels, Blocks, Compression, Encoding, FlatSamples, Image, ImageAttributes, IntegerBounds, Layer, LayerAttributes, LineOrder,
+ WritableImage,
+};
+use photocraft_codecs::f16;
+use photocraft_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, Format, Limits, SampleType, decode, decode_as_with, decode_exr_part, exr_info};
+
+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());
+ let list = chans
+ .iter()
+ .map(|(cn, v)| {
+ assert_eq!(v.len(), n, "channel lengths must match");
+ AnyChannel::new(*cn, FlatSamples::F32(v.clone()))
+ })
+ .collect::<Vec<_>>();
+ let h = (n as f32).sqrt().round() as usize; // tests use square images
+ Layer::new(
+ (h, h),
+ LayerAttributes::named(name),
+ Encoding { compression: comp, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing },
+ AnyChannels::sort(list.into_iter().collect()),
+ )
+}
+
+/// Three parts in the order an AOV-heavy render might use: a depth-only `Z` part first
+/// (which used to make the whole file fail with "no R/G/B or Y channels"), the `beauty`
+/// RGBA part second and a `diffuse` RGB part third, each with its own compression.
+fn aov_file() -> Vec<u8> {
+ let n = 16;
+ let z: Vec<f32> = (0..n).map(|i| i as f32).collect();
+ let beauty: [Vec<f32>; 4] = std::array::from_fn(|c| {
+ (0..n)
+ .map(|i| match c {
+ 0 => i as f32 / 15.0,
+ 1 => 1.0 - i as f32 / 15.0,
+ 2 => 0.25,
+ _ => 1.0,
+ })
+ .collect()
+ });
+ let diffuse: [Vec<f32>; 3] = std::array::from_fn(|c| (0..n).map(|_| [0.3, 0.6, 0.9][c]).collect());
+ let layers = vec![
+ layer_f32("Z", Compression::Uncompressed, &[("Z", z)]),
+ layer_f32("beauty", Compression::ZIP1, &[("R", beauty[0].clone()), ("G", beauty[1].clone()), ("B", beauty[2].clone()), ("A", beauty[3].clone())]),
+ layer_f32("diffuse", Compression::RLE, &[("R", diffuse[0].clone()), ("G", diffuse[1].clone()), ("B", diffuse[2].clone())]),
+ ];
+ write_image(layers)
+}
+
+fn write_image(layers: Vec<Layer<AnyChannels<FlatSamples>>>) -> Vec<u8> {
+ let size: (usize, usize) = layers.first().map_or((1, 1), |l| l.size.into());
+ let bounds = IntegerBounds::new((0, 0), size);
+ let image = Image::from_layers(ImageAttributes::new(bounds), layers);
+ let mut out = std::io::Cursor::new(Vec::new());
+ image.write().to_buffered(&mut out).expect("synthetic exr writes");
+ out.into_inner()
+}
+
+fn stereo_file() -> Vec<u8> {
+ let n = 4;
+ let px = |k: f32| -> [Vec<f32>; 4] { std::array::from_fn(|c| (0..n).map(|i| if c == 0 { i as f32 / 3.0 * k } else { k }).collect()) };
+ let left = px(0.1);
+ let right = px(0.9);
+ let with_view = |name: &str, view: &str, p: [Vec<f32>; 4]| {
+ let attrs = LayerAttributes { view_name: Some(view.into()), ..LayerAttributes::named(name) };
+ let list: Vec<_> = ["R", "G", "B", "A"].iter().enumerate().map(|(c, cn)| AnyChannel::new(*cn, FlatSamples::F32(p[c].clone()))).collect();
+ Layer::new(
+ (2, 2),
+ attrs,
+ Encoding { compression: Compression::Uncompressed, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing },
+ AnyChannels::sort(list.into_iter().collect()),
+ )
+ };
+ // The `exr` crate refuses duplicate part names when writing, so a stereo pair is
+ // emulated with distinct names that still carry the view attribute.
+ write_image(vec![with_view("beauty_left", "left", left), with_view("beauty_right", "right", right)])
+}
+
+fn near(a: f32, b: f32) -> bool {
+ (a - b).abs() < 1e-6
+}
+
+#[test]
+fn info_lists_every_part() {
+ let parts = exr_info(&aov_file(), &Limits::default()).unwrap();
+ assert_eq!(parts.len(), 3);
+ assert_eq!(parts.iter().map(|p| p.name.as_deref()).collect::<Vec<_>>(), [Some("Z"), Some("beauty"), Some("diffuse")]);
+ let z = &parts[0];
+ assert_eq!((z.width, z.height), (4, 4));
+ assert!(!z.deep && !z.tiled);
+ assert_eq!(z.channels.len(), 1);
+ assert_eq!(z.channels[0].name, "Z");
+ assert_eq!(z.channels[0].sample, SampleType::F32);
+ let beauty = &parts[1];
+ // OpenEXR stores the channel list in the header alphabetically; the info shows the file as-is.
+ assert_eq!(beauty.channels.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["A", "B", "G", "R"]);
+ assert_eq!(beauty.channels.iter().map(|c| c.sample).collect::<Vec<_>>(), [SampleType::F32; 4]);
+}
+
+#[test]
+fn auto_pick_skips_the_depth_part() {
+ let img = decode(&aov_file()).unwrap();
+ assert_eq!(img.layout(), ChannelLayout::Rgba);
+ assert!(img.warnings.contains(&DecodeWarning::MoreParts { total: Some(3) }), "{:?}", img.warnings);
+ for i in 0..16 {
+ let (x, y) = (i % 4, i / 4);
+ assert!(near(img.get(x, y, 0), i as f32 / 15.0), "pixel {i}");
+ assert!(near(img.get(x, y, 1), 1.0 - i as f32 / 15.0), "pixel {i}");
+ assert!(near(img.get(x, y, 2), 0.25), "pixel {i}");
+ assert!(near(img.get(x, y, 3), 1.0), "pixel {i}");
+ }
+}
+
+#[test]
+fn parts_decode_by_index() {
+ let bytes = aov_file();
+ // The depth part opens as a grayscale image instead of failing the file.
+ let z = decode_exr_part(&bytes, 0, &DecodeOptions::default()).unwrap();
+ assert_eq!(z.layout(), ChannelLayout::Gray);
+ for i in 0..16 {
+ assert!(near(z.get(i % 4, i / 4, 0), i as f32), "pixel {i}");
+ }
+ let diffuse = decode_exr_part(&bytes, 2, &DecodeOptions::default()).unwrap();
+ assert_eq!(diffuse.layout(), ChannelLayout::Rgb);
+ assert!(near(diffuse.get(1, 2, 2), 0.9));
+ // An explicit part choice does not warn about the parts left out.
+ assert!(!diffuse.warnings.contains(&DecodeWarning::MoreParts { total: Some(3) }));
+}
+
+#[test]
+fn part_index_out_of_range_errors() {
+ let bytes = aov_file();
+ let e = decode_exr_part(&bytes, 3, &DecodeOptions::default()).unwrap_err().to_string();
+ assert!(e.contains("out of range") && e.contains("3 parts"), "{e}");
+}
+
+#[test]
+fn views_are_listed_and_left_wins_the_auto_pick() {
+ let bytes = stereo_file();
+ let parts = exr_info(&bytes, &Limits::default()).unwrap();
+ assert_eq!(parts.iter().map(|p| p.view.as_deref()).collect::<Vec<_>>(), [Some("left"), Some("right")]);
+ let img = decode(&bytes).unwrap();
+ assert!(near(img.get(0, 0, 0), 0.0) && near(img.get(3, 0, 0), 0.1), "the left view is the first part");
+ assert!(near(img.get(1, 1, 1), 0.1), "left's G is 0.1 everywhere");
+ let right = decode_exr_part(&bytes, 1, &DecodeOptions::default()).unwrap();
+ assert!(near(right.get(1, 1, 1), 0.9), "right's G is 0.9 everywhere");
+}
+
+#[test]
+fn single_part_files_do_not_warn() {
+ let n = 4;
+ let v: Vec<f32> = (0..n).map(|i| i as f32 / 3.0).collect();
+ let bytes = write_image(vec![layer_f32("main", Compression::ZIP1, &[("Y", v)])]);
+ let img = decode(&bytes).unwrap();
+ assert_eq!(img.layout(), ChannelLayout::Gray);
+ assert!(img.warnings.is_empty(), "{:?}", img.warnings);
+}
+
+#[test]
+fn half_float_parts_stay_half() {
+ let n = 4;
+ let chans: [Vec<f16>; 3] = std::array::from_fn(|c| (0..n).map(|_| f16::from_f32([0.5, 0.25, 1.0][c])).collect());
+ let list: Vec<_> = ["R", "G", "B"].iter().enumerate().map(|(c, cn)| AnyChannel::new(*cn, FlatSamples::F16(chans[c].clone()))).collect();
+ let layer = Layer::new(
+ (2, 2),
+ LayerAttributes::named("half"),
+ Encoding { compression: Compression::Uncompressed, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing },
+ AnyChannels::sort(list.into_iter().collect()),
+ );
+ let bytes = write_image(vec![layer]);
+ let img = decode_exr_part(&bytes, 0, &DecodeOptions::default()).unwrap();
+ assert_eq!(img.sample_type(), SampleType::F16);
+ assert!(near(img.get(1, 1, 0), 0.5));
+}
+
+#[test]
+fn truncated_files_error_never_panic() {
+ let bytes = aov_file();
+ for end in (8..bytes.len()).step_by(5) {
+ let cut = &bytes[..end];
+ let _ = exr_info(cut, &Limits::default());
+ let _ = decode_as_with(Format::OpenExr, cut, &DecodeOptions::default());
+ let _ = decode_exr_part(cut, 1, &DecodeOptions::default());
+ }
+}
+
+#[test]
+fn parts_are_capped_together() {
+ // Each part fits alone (largest 256 bytes) but the three together (512) do not.
+ let limits = Limits { max_alloc: 300, ..Limits::default() };
+ let e = exr_info(&aov_file(), &limits).unwrap_err().to_string();
+ assert!(e.contains("across 3 parts"), "{e}");
+}