Skip to main content

openreadout_czi/
lib.rs

1//! Clean-room reader for Zeiss CZI files.
2//!
3//! Layout and vocabulary: `docs/formats/czi.md`. Provenance: `docs/provenance/czi.md`.
4//!
5//! # Example
6//!
7//! Every reader implements [`openreadout_core::FormatReader`]: `descriptor`
8//! says what it reads, `sniff` recognises a file from its first bytes, and `open` returns a
9//! [`openreadout_core::Dataset`] with a header-only `info()` summary and lazy data
10//! access.
11//!
12//! ```
13//! use openreadout_core::FormatReader;
14//! use openreadout_czi::CziReader;
15//!
16//! let format = CziReader.descriptor();
17//! assert_eq!(format.id, openreadout_czi::FORMAT_ID);
18//! println!("{} ({}): .{}", format.name, format.family, format.extensions.join(", ."));
19//! ```
20//!
21//! Reading a file:
22//!
23//! ```no_run
24//! use std::path::Path;
25//!
26//! use openreadout_core::{FormatReader, PlaneIndex};
27//! use openreadout_czi::CziReader;
28//!
29//! let mut dataset = CziReader.open(Path::new("experiment.czi"))?;
30//! let info = dataset.info()?; // headers only: fast even on multi-gigabyte files
31//! for image in &info.images {
32//!     println!(
33//!         "image {}: {} x {} px, {} channel(s), {} plane(s)",
34//!         image.index, image.size_x, image.size_y, image.size_c, image.plane_count
35//!     );
36//! }
37//! // Pixels are read one plane at a time: image 0, channel 0, first Z slice, first time point.
38//! let plane = dataset.read_plane(0, PlaneIndex { c: 0, z: 0, t: 0 })?;
39//! assert_eq!(plane.data.len(), plane.expected_len());
40//! # Ok::<(), openreadout_core::Error>(())
41//! ```
42//!
43//! Applications that accept any instrument file usually register every reader in an
44//! [`openreadout_core::Registry`] and let it detect the format; that is what the
45//! `openreadout` command-line tool does.
46//!
47//! # API stability
48//!
49//! The supported API is what this page documents. The parser modules are public only so that
50//! tests and fuzz targets can reach them: they are hidden from this documentation and may change
51//! in any release.
52#![forbid(unsafe_code)]
53#![warn(missing_docs)]
54
55mod assurance;
56#[doc(hidden)]
57pub mod attach;
58#[doc(hidden)]
59pub mod container;
60mod convert;
61mod dataset;
62#[cfg(feature = "fuzzing")]
63#[doc(hidden)]
64pub mod fuzzing;
65#[doc(hidden)]
66pub mod mask;
67#[doc(hidden)]
68pub mod xml;
69
70use std::path::Path;
71
72use openreadout_core::Result;
73use openreadout_core::model::{DetectConfidence, FormatDescriptor};
74use openreadout_core::reader::{Dataset, Detection, FormatReader};
75use openreadout_core::source::Input;
76
77#[doc(hidden)]
78pub use attach::{EventRecord, parse_event_list, parse_time_stamps};
79#[doc(hidden)]
80pub use container::{
81    ATTACHMENT_DATA_OFFSET, AttachmentEntry, CompressionId, CziFile, DimensionEntry,
82    DirectoryEntry, FileHeader, FilePart, PixelTypeId, SEGMENT_HEADER_LEN, SegmentHeader,
83    SegmentId, SubBlockHeader, master_path, part_path,
84};
85#[doc(hidden)]
86pub use mask::{MASK_CHUNK_GUID, ValidMask, parse_valid_mask};
87#[doc(hidden)]
88pub use xml::{
89    ChannelXml, ExperimentXml, ImageXml, ObjectiveXml, ScalingXml, SceneXml, SubBlockTags,
90    parse_subblock_tags,
91};
92
93/// Format id used on the command line and in JSON.
94pub const FORMAT_ID: &str = "czi";
95/// First 10 bytes of every CZI file (ASCII).
96pub const FILE_MAGIC: &[u8; 10] = b"ZISRAWFILE";
97
98/// The Zeiss CZI format reader.
99#[derive(Debug, Default, Clone, Copy)]
100pub struct CziReader;
101
102impl FormatReader for CziReader {
103    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
104        Some(&assurance::CZI)
105    }
106
107    fn descriptor(&self) -> FormatDescriptor {
108        FormatDescriptor {
109            id: FORMAT_ID.into(),
110            name: "Zeiss CZI".into(),
111            vendor: "Carl Zeiss Microscopy".into(),
112            extensions: vec!["czi".into()],
113            family: "microscopy".into(),
114            can_read: true,
115            can_write: false,
116            confidence: assurance::CZI.confidence,
117            known_gaps: vec![
118                "JPEG (id 1) subblocks decode with jpeg-decoder (8-bit) and our own 12-bit decoder, which differ from libjpeg-turbo by up to a few grey levels on lossy streams (lossless JPEG is bit-exact); 12-bit progressive or chroma-subsampled JPEG is not decoded".into(),
119                "Chunked subblocks (id 7) are validated on synthetic files only (imagecodecs-written; no public file uses id 7); the HiLo split over more than one chunk is refused because libCZI's documentation and imagecodecs read it differently".into(),
120                "JPEG-lossless (id 3) and camera/system raw (id >= 100) subblocks are not decoded (no public sample)".into(),
121                "Multi-file documents: part discovery (`<name> (<k>).czi`) is inferred from synthetic fixtures; no public multi-file CZI was available".into(),
122                "Dimensions H, I, R, V, B that vary are one image per combination of coordinates; validated on H only (SIM phases; Airyscan-era multi-track files where some channels exist at H = 0 only, the others read as 0 and listed in extra.absent_channels); no public file varies along I, R, V or B".into(),
123                "Scenes above 4 GiB are read by region (`--region`), not whole; pyramid levels and regions are read with `--level`/`--region`, and `export` copies the pyramid".into(),
124                "Subblocks stored below their logical size without a pyramid flag (Airyscan fast-scan) are not upsampled".into(),
125                "Complex-valued pixel types are not decoded".into(),
126                "Super-resolved renderings (subblocks stored above their logical size, e.g. PALM) are exposed as their own image at the stored size, pixel size divided by the stored-to-logical ratio; they are not resampled onto the other channels' grid".into(),
127            ],
128        }
129    }
130
131    fn sniff(&self, head: &[u8], _path: &Path) -> Option<Detection> {
132        head.starts_with(FILE_MAGIC).then_some(Detection {
133            format_id: FORMAT_ID,
134            confidence: DetectConfidence::Definite,
135            note: None,
136        })
137    }
138
139    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
140        self.open_input(&Input::local(path))
141    }
142
143    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
144        Ok(Box::new(dataset::CziDataset::open(input)?))
145    }
146
147    fn reads_any_source(&self) -> bool {
148        true
149    }
150}