1use crate::err;
4use crate::error::Result;
5use crate::header::Element;
6
7#[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 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 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 pub fn requires_bounds(self) -> bool {
81 matches!(self, SampleFormat::Float32 | SampleFormat::Float64)
82 }
83
84 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 Some(Bounds { low: 0.0, high: 2f64.powi(bits as i32) - 1.0 })
103 }
104}
105
106#[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 pub fn nominal_channels(self) -> u64 {
135 match self {
136 ColorSpace::Gray => 1,
137 ColorSpace::Rgb | ColorSpace::CieLab => 3,
138 }
139 }
140}
141
142#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
144pub enum PixelStorage {
145 #[default]
147 Planar,
148 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#[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 SlopeMap,
195 WeightMap,
196 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 pub fn is_standard(&self) -> bool {
245 !matches!(self, ImageType::Other(_))
246 }
247}
248
249#[derive(Clone, Copy, PartialEq, Debug)]
251pub struct Bounds {
252 pub low: f64,
253 pub high: f64,
254}
255
256#[derive(Clone, PartialEq, Debug)]
258pub struct Image {
259 pub dimensions: Vec<u64>,
264 pub channels: u64,
265 pub sample_format: SampleFormat,
266 pub color_space: ColorSpace,
267 pub pixel_storage: PixelStorage,
268 pub bounds: Option<Bounds>,
270 pub id: Option<String>,
271 pub uuid: Option<String>,
272 pub image_type: Option<ImageType>,
273 pub offset: Option<f64>,
279 pub orientation: Option<Orientation>,
286}
287
288#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
293pub struct Orientation {
294 pub rotation: i16,
296 pub flip_horizontal: bool,
297}
298
299impl Orientation {
300 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 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 pub fn is_identity(self) -> bool {
333 self.rotation == 0 && !self.flip_horizontal
334 }
335}
336
337impl Image {
338 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 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 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 pub fn data_size(&self) -> Option<u64> {
405 self.sample_count()?.checked_mul(self.sample_format.size() as u64)
406 }
407
408 pub fn channels_suffice(&self) -> bool {
413 self.channels >= self.color_space.nominal_channels()
414 }
415}
416
417fn 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
448fn 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#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
472pub enum ResolutionUnit {
473 #[default]
475 Inch,
476 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#[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 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 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
544fn 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
556fn 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#[derive(Clone, Copy, PartialEq, Debug)]
579pub enum Gamma {
580 Exponent(f64),
582 Srgb,
584}
585
586#[derive(Clone, PartialEq, Debug)]
593pub struct RgbWorkingSpace {
594 pub gamma: Gamma,
595 pub x: [f64; 3],
597 pub y: [f64; 3],
599 pub luminance: [f64; 3],
601 pub name: Option<String>,
602}
603
604pub const D50_WHITE: [f64; 3] = [0.96422, 1.0, 0.82521];
611
612impl RgbWorkingSpace {
613 pub fn derive_luminance(x: [f64; 3], y: [f64; 3]) -> Option<[f64; 3]> {
627 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 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 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 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 pub fn srgb() -> Self {
689 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 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#[derive(Clone, PartialEq, Debug)]
752pub struct DisplayFunction {
753 pub midtones: [f64; 4],
755 pub shadows: [f64; 4],
757 pub highlights: [f64; 4],
759 pub low_range: [f64; 4],
761 pub high_range: [f64; 4],
763 pub name: Option<String>,
764}
765
766impl DisplayFunction {
767 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 pub fn is_identity(&self) -> bool {
781 *self == DisplayFunction { name: self.name.clone(), ..DisplayFunction::identity() }
782 }
783
784 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#[derive(Clone, Copy, PartialEq, Eq, Debug)]
812pub enum CfaElement {
813 Undefined,
815 Red,
816 Green,
817 Blue,
818 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 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#[derive(Clone, PartialEq, Eq, Debug)]
862pub struct ColorFilterArray {
863 pub pattern: Vec<CfaElement>,
864 pub width: u64,
865 pub height: u64,
866 pub name: Option<String>,
868}
869
870impl ColorFilterArray {
871 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 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 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 pub fn pattern_string(&self) -> String {
938 self.pattern.iter().map(|e| e.as_char()).collect()
939 }
940}
941
942pub fn parse_thumbnail(element: &Element) -> Result<Image> {
948 if element.name != "Thumbnail" {
949 return Err(err!(InvalidArgument, "expected <Thumbnail>, got <{}>", element.name));
950 }
951 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 #[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 #[test]
981 fn the_built_in_srgb_space_is_self_consistent() {
982 assert!(RgbWorkingSpace::srgb().luminance_is_consistent());
983 }
984
985 #[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 #[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 #[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 #[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 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 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 #[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 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}