Skip to main content

openreadout_nd2/
lib.rs

1//! Clean-room reader for Nikon ND2 files (chunk-based format).
2//!
3//! Layout and vocabulary: `docs/formats/nd2.md`. Provenance: `docs/provenance/nd2.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_nd2::Nd2Reader;
15//!
16//! let format = Nd2Reader.descriptor();
17//! assert_eq!(format.id, openreadout_nd2::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_nd2::Nd2Reader;
28//!
29//! let mut dataset = Nd2Reader.open(Path::new("timelapse.nd2"))?;
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 container;
58mod dataset;
59mod deinterleave;
60#[doc(hidden)]
61pub mod frames;
62#[cfg(feature = "fuzzing")]
63#[doc(hidden)]
64pub mod fuzzing;
65#[doc(hidden)]
66pub mod legacy;
67#[doc(hidden)]
68pub mod lv;
69#[doc(hidden)]
70pub mod meta;
71#[doc(hidden)]
72pub mod variant;
73
74use std::path::Path;
75
76use openreadout_core::Result;
77use openreadout_core::model::{DetectConfidence, FormatDescriptor};
78use openreadout_core::reader::{Dataset, Detection, FormatReader, has_extension};
79use openreadout_core::source::Input;
80
81#[doc(hidden)]
82pub use container::{
83    CHUNK_MAGIC, CHUNK_MAGIC_BYTES, CHUNK_MAP_SIGNATURE, ChunkHeader, ChunkMapEntry, FILE_MAP_NAME,
84    FILE_SIGNATURE, LEGACY_SIGNATURE, Nd2File,
85};
86#[doc(hidden)]
87pub use frames::CustomTag;
88#[doc(hidden)]
89pub use legacy::{BOX_MAP_SIGNATURE, LegacyBox, LegacyFile};
90#[doc(hidden)]
91pub use lv::lv_decode;
92#[doc(hidden)]
93pub use meta::{
94    Attributes, CameraSetting, FrameLayout, Loop, LoopKind, Period, PlaneDesc, Position,
95};
96#[doc(hidden)]
97pub use variant::{legacy_xml_decode, variant_decode};
98
99/// Format id used on the command line and in JSON.
100pub const FORMAT_ID: &str = "nd2";
101
102/// The Nikon ND2 format reader.
103#[derive(Debug, Default, Clone, Copy)]
104pub struct Nd2Reader;
105
106impl FormatReader for Nd2Reader {
107    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
108        Some(&assurance::ND2)
109    }
110
111    fn descriptor(&self) -> FormatDescriptor {
112        FormatDescriptor {
113            id: FORMAT_ID.into(),
114            name: "Nikon ND2".into(),
115            vendor: "Nikon".into(),
116            extensions: vec!["nd2".into()],
117            family: "microscopy".into(),
118            can_read: true,
119            can_write: false,
120            confidence: assurance::ND2.confidence,
121            known_gaps: vec![
122                "Lossy-compressed frames (eCompression 1) are not decoded: no public sample exists to derive the codec from".into(),
123                "Custom loops and unrecognized loop types are folded into T; NE-time sub-loops (pSubLoops) are not expanded".into(),
124                "Legacy (JPEG 2000) files: events and per-frame times are read, ROIs and custom-data columns do not exist in that generation".into(),
125                "ROI geometry is normalized from the documented tree layout but no corpus file contains ROIs; units are as stored".into(),
126                "RGB planes carry no excitation/emission wavelengths (the nd2 package assigns pseudo-wavelengths; we do not)".into(),
127                "RGB planes are returned R, G, B (modern files store B, G, R; validated on dye-coded planes); legacy JPEG 2000 RGB planes keep the codestream order their JP2 colour box declares as sRGB (inferred, no reference export)".into(),
128            ],
129        }
130    }
131
132    fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection> {
133        if head.starts_with(&CHUNK_MAGIC_BYTES)
134            && head.len() > 48
135            && head[16..].starts_with(FILE_SIGNATURE.as_bytes())
136        {
137            return Some(Detection {
138                format_id: FORMAT_ID,
139                confidence: DetectConfidence::Definite,
140                note: None,
141            });
142        }
143        if head.starts_with(&CHUNK_MAGIC_BYTES) {
144            return Some(Detection {
145                format_id: FORMAT_ID,
146                confidence: DetectConfidence::Likely,
147                note: Some("chunk magic without the file signature".into()),
148            });
149        }
150        if head.starts_with(&LEGACY_SIGNATURE) && has_extension(path, &["nd2"]) {
151            return Some(Detection {
152                format_id: FORMAT_ID,
153                confidence: DetectConfidence::Likely,
154                note: Some("legacy JPEG 2000-based ND2".into()),
155            });
156        }
157        None
158    }
159
160    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
161        self.open_input(&Input::local(path))
162    }
163
164    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
165        Ok(Box::new(dataset::Nd2Dataset::open(input)?))
166    }
167
168    fn reads_any_source(&self) -> bool {
169        true
170    }
171}