Skip to main content

openreadout_oir/
lib.rs

1//! Clean-room reader for Olympus/Evident OIR files (FluoView), including multi-file series whose
2//! pixel blocks continue in `<name>_00001`, `<name>_00002`, ... next to the `.oir`.
3//!
4//! Layout and vocabulary: `docs/formats/oir.md`. Provenance: `docs/provenance/oir.md`.
5//! An OIR file is a 96-byte header, a chain of typed blocks (XML documents, frame properties,
6//! chunk tags and raw pixel chunks, a bitmap thumbnail) and a block index at the end.
7//!
8//! # Example
9//!
10//! Every reader implements [`openreadout_core::FormatReader`]: `descriptor`
11//! says what it reads, `sniff` recognises a file from its first bytes, and `open` returns a
12//! [`openreadout_core::Dataset`] with a header-only `info()` summary and lazy data
13//! access.
14//!
15//! ```
16//! use openreadout_core::FormatReader;
17//! use openreadout_oir::OirReader;
18//!
19//! let format = OirReader.descriptor();
20//! assert_eq!(format.id, openreadout_oir::FORMAT_ID);
21//! println!("{} ({}): .{}", format.name, format.family, format.extensions.join(", ."));
22//! ```
23//!
24//! Reading a file:
25//!
26//! ```no_run
27//! use std::path::Path;
28//!
29//! use openreadout_core::{FormatReader, PlaneIndex};
30//! use openreadout_oir::OirReader;
31//!
32//! let mut dataset = OirReader.open(Path::new("scan.oir"))?;
33//! let info = dataset.info()?; // headers only: fast even on multi-gigabyte files
34//! for image in &info.images {
35//!     println!(
36//!         "image {}: {} x {} px, {} channel(s), {} plane(s)",
37//!         image.index, image.size_x, image.size_y, image.size_c, image.plane_count
38//!     );
39//! }
40//! // Pixels are read one plane at a time: image 0, channel 0, first Z slice, first time point.
41//! let plane = dataset.read_plane(0, PlaneIndex { c: 0, z: 0, t: 0 })?;
42//! assert_eq!(plane.data.len(), plane.expected_len());
43//! # Ok::<(), openreadout_core::Error>(())
44//! ```
45//!
46//! Applications that accept any instrument file usually register every reader in an
47//! [`openreadout_core::Registry`] and let it detect the format; that is what the
48//! `openreadout` command-line tool does.
49//!
50//! # API stability
51//!
52//! The supported API is what this page documents. The parser modules are public only so that
53//! tests and fuzz targets can reach them: they are hidden from this documentation and may change
54//! in any release.
55#![forbid(unsafe_code)]
56#![warn(missing_docs)]
57
58mod assurance;
59#[doc(hidden)]
60pub mod container;
61#[doc(hidden)]
62pub mod dataset;
63#[doc(hidden)]
64pub mod meta;
65
66use std::path::Path;
67
68use openreadout_core::model::{DetectConfidence, FormatDescriptor};
69use openreadout_core::reader::{Dataset, Detection, FormatReader, has_extension};
70use openreadout_core::source::Input;
71use openreadout_core::{Error, Result};
72
73#[doc(hidden)]
74pub use container::{
75    Block, BlockKind, ChunkName, ChunkTag, FIRST_BLOCK_OFFSET, INDEX_MARKER, MAGIC, OirFile,
76    OirHeader, XmlDoc, documents, looks_like_oir,
77};
78#[doc(hidden)]
79pub use dataset::OirDataset;
80#[doc(hidden)]
81pub use meta::{
82    AxisDesc, ChannelDesc, ChannelSettings, FrameGeometry, FrameRecord, ImageProperties, LaserLine,
83    ObjectiveDesc,
84};
85
86/// Format id used on the command line and in JSON.
87pub const FORMAT_ID: &str = "oir";
88
89/// The Olympus/Evident OIR format reader.
90#[derive(Debug, Default, Clone, Copy)]
91pub struct OirReader;
92
93impl FormatReader for OirReader {
94    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
95        Some(&assurance::OIR)
96    }
97
98    fn descriptor(&self) -> FormatDescriptor {
99        FormatDescriptor {
100            id: FORMAT_ID.into(),
101            name: "Olympus/Evident OIR".into(),
102            vendor: "Evident (Olympus)".into(),
103            extensions: vec!["oir".into()],
104            family: "microscopy".into(),
105            can_read: true,
106            can_write: false,
107            confidence: assurance::OIR.confidence,
108            known_gaps: vec![
109                "Compressed pixel blocks are not known to exist and are not handled; 4-byte samples are read as float32 on the strength of oirfile's documentation only (no corpus file)".into(),
110                "RGB (colour camera) acquisitions are exposed as three planar channels, not as interleaved RGB; no corpus file".into(),
111                "Line scans are exposed as XY planes whose height is the number of stored lines (no reinterpretation of Y as time); no corpus file".into(),
112                "POIR/MPOIR archives (zip collections of OIR files, mosaic layouts in matl.omp2info) are not read; open the .oir files inside".into(),
113                "Chunk names with axis letters other than t, l and z are listed by `check` but not exposed".into(),
114                "Excitation wavelength is reported only when exactly one enabled laser line is linked to the channel".into(),
115            ],
116        }
117    }
118
119    fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection> {
120        if container::looks_like_oir(head) {
121            let continuation = !has_extension(path, &["oir"]);
122            return Some(Detection {
123                format_id: FORMAT_ID,
124                confidence: DetectConfidence::Definite,
125                note: continuation.then(|| {
126                    "OIR continuation file (pixel blocks of a multi-file series); open the .oir file of the series for its metadata".to_string()
127                }),
128            });
129        }
130        // a longer file without the signature is another kind of file (exit 3)
131        if has_extension(path, &["oir"]) && head.len() < 16 {
132            return Some(Detection {
133                format_id: FORMAT_ID,
134                confidence: DetectConfidence::ExtensionOnly,
135                note: Some(
136                    "`.oir` extension, but the file does not start with OLYMPUSRAWFORMAT".into(),
137                ),
138            });
139        }
140        None
141    }
142
143    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
144        self.open_input(&Input::local(path))
145    }
146
147    fn reads_any_source(&self) -> bool {
148        true
149    }
150
151    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
152        let path = input.path();
153        if !input.fs().is_file(path) {
154            return Err(Error::io(
155                path,
156                std::io::Error::new(std::io::ErrorKind::NotFound, "not a file"),
157            ));
158        }
159        Ok(Box::new(dataset::OirDataset::open(input)?))
160    }
161}