#![warn(missing_docs)]
extern crate alloc;
use alloc::borrow::Cow;
use std::path::Path;
pub use xisf_core::Reader;
pub use xisf_core::astrometry;
pub use xisf_core::block::{ByteOrder, ChecksumAlgorithm, Codec, Compression, Location};
pub use xisf_core::color;
pub use xisf_core::color::ColorTransform;
pub use xisf_core::error::{Error, ErrorKind, Result};
pub use xisf_core::header::DataRef;
pub use xisf_core::header::{Element, Header};
pub use xisf_core::image::{
Bounds, CfaElement, ColorFilterArray, ColorSpace, DisplayFunction, Gamma, Image, Orientation,
PixelStorage, Resolution, ResolutionUnit, RgbWorkingSpace, SampleFormat,
};
pub use xisf_core::property::{Property, PropertyType, Scalar, ScalarValue, Shape};
pub use xisf_core::reader::ChecksumStatus;
pub use xisf_core::table::{Cell, Field, Structure, Table};
pub use xisf_core::writer::{
BlockOptions, Codec2 as WriteCodec, CompressionRequest, DistributedUnit, FitsKeyword,
PendingImage, PendingThumbnail, Writer,
};
#[derive(Debug)]
pub struct XisfFile {
reader: Reader,
}
impl XisfFile {
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
Ok(Self { reader: Reader::open(path)? })
}
pub fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
Ok(Self { reader: Reader::from_bytes(bytes)? })
}
pub fn images(&self) -> Vec<ImageRef<'_>> {
self.reader
.header()
.images()
.into_iter()
.filter_map(|element| {
Image::parse(element).ok().map(|image| ImageRef { file: self, element, image })
})
.collect()
}
pub fn unavailable_images(&self) -> usize {
self.reader
.header()
.images()
.into_iter()
.filter(|element| Image::parse(element).is_err())
.count()
}
pub fn properties(&self) -> Vec<PropertyRef<'_>> {
self.reader
.header()
.root
.descendants()
.into_iter()
.filter(|e| e.is("Property"))
.filter_map(|element| {
Property::parse(element).ok().map(|property| PropertyRef {
file: self,
element,
property,
})
})
.collect()
}
pub fn tables(&self) -> Vec<Table> {
let header = self.reader.header();
header
.root
.descendants()
.into_iter()
.filter(|e| e.is("Table"))
.filter_map(|element| Table::parse(element, header).ok())
.collect()
}
pub fn table(&self, id: &str) -> Option<Table> {
self.tables().into_iter().find(|t| t.id == id)
}
pub fn property(&self, id: &str) -> Option<PropertyRef<'_>> {
self.properties().into_iter().find(|p| p.id() == id)
}
pub fn metadata(&self) -> Vec<(String, String)> {
self.reader
.header()
.root
.descendants()
.into_iter()
.filter(|e| e.is("Property"))
.filter_map(|e| {
let id = e.attr("id")?.to_string();
let value = e.attr("value").map(str::to_owned).or_else(|| e.data.text.clone())?;
Some((id, value))
})
.collect()
}
pub fn reader(&self) -> &Reader {
&self.reader
}
}
#[derive(Debug)]
pub struct ImageRef<'a> {
file: &'a XisfFile,
element: &'a Element,
image: Image,
}
impl<'a> ImageRef<'a> {
pub fn geometry(&self) -> &[u64] {
&self.image.dimensions
}
pub fn channels(&self) -> u64 {
self.image.channels
}
pub fn sample_format(&self) -> SampleFormat {
self.image.sample_format
}
pub fn color_space(&self) -> ColorSpace {
self.image.color_space
}
pub fn pixel_storage(&self) -> PixelStorage {
self.image.pixel_storage
}
pub fn bounds(&self) -> Option<Bounds> {
self.image.bounds
}
pub fn representable_range(&self) -> Option<Bounds> {
self.image.bounds.or_else(|| self.image.sample_format.default_bounds())
}
pub fn attributes(&self) -> &Image {
&self.image
}
pub fn byte_order(&self) -> ByteOrder {
self.element.data.byte_order
}
pub fn is_compressed(&self) -> bool {
self.element.data.compression.is_some()
}
pub fn bytes(&self) -> Result<Cow<'a, [u8]>> {
self.file.reader.block(&self.element.data)
}
pub fn verify(&self) -> Result<ChecksumStatus> {
self.file.reader.verify(&self.element.data)
}
pub fn fits_keywords(&self) -> Vec<(String, String, String)> {
self.element
.children_named("FITSKeyword")
.map(|k| {
(
k.attr("name").unwrap_or_default().to_string(),
k.attr("value").unwrap_or_default().to_string(),
k.attr("comment").unwrap_or_default().to_string(),
)
})
.collect()
}
pub fn read<T: Sample>(&self) -> Result<Vec<T>> {
if self.image.sample_format != T::FORMAT {
return Err(Error::new(
ErrorKind::InvalidArgument,
format!(
"this image holds {} samples; asked for {}",
self.image.sample_format.name(),
T::FORMAT.name()
),
));
}
let bytes = self.bytes()?;
let expected = self.image.data_size().ok_or_else(|| {
Error::new(ErrorKind::Unsupported, "the image's geometry overflows this platform")
})?;
if bytes.len() as u64 != expected {
return Err(Error::new(
ErrorKind::Truncated,
format!("the image declares {expected} bytes of pixel data, found {}", bytes.len()),
));
}
Ok(T::decode(&bytes, self.byte_order()))
}
pub fn read_planar<T: Sample>(&self) -> Result<Vec<T>> {
let samples = self.read::<T>()?;
if self.image.pixel_storage == PixelStorage::Planar {
return Ok(samples);
}
let channels = self.image.channels as usize;
if channels <= 1 {
return Ok(samples);
}
let pixels = samples.len() / channels;
let mut out = Vec::with_capacity(samples.len());
for c in 0..channels {
out.extend((0..pixels).map(|p| samples[p * channels + c]));
}
out.extend_from_slice(&samples[pixels * channels..]);
Ok(out)
}
pub fn location(&self) -> Option<&Location> {
self.element.data.location.as_ref()
}
pub fn resolution(&self) -> Option<Resolution> {
self.associated("Resolution").into_iter().find_map(|e| Resolution::parse(e).ok())
}
fn associated(&self, name: &'static str) -> Vec<&'a xisf_core::header::Element> {
self.file.reader.header().associated(self.element, name)
}
pub fn icc_profile(&self) -> Option<Result<Cow<'a, [u8]>>> {
let element = *self.associated("ICCProfile").first()?;
Some(self.file.reader.block(&element.data))
}
pub fn color_transform(&self) -> Option<ColorTransform> {
match self.rgb_working_space() {
Some(space) => ColorTransform::new(&space),
None => Some(ColorTransform::srgb()),
}
}
pub fn astrometric_solution(&self) -> Option<Result<astrometry::Solution>> {
match astrometry::read(&self.file.reader, self.element) {
Ok(None) => None,
Ok(Some(solution)) => Some(Ok(solution)),
Err(e) => Some(Err(e)),
}
}
pub fn rgb_working_space(&self) -> Option<RgbWorkingSpace> {
self.associated("RGBWorkingSpace").into_iter().find_map(|e| RgbWorkingSpace::parse(e).ok())
}
pub fn display_function(&self) -> Option<DisplayFunction> {
self.associated("DisplayFunction").into_iter().find_map(|e| DisplayFunction::parse(e).ok())
}
pub fn tables(&self) -> Vec<Table> {
let header = self.file.reader.header();
self.associated("Table").into_iter().filter_map(|e| Table::parse(e, header).ok()).collect()
}
pub fn color_filter_array(&self) -> Option<ColorFilterArray> {
self.associated("ColorFilterArray")
.into_iter()
.find_map(|e| ColorFilterArray::parse(e).ok())
}
pub fn thumbnail(&self) -> Option<ThumbnailRef<'a>> {
let element = *self.associated("Thumbnail").first()?;
let image = xisf_core::image::parse_thumbnail(element).ok()?;
Some(ThumbnailRef { file: self.file, element, image })
}
}
#[derive(Debug)]
pub struct ThumbnailRef<'a> {
file: &'a XisfFile,
element: &'a Element,
image: Image,
}
impl<'a> ThumbnailRef<'a> {
pub fn geometry(&self) -> &[u64] {
&self.image.dimensions
}
pub fn channels(&self) -> u64 {
self.image.channels
}
pub fn sample_format(&self) -> SampleFormat {
self.image.sample_format
}
pub fn color_space(&self) -> ColorSpace {
self.image.color_space
}
pub fn pixel_storage(&self) -> PixelStorage {
self.image.pixel_storage
}
pub fn attributes(&self) -> &Image {
&self.image
}
pub fn bytes(&self) -> Result<Cow<'a, [u8]>> {
self.file.reader.block(&self.element.data)
}
}
#[derive(Debug)]
pub struct PropertyRef<'a> {
file: &'a XisfFile,
element: &'a Element,
property: Property,
}
impl<'a> PropertyRef<'a> {
pub fn id(&self) -> &str {
&self.property.id
}
pub fn kind(&self) -> PropertyType {
self.property.kind
}
pub fn attributes(&self) -> &Property {
&self.property
}
pub fn value(&self) -> Option<ScalarValue> {
self.property.value()
}
pub fn as_str(&self) -> Option<&str> {
match self.property.kind.shape {
Shape::Scalar | Shape::TimePoint => self.property.value.as_deref(),
Shape::String => {
self.property.text.as_deref().or(self.property.value.as_deref())
}
_ => None,
}
}
pub fn bytes(&self) -> Result<Cow<'a, [u8]>> {
if self.element.data.location.is_none() {
return Err(Error::new(
ErrorKind::NotFound,
format!("property {:?} has no data block", self.property.id),
));
}
self.file.reader.block(&self.element.data)
}
pub fn read<T: Sample>(&self) -> Result<Vec<T>> {
let element = self.property.kind.element.ok_or_else(|| {
Error::new(
ErrorKind::InvalidArgument,
format!("property {:?} has no element type to read", self.property.id),
)
})?;
if element.name() != T::FORMAT.name() {
return Err(Error::new(
ErrorKind::InvalidArgument,
format!(
"property {:?} holds {} components; asked for {}",
self.property.id,
element.name(),
T::FORMAT.name()
),
));
}
let expected = self.property.data_size().ok_or_else(|| {
Error::new(
ErrorKind::Unsupported,
format!(
"property {:?} declares a shape this platform cannot hold",
self.property.id
),
)
})?;
let bytes = self.bytes()?;
if bytes.len() as u64 != expected {
return Err(Error::new(
ErrorKind::Truncated,
format!(
"property {:?} declares {expected} bytes but its block holds {}",
self.property.id,
bytes.len()
),
));
}
Ok(T::decode(&bytes, self.element.data.byte_order))
}
}
pub trait Sample: sealed::Sealed + Copy {
const FORMAT: SampleFormat;
#[doc(hidden)]
fn decode(bytes: &[u8], order: ByteOrder) -> Vec<Self>;
}
mod sealed {
pub trait Sealed {}
}
macro_rules! sample {
($ty:ty, $format:ident) => {
impl sealed::Sealed for $ty {}
impl Sample for $ty {
const FORMAT: SampleFormat = SampleFormat::$format;
fn decode(bytes: &[u8], order: ByteOrder) -> Vec<Self> {
let (chunks, _) = bytes.as_chunks::<{ size_of::<$ty>() }>();
match order {
ByteOrder::Big => chunks.iter().map(|c| <$ty>::from_be_bytes(*c)).collect(),
ByteOrder::Little => chunks.iter().map(|c| <$ty>::from_le_bytes(*c)).collect(),
}
}
}
};
}
sample!(u8, UInt8);
sample!(u16, UInt16);
sample!(u32, UInt32);
sample!(u64, UInt64);
sample!(f32, Float32);
sample!(f64, Float64);
#[cfg(test)]
mod tests {
use super::*;
use xisf_core::writer::{PendingImage, Writer};
fn write(image: Image, data: Vec<u8>) -> XisfFile {
let mut writer = Writer::new();
writer
.add_image(PendingImage::new(image, data, BlockOptions::default()))
.expect("add_image");
XisfFile::from_bytes(writer.to_bytes().expect("to_bytes")).expect("read back")
}
fn image(format: SampleFormat, channels: u64) -> Image {
Image {
dimensions: vec![5, 4],
channels,
sample_format: format,
color_space: if channels >= 3 { ColorSpace::Rgb } else { ColorSpace::Gray },
pixel_storage: PixelStorage::Planar,
bounds: format.requires_bounds().then_some(Bounds { low: 0.0, high: 1.0 }),
id: None,
uuid: None,
image_type: None,
offset: None,
orientation: None,
}
}
#[test]
fn reads_samples_of_the_right_type() {
let values: Vec<u16> = (0..20u16).map(|i| i * 1000).collect();
let bytes: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
let file = write(image(SampleFormat::UInt16, 1), bytes);
let read: Vec<u16> = file.images()[0].read().expect("read");
assert_eq!(read, values);
}
#[test]
fn the_wrong_sample_type_is_refused() {
let file = write(image(SampleFormat::Float32, 1), vec![0; 80]);
let err = file.images()[0].read::<u16>().unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidArgument);
assert!(err.message().contains("Float32"), "the message should name both types");
}
#[test]
fn big_endian_blocks_are_byte_swapped() {
let values: Vec<u32> = vec![1, 0x0102_0304, u32::MAX, 42];
let big: Vec<u8> = values.iter().flat_map(|v| v.to_be_bytes()).collect();
let xml = format!(
r#"<xisf version="1.0"><Image geometry="4:1:1" sampleFormat="UInt32" \
byteOrder="big" location="inline:base64">{}</Image></xisf>"#,
base64_encode(&big)
);
let file = XisfFile::from_bytes(monolithic(&xml)).expect("read");
let read: Vec<u32> = file.images()[0].read().expect("read");
assert_eq!(read, values, "a big-endian block must not depend on the host");
assert_eq!(file.images()[0].byte_order(), ByteOrder::Big);
}
#[test]
fn an_absent_byte_order_means_little_endian() {
let values: Vec<u32> = vec![0x0a0b_0c0d, 7];
let little: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
let xml = format!(
r#"<xisf version="1.0"><Image geometry="2:1:1" sampleFormat="UInt32" \
location="inline:base64">{}</Image></xisf>"#,
base64_encode(&little)
);
let file = XisfFile::from_bytes(monolithic(&xml)).expect("read");
assert_eq!(file.images()[0].byte_order(), ByteOrder::Little);
assert_eq!(file.images()[0].read::<u32>().unwrap(), values);
}
#[test]
fn geometry_and_metadata_come_through() {
let file = write(image(SampleFormat::UInt8, 3), vec![0; 60]);
let images = file.images();
assert_eq!(images.len(), 1);
assert_eq!(images[0].geometry(), &[5, 4]);
assert_eq!(images[0].channels(), 3);
assert_eq!(images[0].color_space(), ColorSpace::Rgb);
}
fn monolithic(xml: &str) -> Vec<u8> {
let xml = xml.replace("\\\n", "");
let mut out = Vec::new();
out.extend_from_slice(b"XISF0100");
out.extend_from_slice(&(xml.len() as u32).to_le_bytes());
out.extend_from_slice(&[0; 4]);
out.extend_from_slice(xml.as_bytes());
out
}
fn base64_encode(bytes: &[u8]) -> String {
const TABLE: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::new();
for chunk in bytes.chunks(3) {
let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
let n = u32::from_be_bytes([0, b[0], b[1], b[2]]);
let digits = [n >> 18, (n >> 12) & 63, (n >> 6) & 63, n & 63];
for (i, d) in digits.iter().enumerate() {
if i <= chunk.len() {
out.push(TABLE[*d as usize] as char);
} else {
out.push('=');
}
}
}
out
}
}