Skip to main content

openreadout_lif/
lib.rs

1//! Clean-room reader for the Leica LIF family: LIF, LIFEXT, LOF, XLIF, XLEF, XLCF, XLLF.
2//!
3//! Layout and vocabulary: `docs/formats/lif.md`. Provenance: `docs/provenance/lif.md`.
4//! A LIF file is a UTF-16 XML document followed by raw, uncompressed memory blocks.
5//!
6//! # Example
7//!
8//! Every reader implements [`openreadout_core::FormatReader`]: `descriptor`
9//! says what it reads, `sniff` recognises a file from its first bytes, and `open` returns a
10//! [`openreadout_core::Dataset`] with a header-only `info()` summary and lazy data
11//! access.
12//!
13//! ```
14//! use openreadout_core::FormatReader;
15//! use openreadout_lif::LifReader;
16//!
17//! let format = LifReader.descriptor();
18//! assert_eq!(format.id, openreadout_lif::FORMAT_ID);
19//! println!("{} ({}): .{}", format.name, format.family, format.extensions.join(", ."));
20//! ```
21//!
22//! Reading a file:
23//!
24//! ```no_run
25//! use std::path::Path;
26//!
27//! use openreadout_core::{FormatReader, PlaneIndex};
28//! use openreadout_lif::LifReader;
29//!
30//! let mut dataset = LifReader.open(Path::new("project.lif"))?;
31//! let info = dataset.info()?; // headers only: fast even on multi-gigabyte files
32//! for image in &info.images {
33//!     println!(
34//!         "image {}: {} x {} px, {} channel(s), {} plane(s)",
35//!         image.index, image.size_x, image.size_y, image.size_c, image.plane_count
36//!     );
37//! }
38//! // Pixels are read one plane at a time: image 0, channel 0, first Z slice, first time point.
39//! let plane = dataset.read_plane(0, PlaneIndex { c: 0, z: 0, t: 0 })?;
40//! assert_eq!(plane.data.len(), plane.expected_len());
41//! # Ok::<(), openreadout_core::Error>(())
42//! ```
43//!
44//! Applications that accept any instrument file usually register every reader in an
45//! [`openreadout_core::Registry`] and let it detect the format; that is what the
46//! `openreadout` command-line tool does.
47//!
48//! # API stability
49//!
50//! The supported API is what this page documents. The parser modules are public only so that
51//! tests and fuzz targets can reach them: they are hidden from this documentation and may change
52//! in any release.
53#![forbid(unsafe_code)]
54#![warn(missing_docs)]
55
56mod assurance;
57#[doc(hidden)]
58pub mod container;
59mod dataset;
60#[doc(hidden)]
61pub mod frames;
62#[cfg(feature = "fuzzing")]
63#[doc(hidden)]
64pub mod fuzzing;
65#[doc(hidden)]
66pub mod mosaic;
67mod storage;
68#[doc(hidden)]
69pub mod xlef;
70#[doc(hidden)]
71pub mod xml;
72
73use std::path::Path;
74
75use openreadout_core::model::{DetectConfidence, FormatDescriptor};
76use openreadout_core::reader::{Dataset, Detection, FormatReader, has_extension};
77use openreadout_core::source::{Fs, Input};
78use openreadout_core::{Error, Result};
79
80#[doc(hidden)]
81pub use container::{
82    ContainerHeader, ContainerKind, LOF_TEXT, LifFile, MAGIC, MemoryBlock, TEXT_MARKER,
83};
84#[doc(hidden)]
85pub use mosaic::{MosaicLayout, PlacementMethod, TilePlacement, layout};
86#[doc(hidden)]
87pub use xlef::{FrameRef, XmlContainer, XmlKind};
88#[doc(hidden)]
89pub use xml::{
90    Axis, ChannelDesc, DimensionDesc, FlimInfo, HardwareInfo, ImageNode, TilePosition, TileScan,
91};
92
93/// Format id used on the command line and in JSON.
94pub const FORMAT_ID: &str = "lif";
95
96/// Extensions of the XML-only members of the family.
97const XML_EXTENSIONS: [&str; 4] = ["xlif", "xlef", "xlcf", "xllf"];
98
99/// The Leica LIF format reader.
100#[derive(Debug, Default, Clone, Copy)]
101pub struct LifReader;
102
103impl FormatReader for LifReader {
104    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
105        Some(&assurance::LIF)
106    }
107
108    fn descriptor(&self) -> FormatDescriptor {
109        FormatDescriptor {
110            id: FORMAT_ID.into(),
111            name: "Leica LIF".into(),
112            vendor: "Leica Microsystems".into(),
113            extensions: vec![
114                "lif".into(),
115                "lifext".into(),
116                "lof".into(),
117                "xlif".into(),
118                "xlef".into(),
119                "xlcf".into(),
120                "xllf".into(),
121            ],
122            family: "microscopy".into(),
123            can_read: true,
124            can_write: false,
125            confidence: assurance::LIF.confidence,
126            known_gaps: vec![
127                "FLIM/TCSPC raw photon data (FALCON) is detected and described but not decoded; reading those planes exits 6, and `stats` and `export` without `--image` leave those images out".into(),
128                "XLIF frames stored as single-page TIFF files are read (validated on two LAS X exports); JPEG and PNG frames follow the same rule unvalidated (a note says so); BMP and multi-page OME/Aivia TIFF frames are not read (exit 6)".into(),
129                "LOF, XLEF and XLCF are implemented from liffile's documentation and synthetic test files only; XLLF folder lists and XLIF files with TIFF frames are validated on real LAS X 3.7 exports (two depositors)".into(),
130                "Tile scans are stitched from stage positions without registration or blending; LAS X 'Merged' images may differ where it registered overlapping tiles".into(),
131                "Rotation (DimID 6) and XT/T-slice (DimID 7/8) addressing is validated on synthetic files only".into(),
132                "LIFEXT sidecar images (pyramid previews, histograms) are listed from the .lif but read by opening the .lifext itself".into(),
133                "Version-1 LIF containers (32-bit block lengths) are untested".into(),
134            ],
135        }
136    }
137
138    fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection> {
139        let definite = |note: Option<&str>| {
140            Some(Detection {
141                format_id: FORMAT_ID,
142                confidence: DetectConfidence::Definite,
143                note: note.map(str::to_string),
144            })
145        };
146        if container::looks_like_lif(head) {
147            return definite(None);
148        }
149        if container::looks_like_lifext(head) {
150            return definite(Some("Leica LIFEXT sidecar (images attached to a .lif)"));
151        }
152        if container::looks_like_lof(head) {
153            return definite(Some("Leica LOF (single-object) file"));
154        }
155        if has_extension(path, &XML_EXTENSIONS) && xlef::looks_like_xml_container(head) {
156            return definite(Some(
157                "Leica XML container (XLIF/XLEF/XLCF/XLLF); images are read from the files it references",
158            ));
159        }
160        if has_extension(path, &["lof", "lifext", "xlif", "xlef", "xlcf", "xllf"]) {
161            return Some(Detection {
162                format_id: FORMAT_ID,
163                confidence: DetectConfidence::ExtensionOnly,
164                note: Some(
165                    "Leica LOF/XLEF-family extension, but the content does not match the expected header"
166                        .into(),
167                ),
168            });
169        }
170        None
171    }
172
173    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
174        self.open_input(&Input::local(path))
175    }
176
177    fn reads_any_source(&self) -> bool {
178        true
179    }
180
181    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
182        let fs: &Fs = input.fs();
183        let head = container::read_head(fs, input.path(), 4096)?;
184        let known = container::looks_like_lif(&head)
185            || container::looks_like_lifext(&head)
186            || container::looks_like_lof(&head)
187            || xlef::looks_like_xml_container(&head);
188        if !known {
189            return Err(Error::corrupt(
190                FORMAT_ID,
191                "file does not start with a LIF/LOF/LIFEXT header block or a Leica XML container",
192            ));
193        }
194        Ok(Box::new(dataset::LifDataset::open(input)?))
195    }
196}