Skip to main content

xisf_core/
image.rs

1//! The `<Image>` core element: what the pixels are and how they are laid out.
2
3use crate::err;
4use crate::error::Result;
5use crate::header::Element;
6
7/// How pixel samples are stored.
8#[derive(Clone, Copy, PartialEq, Eq, Debug)]
9pub enum SampleFormat {
10    UInt8,
11    UInt16,
12    UInt32,
13    UInt64,
14    Float32,
15    Float64,
16    Complex32,
17    Complex64,
18}
19
20impl SampleFormat {
21    pub fn parse(name: &str) -> Option<Self> {
22        Some(match name {
23            "UInt8" => SampleFormat::UInt8,
24            "UInt16" => SampleFormat::UInt16,
25            "UInt32" => SampleFormat::UInt32,
26            "UInt64" => SampleFormat::UInt64,
27            "Float32" => SampleFormat::Float32,
28            "Float64" => SampleFormat::Float64,
29            "Complex32" => SampleFormat::Complex32,
30            "Complex64" => SampleFormat::Complex64,
31            _ => return None,
32        })
33    }
34
35    pub fn name(self) -> &'static str {
36        match self {
37            SampleFormat::UInt8 => "UInt8",
38            SampleFormat::UInt16 => "UInt16",
39            SampleFormat::UInt32 => "UInt32",
40            SampleFormat::UInt64 => "UInt64",
41            SampleFormat::Float32 => "Float32",
42            SampleFormat::Float64 => "Float64",
43            SampleFormat::Complex32 => "Complex32",
44            SampleFormat::Complex64 => "Complex64",
45        }
46    }
47
48    /// Bytes per sample. A complex sample is two components wide.
49    pub fn size(self) -> usize {
50        match self {
51            SampleFormat::UInt8 => 1,
52            SampleFormat::UInt16 => 2,
53            SampleFormat::UInt32 | SampleFormat::Float32 => 4,
54            SampleFormat::UInt64 | SampleFormat::Float64 | SampleFormat::Complex32 => 8,
55            SampleFormat::Complex64 => 16,
56        }
57    }
58
59    /// Whether samples are floating point, which decides how `bounds` applies.
60    pub fn is_float(self) -> bool {
61        matches!(
62            self,
63            SampleFormat::Float32
64                | SampleFormat::Float64
65                | SampleFormat::Complex32
66                | SampleFormat::Complex64
67        )
68    }
69
70    /// Whether an image in this format must declare a `bounds` attribute.
71    ///
72    /// "The bounds attribute is required for floating point real images, that
73    /// is, it shall be defined for images where the value of the sampleFormat
74    /// attribute is either Float32 or Float64."
75    ///
76    /// Deliberately not [`SampleFormat::is_float`], which also answers yes for
77    /// the complex formats: "For complex images the bounds attribute is
78    /// optional because the representable range is formally undefined for
79    /// these images." The two questions look alike and have different answers.
80    pub fn requires_bounds(self) -> bool {
81        matches!(self, SampleFormat::Float32 | SampleFormat::Float64)
82    }
83
84    /// The representable range an image in this format has when it declares no
85    /// `bounds`.
86    ///
87    /// "If the bounds attribute is not specified for an integer image, then
88    /// its representable range shall be [0, 2^k - 1], where k is the number of
89    /// bits per pixel sample." There is no default for the real formats, which
90    /// is why they must declare one, nor for the complex formats, whose range
91    /// is undefined.
92    pub fn default_bounds(self) -> Option<Bounds> {
93        let bits = match self {
94            SampleFormat::UInt8 => 8u32,
95            SampleFormat::UInt16 => 16,
96            SampleFormat::UInt32 => 32,
97            SampleFormat::UInt64 => 64,
98            _ => return None,
99        };
100        // 2^k - 1, computed in f64 because that is what Bounds holds and the
101        // 64-bit case exceeds what an f64 can represent exactly anyway.
102        Some(Bounds { low: 0.0, high: 2f64.powi(bits as i32) - 1.0 })
103    }
104}
105
106/// The colour space the channels are in.
107#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
108pub enum ColorSpace {
109    #[default]
110    Gray,
111    Rgb,
112    CieLab,
113}
114
115impl ColorSpace {
116    pub fn parse(name: &str) -> Option<Self> {
117        Some(match name {
118            "Gray" => ColorSpace::Gray,
119            "RGB" => ColorSpace::Rgb,
120            "CIELab" => ColorSpace::CieLab,
121            _ => return None,
122        })
123    }
124
125    pub fn name(self) -> &'static str {
126        match self {
127            ColorSpace::Gray => "Gray",
128            ColorSpace::Rgb => "RGB",
129            ColorSpace::CieLab => "CIELab",
130        }
131    }
132
133    /// How many channels this space needs, before any alpha channels.
134    pub fn nominal_channels(self) -> u64 {
135        match self {
136            ColorSpace::Gray => 1,
137            ColorSpace::Rgb | ColorSpace::CieLab => 3,
138        }
139    }
140}
141
142/// How samples of different channels are interleaved.
143#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
144pub enum PixelStorage {
145    /// Each channel stored whole, one after another. The spec's default.
146    #[default]
147    Planar,
148    /// Channels interleaved per pixel.
149    Normal,
150}
151
152impl PixelStorage {
153    pub fn parse(name: &str) -> Option<Self> {
154        Some(match name {
155            "Planar" => PixelStorage::Planar,
156            "Normal" => PixelStorage::Normal,
157            _ => return None,
158        })
159    }
160
161    pub fn name(self) -> &'static str {
162        match self {
163            PixelStorage::Planar => "Planar",
164            PixelStorage::Normal => "Normal",
165        }
166    }
167}
168
169/// The `imageType` attribute: what the image is for.
170///
171/// Revision 1's schema fixes this as a closed set, but an unrecognized value
172/// is kept rather than refused. It is metadata: it says what an image is for,
173/// not how to decode it, so losing an image over a word nobody recognizes
174/// would trade real pixels for a nicety. This follows [`crate::block::Codec`],
175/// which keeps an unknown codec by name for the same reason.
176#[derive(Clone, PartialEq, Eq, Debug)]
177pub enum ImageType {
178    Bias,
179    Dark,
180    Flat,
181    Light,
182    MasterBias,
183    MasterDark,
184    MasterFlat,
185    MasterLight,
186    DefectMap,
187    RejectionMapHigh,
188    RejectionMapLow,
189    BinaryRejectionMapHigh,
190    BinaryRejectionMapLow,
191    /// Values proportional to the *angle* of fitted lines, 0 to 90 degrees --
192    /// Revision 1 corrects this from "proportional to the slope", whose upper
193    /// bound would have represented an infinite slope.
194    SlopeMap,
195    WeightMap,
196    /// A value the specification does not define, kept as written.
197    Other(String),
198}
199
200impl ImageType {
201    pub fn parse(name: &str) -> Self {
202        match name {
203            "Bias" => ImageType::Bias,
204            "Dark" => ImageType::Dark,
205            "Flat" => ImageType::Flat,
206            "Light" => ImageType::Light,
207            "MasterBias" => ImageType::MasterBias,
208            "MasterDark" => ImageType::MasterDark,
209            "MasterFlat" => ImageType::MasterFlat,
210            "MasterLight" => ImageType::MasterLight,
211            "DefectMap" => ImageType::DefectMap,
212            "RejectionMapHigh" => ImageType::RejectionMapHigh,
213            "RejectionMapLow" => ImageType::RejectionMapLow,
214            "BinaryRejectionMapHigh" => ImageType::BinaryRejectionMapHigh,
215            "BinaryRejectionMapLow" => ImageType::BinaryRejectionMapLow,
216            "SlopeMap" => ImageType::SlopeMap,
217            "WeightMap" => ImageType::WeightMap,
218            other => ImageType::Other(other.to_string()),
219        }
220    }
221
222    pub fn name(&self) -> &str {
223        match self {
224            ImageType::Bias => "Bias",
225            ImageType::Dark => "Dark",
226            ImageType::Flat => "Flat",
227            ImageType::Light => "Light",
228            ImageType::MasterBias => "MasterBias",
229            ImageType::MasterDark => "MasterDark",
230            ImageType::MasterFlat => "MasterFlat",
231            ImageType::MasterLight => "MasterLight",
232            ImageType::DefectMap => "DefectMap",
233            ImageType::RejectionMapHigh => "RejectionMapHigh",
234            ImageType::RejectionMapLow => "RejectionMapLow",
235            ImageType::BinaryRejectionMapHigh => "BinaryRejectionMapHigh",
236            ImageType::BinaryRejectionMapLow => "BinaryRejectionMapLow",
237            ImageType::SlopeMap => "SlopeMap",
238            ImageType::WeightMap => "WeightMap",
239            ImageType::Other(name) => name,
240        }
241    }
242
243    /// Whether this is one of the values the specification defines.
244    pub fn is_standard(&self) -> bool {
245        !matches!(self, ImageType::Other(_))
246    }
247}
248
249/// The `bounds` attribute: the range floating-point samples are scaled to.
250#[derive(Clone, Copy, PartialEq, Debug)]
251pub struct Bounds {
252    pub low: f64,
253    pub high: f64,
254}
255
256/// An `<Image>` element's attributes, parsed.
257#[derive(Clone, PartialEq, Debug)]
258pub struct Image {
259    /// Dimensions, fastest-varying first, then the channel count.
260    ///
261    /// The spec writes `geometry="width:height:channels"` for a 2-D image,
262    /// and allows more dimensions before the channel count.
263    pub dimensions: Vec<u64>,
264    pub channels: u64,
265    pub sample_format: SampleFormat,
266    pub color_space: ColorSpace,
267    pub pixel_storage: PixelStorage,
268    /// Present for floating-point images; the spec's default is 0:1.
269    pub bounds: Option<Bounds>,
270    pub id: Option<String>,
271    pub uuid: Option<String>,
272    pub image_type: Option<ImageType>,
273    /// A pedestal added to every sample, which must be subtracted to get
274    /// zero-based values. The spec's default is zero.
275    ///
276    /// This is not cosmetic: calibration and integration subtract it, so an
277    /// image read without it has the wrong zero point.
278    pub offset: Option<f64>,
279    /// How the image should be reoriented for display. `None` is the spec's
280    /// default of no transformation.
281    ///
282    /// A decoder must *not* apply this for processing that depends on the
283    /// physical layout of the pixels -- calibration frames would no longer
284    /// line up -- so it is kept as a declaration rather than applied here.
285    pub orientation: Option<Orientation>,
286}
287
288/// The `orientation` attribute: a rotation, and optionally a horizontal flip.
289///
290/// The rotation is counter-clockwise in degrees, and the flip is applied
291/// after it, which is the order the spec's `90;flip` spelling implies.
292#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
293pub struct Orientation {
294    /// One of 0, 90, 180 or -90.
295    pub rotation: i16,
296    pub flip_horizontal: bool,
297}
298
299impl Orientation {
300    /// Parse an `orientation` attribute.
301    pub fn parse(text: &str) -> Result<Self> {
302        let (rotation, flip_horizontal) = match text.strip_suffix(";flip") {
303            Some(rest) => (rest, true),
304            None => match text {
305                "flip" => ("0", true),
306                rest => (rest, false),
307            },
308        };
309        let rotation = match rotation {
310            "0" => 0,
311            "90" => 90,
312            "180" => 180,
313            "-90" => -90,
314            other => {
315                return Err(err!(BadAttribute, "unknown orientation rotation {other:?}"));
316            }
317        };
318        Ok(Orientation { rotation, flip_horizontal })
319    }
320
321    /// The attribute text for this orientation.
322    pub fn to_attribute(self) -> String {
323        match (self.rotation, self.flip_horizontal) {
324            (0, false) => "0".into(),
325            (0, true) => "flip".into(),
326            (rotation, false) => rotation.to_string(),
327            (rotation, true) => format!("{rotation};flip"),
328        }
329    }
330
331    /// Whether this leaves the image as stored.
332    pub fn is_identity(self) -> bool {
333        self.rotation == 0 && !self.flip_horizontal
334    }
335}
336
337impl Image {
338    /// Parse an `<Image>` element's attributes.
339    pub fn parse(element: &Element) -> Result<Self> {
340        if element.name != "Image" {
341            return Err(err!(InvalidArgument, "expected <Image>, got <{}>", element.name));
342        }
343
344        let geometry = element
345            .attr("geometry")
346            .ok_or_else(|| err!(BadHeader, "<Image> has no geometry attribute"))?;
347        let (dimensions, channels) = parse_geometry(geometry)?;
348
349        let sample_format = element
350            .attr("sampleFormat")
351            .ok_or_else(|| err!(BadHeader, "<Image> has no sampleFormat attribute"))?;
352        let sample_format = SampleFormat::parse(sample_format)
353            .ok_or_else(|| err!(Unsupported, "unknown sampleFormat {sample_format:?}"))?;
354
355        // `colorSpace` and `pixelStorage` are optional and default per the
356        // spec; an unrecognised *value* is still an error, since guessing
357        // would misread the pixels.
358        let color_space = match element.attr("colorSpace") {
359            None => ColorSpace::default(),
360            Some(name) => ColorSpace::parse(name)
361                .ok_or_else(|| err!(Unsupported, "unknown colorSpace {name:?}"))?,
362        };
363        let pixel_storage = match element.attr("pixelStorage") {
364            None => PixelStorage::default(),
365            Some(name) => PixelStorage::parse(name)
366                .ok_or_else(|| err!(Unsupported, "unknown pixelStorage {name:?}"))?,
367        };
368
369        let bounds = match element.attr("bounds") {
370            None => None,
371            Some(text) => Some(parse_bounds(text)?),
372        };
373
374        Ok(Image {
375            dimensions,
376            channels,
377            sample_format,
378            color_space,
379            pixel_storage,
380            bounds,
381            id: element.attr("id").map(str::to_owned),
382            uuid: element.attr("uuid").map(str::to_owned),
383            image_type: element.attr("imageType").map(ImageType::parse),
384            offset: match element.attr("offset") {
385                None => None,
386                Some(text) => Some(parse_offset(text)?),
387            },
388            orientation: match element.attr("orientation") {
389                None => None,
390                Some(text) => Some(Orientation::parse(text)?),
391            },
392        })
393    }
394
395    /// Total number of samples: every dimension times the channel count.
396    pub fn sample_count(&self) -> Option<u64> {
397        self.dimensions
398            .iter()
399            .try_fold(1u64, |acc, d| acc.checked_mul(*d))?
400            .checked_mul(self.channels)
401    }
402
403    /// The size the pixel data should be, in bytes.
404    pub fn data_size(&self) -> Option<u64> {
405        self.sample_count()?.checked_mul(self.sample_format.size() as u64)
406    }
407
408    /// Whether the channel count covers what the colour space needs.
409    ///
410    /// More channels than nominal is legal -- they are alpha channels -- but
411    /// fewer means the image cannot be interpreted in the space it declares.
412    pub fn channels_suffice(&self) -> bool {
413        self.channels >= self.color_space.nominal_channels()
414    }
415}
416
417/// Parse `geometry="d1:d2:...:channels"`.
418///
419/// The last field is always the channel count, and at least one dimension has
420/// to precede it, so `"10"` alone is not a geometry.
421fn parse_geometry(text: &str) -> Result<(Vec<u64>, u64)> {
422    let fields: Vec<&str> = text.split(':').collect();
423    if fields.len() < 2 {
424        return Err(err!(
425            BadAttribute,
426            "geometry needs at least one dimension and a channel count, got {text:?}"
427        ));
428    }
429
430    let mut values = Vec::with_capacity(fields.len());
431    for field in &fields {
432        let value = field
433            .parse::<u64>()
434            .map_err(|_| err!(BadAttribute, "geometry field {field:?} is not a decimal integer"))?;
435        values.push(value);
436    }
437
438    let channels = values.pop().expect("checked non-empty above");
439    if channels == 0 {
440        return Err(err!(BadAttribute, "an image with zero channels has no pixels"));
441    }
442    if values.contains(&0) {
443        return Err(err!(BadAttribute, "geometry {text:?} has a zero-length dimension"));
444    }
445    Ok((values, channels))
446}
447
448/// Parse `bounds="low:high"`.
449fn parse_bounds(text: &str) -> Result<Bounds> {
450    let (low, high) = text
451        .split_once(':')
452        .ok_or_else(|| err!(BadAttribute, "bounds needs low:high, got {text:?}"))?;
453    let low = low
454        .trim()
455        .parse::<f64>()
456        .map_err(|_| err!(BadAttribute, "bounds low {low:?} is not a number"))?;
457    let high = high
458        .trim()
459        .parse::<f64>()
460        .map_err(|_| err!(BadAttribute, "bounds high {high:?} is not a number"))?;
461    if !(low.is_finite() && high.is_finite()) {
462        return Err(err!(BadAttribute, "bounds must be finite, got {text:?}"));
463    }
464    if low >= high {
465        return Err(err!(BadAttribute, "bounds low must be below high, got {text:?}"));
466    }
467    Ok(Bounds { low, high })
468}
469
470/// The unit an image's resolution is measured in.
471#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
472pub enum ResolutionUnit {
473    /// Pixels per inch, and the spec's default when no `unit` is given.
474    #[default]
475    Inch,
476    /// Pixels per centimetre.
477    Centimetre,
478}
479
480impl ResolutionUnit {
481    pub fn parse(name: &str) -> Option<Self> {
482        Some(match name {
483            "inch" => ResolutionUnit::Inch,
484            "cm" => ResolutionUnit::Centimetre,
485            _ => return None,
486        })
487    }
488
489    pub fn name(self) -> &'static str {
490        match self {
491            ResolutionUnit::Inch => "inch",
492            ResolutionUnit::Centimetre => "cm",
493        }
494    }
495}
496
497/// A `<Resolution>` element: how many pixels there are per unit of length.
498#[derive(Clone, Copy, PartialEq, Debug)]
499pub struct Resolution {
500    pub horizontal: f64,
501    pub vertical: f64,
502    pub unit: ResolutionUnit,
503}
504
505impl Resolution {
506    /// Parse a `<Resolution>` element.
507    pub fn parse(element: &Element) -> Result<Self> {
508        if element.name != "Resolution" {
509            return Err(err!(InvalidArgument, "expected <Resolution>, got <{}>", element.name));
510        }
511        let number = |name: &str| -> Result<f64> {
512            let text =
513                element.attr(name).ok_or_else(|| err!(BadHeader, "<Resolution> has no {name}"))?;
514            let value = text
515                .trim()
516                .parse::<f64>()
517                .map_err(|_| err!(BadAttribute, "<Resolution> {name}={text:?} is not a number"))?;
518            if !value.is_finite() || value <= 0.0 {
519                return Err(err!(
520                    BadAttribute,
521                    "<Resolution> {name} must be positive, got {value}"
522                ));
523            }
524            Ok(value)
525        };
526
527        let unit = match element.attr("unit") {
528            None => ResolutionUnit::default(),
529            Some(name) => ResolutionUnit::parse(name)
530                .ok_or_else(|| err!(Unsupported, "unknown resolution unit {name:?}"))?,
531        };
532        Ok(Resolution { horizontal: number("horizontal")?, vertical: number("vertical")?, unit })
533    }
534
535    /// The resolution in pixels per inch, whatever unit it was written in.
536    pub fn per_inch(&self) -> (f64, f64) {
537        match self.unit {
538            ResolutionUnit::Inch => (self.horizontal, self.vertical),
539            ResolutionUnit::Centimetre => (self.horizontal * 2.54, self.vertical * 2.54),
540        }
541    }
542}
543
544/// Parse an `offset` attribute: a pedestal, which cannot be negative.
545fn parse_offset(text: &str) -> Result<f64> {
546    let value = text
547        .trim()
548        .parse::<f64>()
549        .map_err(|_| err!(BadAttribute, "<Image> offset={text:?} is not a number"))?;
550    if !value.is_finite() || value < 0.0 {
551        return Err(err!(BadAttribute, "<Image> offset must be zero or positive, got {value}"));
552    }
553    Ok(value)
554}
555
556/// Split a colon-separated list of `n` floating point numbers.
557fn colon_numbers<const N: usize>(element: &str, name: &str, text: &str) -> Result<[f64; N]> {
558    let mut out = [0.0; N];
559    let mut parts = text.split(':');
560    for slot in out.iter_mut() {
561        let part = parts
562            .next()
563            .ok_or_else(|| err!(BadAttribute, "<{element}> {name}={text:?} needs {N} values"))?;
564        *slot = part.trim().parse::<f64>().map_err(|_| {
565            err!(BadAttribute, "<{element}> {name}={text:?} has a non-numeric component")
566        })?;
567        if !slot.is_finite() {
568            return Err(err!(BadAttribute, "<{element}> {name}={text:?} is not finite"));
569        }
570    }
571    if parts.next().is_some() {
572        return Err(err!(BadAttribute, "<{element}> {name}={text:?} has more than {N} values"));
573    }
574    Ok(out)
575}
576
577/// The transfer curve of an RGB working space.
578#[derive(Clone, Copy, PartialEq, Debug)]
579pub enum Gamma {
580    /// A fixed exponent, always greater than zero.
581    Exponent(f64),
582    /// The sRGB piecewise transfer function, which is not a pure exponent.
583    Srgb,
584}
585
586/// An `<RGBWorkingSpace>` element: the colour space an image's RGB values
587/// are expressed in.
588///
589/// Every triple is in red, green, blue order. Absent, the spec's default is
590/// sRGB, which is what [`RgbWorkingSpace::srgb`] returns -- so a caller can
591/// treat "no element" and "sRGB" alike without special-casing either.
592#[derive(Clone, PartialEq, Debug)]
593pub struct RgbWorkingSpace {
594    pub gamma: Gamma,
595    /// Chromaticity x of the three primaries.
596    pub x: [f64; 3],
597    /// Chromaticity y of the three primaries.
598    pub y: [f64; 3],
599    /// Luminance coefficients of the three primaries.
600    pub luminance: [f64; 3],
601    pub name: Option<String>,
602}
603
604/// The CIE XYZ tristimulus values of the D50 reference white.
605///
606/// Revision 1: "all RGB working space parameters shall be relative to the
607/// standard D50 reference white", citing ASTM E308-01. These are that
608/// standard's values, and they are what reproduces the specification's own
609/// sRGB example to every digit it prints.
610pub const D50_WHITE: [f64; 3] = [0.96422, 1.0, 0.82521];
611
612impl RgbWorkingSpace {
613    /// The luminance coefficients implied by a set of primary chromaticities.
614    ///
615    /// Revision 1 makes these no longer free parameters: they follow from the
616    /// chromaticities and the reference white, "through the condition that
617    /// the linear RGB white point is transformed to the reference white".
618    /// Each primary contributes a column of CIE XYZ values at unit luminance,
619    /// and the coefficients are the scale factors that carry those columns
620    /// onto the white point -- the solution of `M s = w`, where `s` is what
621    /// comes back here because every column has `Y = 1`.
622    ///
623    /// `None` when the system is singular, which Revision 1 says "does not
624    /// define a valid RGB working space" -- three primaries that are collinear
625    /// in the chromaticity diagram enclose no gamut at all.
626    pub fn derive_luminance(x: [f64; 3], y: [f64; 3]) -> Option<[f64; 3]> {
627        // Column i is the primary's XYZ at Y = 1.
628        let mut m = [[0.0f64; 3]; 3];
629        for i in 0..3 {
630            if y[i] == 0.0 {
631                return None;
632            }
633            m[0][i] = x[i] / y[i];
634            m[1][i] = 1.0;
635            m[2][i] = (1.0 - x[i] - y[i]) / y[i];
636        }
637
638        let det = |m: &[[f64; 3]; 3]| -> f64 {
639            m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
640                - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
641                + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
642        };
643
644        let base = det(&m);
645        if !base.is_finite() || base.abs() < 1e-12 {
646            return None;
647        }
648
649        // Cramer's rule: replace each column with the white point in turn.
650        let mut out = [0.0f64; 3];
651        for (k, slot) in out.iter_mut().enumerate() {
652            let mut replaced = m;
653            for (row, w) in replaced.iter_mut().zip(D50_WHITE) {
654                row[k] = w;
655            }
656            *slot = det(&replaced) / base;
657        }
658        out.iter().all(|v| v.is_finite()).then_some(out)
659    }
660
661    /// Whether the serialized luminance coefficients match the ones its
662    /// chromaticities imply.
663    ///
664    /// Revision 1 says a decoder *may* verify this, not that it must, so this
665    /// is offered rather than enforced: a file whose `Y` is slightly off is
666    /// still readable, and refusing it would lose an image over a rounding
667    /// difference in somebody else's encoder. The tolerance is loose enough
668    /// for values written to six decimal places, which is what the
669    /// specification's own examples use.
670    pub fn luminance_is_consistent(&self) -> bool {
671        match Self::derive_luminance(self.x, self.y) {
672            None => false,
673            Some(derived) => derived.iter().zip(self.luminance).all(|(a, b)| (a - b).abs() <= 1e-5),
674        }
675    }
676
677    /// An RGB working space from its gamma and primaries.
678    ///
679    /// The luminance coefficients are not a parameter: Revision 1 derives
680    /// them from the chromaticities and the D50 reference white, so this
681    /// computes them rather than asking for them. `None` for primaries that
682    /// do not define a valid space.
683    pub fn new(gamma: Gamma, x: [f64; 3], y: [f64; 3], name: Option<String>) -> Option<Self> {
684        Some(RgbWorkingSpace { gamma, x, y, luminance: Self::derive_luminance(x, y)?, name })
685    }
686
687    /// The sRGB space, which applies when an image declares none.
688    pub fn srgb() -> Self {
689        // The chromaticities are the specification's; the luminance
690        // coefficients are derived from them rather than copied, so this
691        // constant satisfies the derivation Revision 1 requires by
692        // construction and cannot drift from it. They agree with the printed
693        // 0.222491:0.716888:0.060621 to every digit the specification gives.
694        Self::new(
695            Gamma::Srgb,
696            [0.648431, 0.321152, 0.155886],
697            [0.330856, 0.597871, 0.066044],
698            Some("sRGB IEC61966-2.1".into()),
699        )
700        .expect("the sRGB primaries define a valid working space")
701    }
702
703    /// Parse an `<RGBWorkingSpace>` element.
704    pub fn parse(element: &Element) -> Result<Self> {
705        if element.name != "RGBWorkingSpace" {
706            return Err(err!(
707                InvalidArgument,
708                "expected <RGBWorkingSpace>, got <{}>",
709                element.name
710            ));
711        }
712        let triple = |name: &str| -> Result<[f64; 3]> {
713            let text = element
714                .attr(name)
715                .ok_or_else(|| err!(BadHeader, "<RGBWorkingSpace> has no {name}"))?;
716            colon_numbers::<3>("RGBWorkingSpace", name, text)
717        };
718
719        let text = element
720            .attr("gamma")
721            .ok_or_else(|| err!(BadHeader, "<RGBWorkingSpace> has no gamma"))?;
722        let gamma = if text.trim().eq_ignore_ascii_case("sRGB") {
723            Gamma::Srgb
724        } else {
725            let exponent = text
726                .trim()
727                .parse::<f64>()
728                .map_err(|_| err!(BadAttribute, "gamma={text:?} is neither sRGB nor a number"))?;
729            if !exponent.is_finite() || exponent <= 0.0 {
730                return Err(err!(BadAttribute, "gamma must be positive, got {exponent}"));
731            }
732            Gamma::Exponent(exponent)
733        };
734
735        Ok(RgbWorkingSpace {
736            gamma,
737            x: triple("x")?,
738            y: triple("y")?,
739            luminance: triple("Y")?,
740            name: element.attr("name").map(str::to_owned),
741        })
742    }
743}
744
745/// A `<DisplayFunction>` element: a screen transfer function, which changes
746/// how an image is *shown* without changing the data.
747///
748/// Each parameter has four components, for the red (or grey), green, blue and
749/// lightness channels in that order. Absent, the identity function applies,
750/// which is what [`DisplayFunction::identity`] returns.
751#[derive(Clone, PartialEq, Debug)]
752pub struct DisplayFunction {
753    /// Midtones balance.
754    pub midtones: [f64; 4],
755    /// Shadows clipping point.
756    pub shadows: [f64; 4],
757    /// Highlights clipping point.
758    pub highlights: [f64; 4],
759    /// Shadows dynamic range expansion.
760    pub low_range: [f64; 4],
761    /// Highlights dynamic range expansion.
762    pub high_range: [f64; 4],
763    pub name: Option<String>,
764}
765
766impl DisplayFunction {
767    /// The identity function, which applies when an image declares none.
768    pub fn identity() -> Self {
769        DisplayFunction {
770            midtones: [0.5; 4],
771            shadows: [0.0; 4],
772            highlights: [1.0; 4],
773            low_range: [0.0; 4],
774            high_range: [1.0; 4],
775            name: None,
776        }
777    }
778
779    /// Whether this is the identity, and so can be skipped when displaying.
780    pub fn is_identity(&self) -> bool {
781        *self == DisplayFunction { name: self.name.clone(), ..DisplayFunction::identity() }
782    }
783
784    /// Parse a `<DisplayFunction>` element.
785    pub fn parse(element: &Element) -> Result<Self> {
786        if element.name != "DisplayFunction" {
787            return Err(err!(
788                InvalidArgument,
789                "expected <DisplayFunction>, got <{}>",
790                element.name
791            ));
792        }
793        let quad = |name: &str| -> Result<[f64; 4]> {
794            let text = element
795                .attr(name)
796                .ok_or_else(|| err!(BadHeader, "<DisplayFunction> has no {name}"))?;
797            colon_numbers::<4>("DisplayFunction", name, text)
798        };
799        Ok(DisplayFunction {
800            midtones: quad("m")?,
801            shadows: quad("s")?,
802            highlights: quad("h")?,
803            low_range: quad("l")?,
804            high_range: quad("r")?,
805            name: element.attr("name").map(str::to_owned),
806        })
807    }
808}
809
810/// One element of a colour filter array pattern.
811#[derive(Clone, Copy, PartialEq, Eq, Debug)]
812pub enum CfaElement {
813    /// `0`: a nonexistent or undefined element.
814    Undefined,
815    Red,
816    Green,
817    Blue,
818    /// White or panchromatic.
819    White,
820    Cyan,
821    Magenta,
822    Yellow,
823}
824
825impl CfaElement {
826    fn parse(c: char) -> Option<Self> {
827        Some(match c {
828            '0' => CfaElement::Undefined,
829            'R' => CfaElement::Red,
830            'G' => CfaElement::Green,
831            'B' => CfaElement::Blue,
832            'W' => CfaElement::White,
833            'C' => CfaElement::Cyan,
834            'M' => CfaElement::Magenta,
835            'Y' => CfaElement::Yellow,
836            _ => return None,
837        })
838    }
839
840    /// The character the specification writes this element as.
841    pub fn as_char(self) -> char {
842        match self {
843            CfaElement::Undefined => '0',
844            CfaElement::Red => 'R',
845            CfaElement::Green => 'G',
846            CfaElement::Blue => 'B',
847            CfaElement::White => 'W',
848            CfaElement::Cyan => 'C',
849            CfaElement::Magenta => 'M',
850            CfaElement::Yellow => 'Y',
851        }
852    }
853}
854
855/// A `<ColorFilterArray>`: the mosaic pattern a sensor captured through.
856///
857/// A Bayer filter is the familiar case, but the format admits any rectangular
858/// pattern over eight element kinds. The pattern is ordered as it lies on the
859/// image, left to right then top to bottom, so `pattern[y * width + x]` is the
860/// filter over pixel `(x, y)` modulo the matrix size.
861#[derive(Clone, PartialEq, Eq, Debug)]
862pub struct ColorFilterArray {
863    pub pattern: Vec<CfaElement>,
864    pub width: u64,
865    pub height: u64,
866    /// An optional human-readable name, e.g. "RGGB".
867    pub name: Option<String>,
868}
869
870impl ColorFilterArray {
871    /// Parse a `<ColorFilterArray>` element.
872    pub fn parse(element: &Element) -> Result<Self> {
873        if element.name != "ColorFilterArray" {
874            return Err(err!(
875                InvalidArgument,
876                "expected <ColorFilterArray>, got <{}>",
877                element.name
878            ));
879        }
880
881        let text = element
882            .attr("pattern")
883            .ok_or_else(|| err!(BadHeader, "<ColorFilterArray> has no pattern"))?;
884        let pattern = text
885            .trim()
886            .chars()
887            .map(|c| {
888                CfaElement::parse(c)
889                    .ok_or_else(|| err!(BadAttribute, "{c:?} is not a CFA pattern element"))
890            })
891            .collect::<Result<Vec<_>>>()?;
892
893        let dimension = |name: &str| -> Result<u64> {
894            let text = element
895                .attr(name)
896                .ok_or_else(|| err!(BadHeader, "<ColorFilterArray> has no {name}"))?;
897            let value = text.trim().parse::<u64>().map_err(|_| {
898                err!(BadAttribute, "<ColorFilterArray> {name}={text:?} is not an integer")
899            })?;
900            if value == 0 {
901                return Err(err!(BadAttribute, "<ColorFilterArray> {name} must be above zero"));
902            }
903            Ok(value)
904        };
905        let width = dimension("width")?;
906        let height = dimension("height")?;
907
908        // The pattern length is the matrix, so a mismatch means the two
909        // disagree about the sensor -- and a decoder that trusted the
910        // dimensions would demosaic with a pattern shifted by however much.
911        let expected = width
912            .checked_mul(height)
913            .ok_or_else(|| err!(BadAttribute, "<ColorFilterArray> dimensions overflow"))?;
914        if pattern.len() as u64 != expected {
915            return Err(err!(
916                BadAttribute,
917                "<ColorFilterArray> is {width}x{height} but its pattern has {} elements",
918                pattern.len()
919            ));
920        }
921
922        Ok(ColorFilterArray {
923            pattern,
924            width,
925            height,
926            name: element.attr("name").map(str::to_owned),
927        })
928    }
929
930    /// The filter over pixel `(x, y)`, which repeats across the image.
931    pub fn element_at(&self, x: u64, y: u64) -> CfaElement {
932        let index = (y % self.height) * self.width + (x % self.width);
933        self.pattern[index as usize]
934    }
935
936    /// The pattern as the specification writes it.
937    pub fn pattern_string(&self) -> String {
938        self.pattern.iter().map(|e| e.as_char()).collect()
939    }
940}
941
942/// A `<Thumbnail>`: a small preview, which is an image in its own right.
943///
944/// Parsed with the same code as an `<Image>`, because it *is* one -- same
945/// geometry, sample format, colour space and data block. Only the element
946/// name and its role differ.
947pub fn parse_thumbnail(element: &Element) -> Result<Image> {
948    if element.name != "Thumbnail" {
949        return Err(err!(InvalidArgument, "expected <Thumbnail>, got <{}>", element.name));
950    }
951    // `Image::parse` checks the element name, so it is parsed from a copy
952    // renamed to match rather than by duplicating every attribute rule.
953    let mut as_image = element.clone();
954    as_image.name = "Image".to_string();
955    Image::parse(&as_image)
956}
957
958#[cfg(test)]
959mod tests {
960    /// The specification's own sRGB example is the reference: if the
961    /// derivation reproduces the Y it prints, the formula and the reference
962    /// white are both right.
963    #[test]
964    fn the_derivation_reproduces_the_specifications_srgb_example() {
965        let derived = RgbWorkingSpace::derive_luminance(
966            [0.648431, 0.321152, 0.155886],
967            [0.330856, 0.597871, 0.066044],
968        )
969        .expect("sRGB primaries are not degenerate");
970        for (got, want) in derived.iter().zip([0.222491, 0.716888, 0.060621]) {
971            assert!(
972                (got - want).abs() < 5e-7,
973                "derived {derived:?}, spec says 0.222491:0.716888:0.060621"
974            );
975        }
976    }
977
978    /// The constant the crate hands out for "no RGBWorkingSpace declared"
979    /// must itself satisfy the derivation Revision 1 now requires.
980    #[test]
981    fn the_built_in_srgb_space_is_self_consistent() {
982        assert!(RgbWorkingSpace::srgb().luminance_is_consistent());
983    }
984
985    /// Collinear primaries enclose no gamut, and Revision 1 says such a set
986    /// "does not define a valid RGB working space".
987    #[test]
988    fn degenerate_primaries_have_no_luminance_coefficients() {
989        assert!(RgbWorkingSpace::derive_luminance([0.3, 0.3, 0.3], [0.3, 0.3, 0.3]).is_none());
990        assert!(RgbWorkingSpace::derive_luminance([0.3, 0.4, 0.5], [0.0, 0.4, 0.5]).is_none());
991    }
992
993    /// Coefficients that do not follow from the chromaticities are reported
994    /// as inconsistent -- which decoders *may* check, so it is offered rather
995    /// than enforced.
996    #[test]
997    fn inconsistent_luminance_is_detected() {
998        let mut space = RgbWorkingSpace::srgb();
999        space.luminance = [0.3, 0.4, 0.3];
1000        assert!(!space.luminance_is_consistent());
1001    }
1002
1003    use super::*;
1004    use crate::header;
1005
1006    fn image_of(attrs: &str) -> Result<Image> {
1007        let xml = format!(r#"<xisf version="1.0"><Image {attrs}/></xisf>"#);
1008        let parsed = header::parse(&xml)?;
1009        Image::parse(parsed.images()[0])
1010    }
1011
1012    #[test]
1013    fn parses_a_typical_image() {
1014        let image =
1015            image_of(r#"geometry="256:256:3" sampleFormat="Float32" colorSpace="RGB""#).unwrap();
1016        assert_eq!(image.dimensions, vec![256, 256]);
1017        assert_eq!(image.channels, 3);
1018        assert_eq!(image.sample_format, SampleFormat::Float32);
1019        assert_eq!(image.color_space, ColorSpace::Rgb);
1020        assert_eq!(image.data_size(), Some(256 * 256 * 3 * 4));
1021        assert!(image.channels_suffice());
1022    }
1023
1024    #[test]
1025    fn omitted_attributes_take_the_specs_defaults() {
1026        let image = image_of(r#"geometry="4:4:1" sampleFormat="UInt8""#).unwrap();
1027        assert_eq!(image.color_space, ColorSpace::Gray);
1028        assert_eq!(image.pixel_storage, PixelStorage::Planar);
1029        assert_eq!(image.bounds, None);
1030    }
1031
1032    #[test]
1033    fn more_than_two_dimensions_are_allowed() {
1034        let image = image_of(r#"geometry="8:8:8:2" sampleFormat="UInt16""#).unwrap();
1035        assert_eq!(image.dimensions, vec![8, 8, 8]);
1036        assert_eq!(image.channels, 2);
1037        assert_eq!(image.data_size(), Some(8 * 8 * 8 * 2 * 2));
1038    }
1039
1040    #[test]
1041    fn bounds_parse_and_are_ordered() {
1042        let image = image_of(r#"geometry="2:2:1" sampleFormat="Float32" bounds="0:1""#).unwrap();
1043        assert_eq!(image.bounds, Some(Bounds { low: 0.0, high: 1.0 }));
1044
1045        for bad in ["1:0", "0:0", "nope", "0", "0:inf"] {
1046            let attrs = format!(r#"geometry="2:2:1" sampleFormat="Float32" bounds="{bad}""#);
1047            assert!(image_of(&attrs).is_err(), "bounds={bad:?} should be refused");
1048        }
1049    }
1050
1051    /// Zero dimensions and unknown enum values are refused rather than
1052    /// defaulted, because both would silently misread the pixel data.
1053    #[test]
1054    fn resolution_defaults_to_pixels_per_inch() {
1055        let xml = r#"<xisf version="1.0"><Resolution horizontal="120" vertical="96"/></xisf>"#;
1056        let header = header::parse(xml).unwrap();
1057        let r = Resolution::parse(&header.root.children[0]).unwrap();
1058        assert_eq!(r.unit, ResolutionUnit::Inch);
1059        assert_eq!(r.per_inch(), (120.0, 96.0));
1060    }
1061
1062    #[test]
1063    fn centimetre_resolutions_convert() {
1064        let xml =
1065            r#"<xisf version="1.0"><Resolution horizontal="100" vertical="100" unit="cm"/></xisf>"#;
1066        let header = header::parse(xml).unwrap();
1067        let r = Resolution::parse(&header.root.children[0]).unwrap();
1068        assert_eq!(r.unit, ResolutionUnit::Centimetre);
1069        assert_eq!(r.per_inch(), (254.0, 254.0));
1070    }
1071
1072    #[test]
1073    fn a_nonsensical_resolution_is_refused() {
1074        for attrs in [
1075            r#"horizontal="0" vertical="1""#,
1076            r#"horizontal="-5" vertical="1""#,
1077            r#"horizontal="1""#,
1078            r#"horizontal="x" vertical="1""#,
1079            r#"horizontal="1" vertical="1" unit="furlong""#,
1080        ] {
1081            let xml = format!(r#"<xisf version="1.0"><Resolution {attrs}/></xisf>"#);
1082            let header = header::parse(&xml).unwrap();
1083            assert!(
1084                Resolution::parse(&header.root.children[0]).is_err(),
1085                "{attrs} should have been refused"
1086            );
1087        }
1088    }
1089
1090    /// A thumbnail is an image, and is parsed by the same rules rather than a
1091    /// second implementation of them.
1092    #[test]
1093    fn a_thumbnail_parses_as_an_image() {
1094        let xml = r#"<xisf version="1.0"><Thumbnail geometry="400:300:3" sampleFormat="UInt8"
1095                     colorSpace="RGB" location="attachment:8192:360000"/></xisf>"#;
1096        let header = header::parse(xml).unwrap();
1097        let thumbnail = parse_thumbnail(&header.root.children[0]).unwrap();
1098        assert_eq!(thumbnail.dimensions, vec![400, 300]);
1099        assert_eq!(thumbnail.channels, 3);
1100        assert_eq!(thumbnail.sample_format, SampleFormat::UInt8);
1101        assert_eq!(thumbnail.data_size(), Some(400 * 300 * 3));
1102    }
1103
1104    fn cfa_of(attrs: &str) -> Result<ColorFilterArray> {
1105        let xml = format!(r#"<xisf version="1.0"><ColorFilterArray {attrs}/></xisf>"#);
1106        let header = header::parse(&xml)?;
1107        ColorFilterArray::parse(&header.root.children[0])
1108    }
1109
1110    #[test]
1111    fn a_bayer_pattern_parses_and_repeats() {
1112        let cfa = cfa_of(r#"pattern="RGGB" width="2" height="2" name="RGGB""#).unwrap();
1113        assert_eq!(cfa.pattern_string(), "RGGB");
1114        assert_eq!(cfa.name.as_deref(), Some("RGGB"));
1115
1116        // Ordered left to right, then top to bottom.
1117        assert_eq!(cfa.element_at(0, 0), CfaElement::Red);
1118        assert_eq!(cfa.element_at(1, 0), CfaElement::Green);
1119        assert_eq!(cfa.element_at(0, 1), CfaElement::Green);
1120        assert_eq!(cfa.element_at(1, 1), CfaElement::Blue);
1121
1122        // And it tiles across the sensor.
1123        assert_eq!(cfa.element_at(2, 2), CfaElement::Red);
1124        assert_eq!(cfa.element_at(101, 100), CfaElement::Green);
1125    }
1126
1127    #[test]
1128    fn every_pattern_element_the_spec_names_is_understood() {
1129        let cfa = cfa_of(r#"pattern="0RGBWCMY" width="8" height="1""#).unwrap();
1130        assert_eq!(cfa.pattern[0], CfaElement::Undefined);
1131        assert_eq!(cfa.pattern[4], CfaElement::White);
1132        assert_eq!(cfa.pattern[7], CfaElement::Yellow);
1133        assert_eq!(cfa.pattern_string(), "0RGBWCMY");
1134    }
1135
1136    /// A pattern that does not fill its declared matrix means the two
1137    /// disagree about the sensor, and demosaicing on the dimensions alone
1138    /// would use a pattern shifted by however much.
1139    #[test]
1140    fn a_pattern_that_does_not_match_its_dimensions_is_refused() {
1141        assert!(cfa_of(r#"pattern="RGGB" width="3" height="2""#).is_err());
1142        assert!(cfa_of(r#"pattern="RGG" width="2" height="2""#).is_err());
1143        assert!(cfa_of(r#"pattern="RGGB" width="0" height="2""#).is_err());
1144        assert!(cfa_of(r#"pattern="RGXB" width="2" height="2""#).is_err(), "X is not an element");
1145        assert!(cfa_of(r#"width="2" height="2""#).is_err());
1146        assert!(cfa_of(r#"pattern="RGGB" height="2""#).is_err());
1147    }
1148
1149    #[test]
1150    fn nonsense_geometry_and_unknown_values_are_refused() {
1151        for attrs in [
1152            r#"geometry="0:0:1" sampleFormat="UInt8""#,
1153            r#"geometry="10:0:1" sampleFormat="UInt8""#,
1154            r#"geometry="10" sampleFormat="UInt8""#,
1155            r#"geometry="10:10:0" sampleFormat="UInt8""#,
1156            r#"geometry="a:b:c" sampleFormat="UInt8""#,
1157            r#"geometry="4:4:1" sampleFormat="Float16""#,
1158            r#"geometry="4:4:1" sampleFormat="UInt8" colorSpace="CMYK""#,
1159            r#"geometry="4:4:1" sampleFormat="UInt8" pixelStorage="Sideways""#,
1160            r#"sampleFormat="UInt8""#,
1161            r#"geometry="4:4:1""#,
1162        ] {
1163            assert!(image_of(attrs).is_err(), "{attrs} should have been refused");
1164        }
1165    }
1166
1167    #[test]
1168    fn an_rgb_image_needs_three_channels() {
1169        let short = image_of(r#"geometry="4:4:1" sampleFormat="UInt8" colorSpace="RGB""#).unwrap();
1170        assert!(!short.channels_suffice());
1171        // A fourth channel is an alpha channel, which is allowed.
1172        let alpha = image_of(r#"geometry="4:4:4" sampleFormat="UInt8" colorSpace="RGB""#).unwrap();
1173        assert!(alpha.channels_suffice());
1174    }
1175
1176    #[test]
1177    fn an_absurd_geometry_does_not_overflow() {
1178        let image =
1179            image_of(&format!(r#"geometry="{0}:{0}:{0}" sampleFormat="Float64""#, u64::MAX))
1180                .unwrap();
1181        assert_eq!(image.sample_count(), None, "should report overflow, not wrap");
1182        assert_eq!(image.data_size(), None);
1183    }
1184}