eozin 0.1.0-alpha.2

A pure-Rust decoder library for digital pathology
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Decoder works with `R: Read + Seek`.
//!
//! This module requires the following crate feature to be activated: `std-io`.
use crate::error::EozinError::{self, *};

use crate::base::{
    DecoderConstructor, EozinDecoderCore, LevelInfo, ReadCommand::*, ReadConsumer, Tile,
    MAX_ALLOCATION, MAX_LOOP_COUNT
};
use crate::dynamic_decoder::{self, SlideFormat};
// use crate::format::philips;
// use crate::format::{aperio, generic_tiff, ndpi, olympus};
use std::{
    fs::File,
    io::{BufReader, Read, Seek, SeekFrom},
    marker::PhantomData,
    path::Path,
};

/// A decoder that dynamically detects file formats.
pub struct DynamicDecoder<R: Read + Seek> {
    decoder: DynamicDecoderBase<R>,
}

impl<R: Read + Seek> DynamicDecoder<R> {
    /// Constructs a new `DynamicDecoder` from an instance satisfying `Read + Seek`.
    ///
    /// When working with Olympus ETS files, specify the ETS file directly
    /// (e.g., `frame_t.ets`) rather than the VSI file.
    ///
    /// ```rust,no_run
    /// # use eozin::std_io::DynamicDecoder;
    /// let in_mem_buf = vec![0x4D, 0x4D, 0x00, 0x2A, 0x00, 0x00, 0x00, 0x08];
    /// let mut cur = std::io::Cursor::new(in_mem_buf);
    /// let mut decoder = DynamicDecoder::new(cur);
    /// ```
    pub fn new(r: R) -> Result<DynamicDecoder<R>, EozinError> {
        let decoder = DynamicDecoderBase::new(r)?;
        Ok(DynamicDecoder { decoder })
    }

    /// Reads the tile at the specified level and coordinates.
    /// All indices are 0-based.
    pub fn read_tile(&mut self, lv: usize, x: usize, y: usize) -> Result<Tile, EozinError> {
        self.decoder.read_tile(lv, x, y)
    }

    /// Reads the tile with the given index as `Vec<u8>`.
    /// This provides same functionality as follows;
    ///
    /// ```rust,no_run
    /// # use eozin::std_io::DynamicDecoder;
    /// # let mut decoder = DynamicDecoder::with_path("/some/slide.svs").unwrap();
    /// let buf = decoder.read_tile_as_bytes(0, 0, 0).unwrap();
    /// assert_eq!(buf, decoder.read_tile(0, 0, 0).unwrap().to_vec());
    /// ```
    pub fn read_tile_as_bytes(
        &mut self,
        lv: usize,
        x: usize,
        y: usize,
    ) -> Result<Vec<u8>, EozinError> {
        self.decoder.read_tile_as_bytes(lv, x, y)
    }

    /// Returns the number of levels
    pub fn level_count(&self) -> usize {
        self.decoder.level_count()
    }

    /// Returns the dimensions (width, height) of the image at the highest 
    /// resolution (level 0).
    pub fn dimensions(&self) -> (u64, u64) {
        self.decoder.dimensions()
    }

    /// Returns the dimensions for each level as a vector of (width, height) 
    /// tuples, starting from level 0.
    pub fn level_dimensions(&self) -> Vec<(u64, u64)> {
        self.decoder.level_dimensions()
    }

    /// Returns the nominal tile size (width, height) for each level.
    ///
    /// Note: While tiles within a level are usually of uniform size, 
    /// the rightmost and bottommost tiles may be smaller if the level's 
    /// total dimensions are not divisible by the tile size (common in NDPI files).
    /// Refer to the `width` and `height` properties of the returned [`Tile`] 
    /// for the actual dimensions of boundary tiles.
    ///
    /// ```rust,no_run
    /// # use eozin::{std_io::DynamicDecoder, Tile};
    /// let mut decoder = DynamicDecoder::with_path("/some/slide.ndpi").unwrap();
    /// let target_lv = decoder.level_count() - 1;
    /// let (lv_width, lv_height) = decoder.level_dimensions()[target_lv];
    /// let (tile_width, tile_height) = decoder.level_tile_sizes()[target_lv];
    ///
    /// let (num_horizontal, num_vertical) = decoder.level_tile_ranges()[target_lv];
    /// let right_most = decoder.read_tile(target_lv, num_horizontal - 1, 0).unwrap();
    ///
    /// // The width of the rightmost tile is the remainder of the level width 
    /// // divided by the standard tile width.
    /// assert_eq!(right_most.width as u64, (lv_width % tile_width));
    /// ```
    pub fn level_tile_sizes(&self) -> Vec<(u64, u64)> {
        self.decoder.level_tile_sizes()
    }

    /// Returns the grid range for each level as a vector of 
    /// (horizontal_tile_count, vertical_tile_count) tuples.
    pub fn level_tile_ranges(&self) -> Vec<(usize, usize)> {
        self.decoder.level_tile_ranges()
    }

    /// Returns the format of slide.
    pub fn slide_format(&self) -> SlideFormat {
        self.decoder.slide_format()
    }
}

impl DynamicDecoder<BufReader<File>> {
    /// Construct decoder from given file path.
    ///
    /// When working with OlympusETS files, specify the ETS file directly
    /// (often frame_t.ets) not the VSI file.
    ///
    /// ```rust,no_run
    /// # use eozin::std_io::DynamicDecoder;
    /// let mut decoder = DynamicDecoder::with_path("/some/slide.tiff");
    /// ```
    pub fn with_path<P: AsRef<Path>>(
        path: P,
    ) -> Result<DynamicDecoder<BufReader<File>>, EozinError> {
        let decoder = DynamicDecoderBase::with_path(path)?;
        Ok(DynamicDecoder { decoder })
    }
}

/*
pub struct AperioDecoder<R: Read + Seek> {
    decoder: AperioDecoderBase<R>,
}

impl<R: Read + Seek> AperioDecoder<R> {
    pub fn new(r: R) -> Result<AperioDecoder<R>, EozinError> {
        let decoder = AperioDecoderBase::new(r)?;
        Ok(AperioDecoder { decoder })
    }
    pub fn read_tile_as_bytes(
        &mut self,
        lv: usize,
        x: usize,
        y: usize,
    ) -> Result<Vec<u8>, EozinError> {
        self.decoder.read_tile_as_bytes(lv, x, y)
    }
    pub fn level_count(&self) -> usize {
        self.decoder.level_count()
    }
    pub fn dimensions(&self) -> (u64, u64) {
        self.decoder.dimensions()
    }
    pub fn level_dimensions(&self) -> Vec<(u64, u64)> {
        self.decoder.level_dimensions()
    }
    pub fn level_tile_sizes(&self) -> Vec<(u64, u64)> {
        self.decoder.level_tile_sizes()
    }
    pub fn level_tile_ranges(&self) -> Vec<(usize, usize)> {
        self.decoder.level_tile_ranges()
    }
}
*/

/*
pub struct NdpiDecoder<R: Read + Seek> {
    decoder: NdpiDecoderBase<R>,
}

impl<R: Read + Seek> NdpiDecoder<R> {
    pub fn new(r: R) -> Result<NdpiDecoder<R>, EozinError> {
        let decoder = NdpiDecoderBase::new(r)?;
        Ok(NdpiDecoder { decoder })
    }
    pub fn read_tile_as_bytes(
        &mut self,
        lv: usize,
        x: usize,
        y: usize,
    ) -> Result<Vec<u8>, EozinError> {
        self.decoder.read_tile_as_bytes(lv, x, y)
    }
    pub fn level_count(&self) -> usize {
        self.decoder.level_count()
    }
    pub fn dimensions(&self) -> (u64, u64) {
        self.decoder.dimensions()
    }
    pub fn level_dimensions(&self) -> Vec<(u64, u64)> {
        self.decoder.level_dimensions()
    }
    pub fn level_tile_sizes(&self) -> Vec<(u64, u64)> {
        self.decoder.level_tile_sizes()
    }
    pub fn level_tile_ranges(&self) -> Vec<(usize, usize)> {
        self.decoder.level_tile_ranges()
    }
}
*/

/*
pub struct OlympusDecoder<R: Read + Seek> {
    decoder: OlympusDecoderBase<R>,
}

impl<R: Read + Seek> OlympusDecoder<R> {
    pub fn new(r: R) -> Result<OlympusDecoder<R>, EozinError> {
        let decoder = OlympusDecoderBase::new(r)?;
        Ok(OlympusDecoder { decoder })
    }
    pub fn read_tile_as_bytes(
        &mut self,
        lv: usize,
        x: usize,
        y: usize,
    ) -> Result<Vec<u8>, EozinError> {
        self.decoder.read_tile_as_bytes(lv, x, y)
    }
    pub fn level_count(&self) -> usize {
        self.decoder.level_count()
    }
    pub fn dimensions(&self) -> (u64, u64) {
        self.decoder.dimensions()
    }
    pub fn level_dimensions(&self) -> Vec<(u64, u64)> {
        self.decoder.level_dimensions()
    }
    pub fn level_tile_sizes(&self) -> Vec<(u64, u64)> {
        self.decoder.level_tile_sizes()
    }
    pub fn level_tile_ranges(&self) -> Vec<(usize, usize)> {
        self.decoder.level_tile_ranges()
    }
}
*/

struct EozinDecoder<R, D, C>
where
    R: Read + Seek,
    D: EozinDecoderCore,
    C: DecoderConstructor,
{
    pub(crate) decoder: D,
    pub(crate) r: R,
    _c: PhantomData<C>,
}

#[allow(dead_code)]
impl<R, D, C> EozinDecoder<R, D, C>
where
    R: Read + Seek,
    D: EozinDecoderCore,
    C: DecoderConstructor<Output = D>,
{
    fn new(mut r: R) -> Result<EozinDecoder<R, D, C>, EozinError> {
        let decoder = excecute_read::<_, C>(&mut r, C::Input::default())?;
        Ok(EozinDecoder {
            decoder,
            r,
            _c: PhantomData,
        })
    }
    fn read_tile_as_bytes(&mut self, lv: usize, x: usize, y: usize) -> Result<Vec<u8>, EozinError> {
        let ri = self.decoder.read_tile(lv, x, y)?;
        let img = excecute_read::<_, D::ReadTile>(&mut self.r, ri)?;
        Ok(img)
    }
    fn read_tile(&mut self, lv: usize, x: usize, y: usize) -> Result<Tile, EozinError> {
        let buf = self.read_tile_as_bytes(lv, x, y)?;
        let image_type = self
            .decoder
            .get_level(lv)
            .map(|l| l.image_type)
            .ok_or(EozinError::UnexpectedStep)?;
        let (width, height) = self
            .decoder
            .tile_size(lv, x, y)
            .and_then(|(w, h)| w.try_into().ok().zip(h.try_into().ok()))
            .ok_or(EozinError::UnexpectedStep)?;
        Ok(Tile {
            buf,
            image_type,
            width,
            height,
        })
    }
    fn level_count(&self) -> usize {
        self.decoder.level_count()
    }
    fn get_level(&self, i: usize) -> Option<LevelInfo> {
        self.decoder.get_level(i)
    }
    fn dimensions(&self) -> (u64, u64) {
        self.decoder.dimensions()
    }
    fn level_dimensions(&self) -> Vec<(u64, u64)> {
        self.decoder.level_dimensions()
    }
    fn level_tile_sizes(&self) -> Vec<(u64, u64)> {
        self.decoder.level_tile_sizes()
    }
    fn level_tile_ranges(&self) -> Vec<(usize, usize)> {
        self.decoder.level_tile_ranges()
    }
}

#[allow(dead_code)]
impl<D, C> EozinDecoder<BufReader<File>, D, C>
where
    D: EozinDecoderCore,
    C: DecoderConstructor<Output = D>,
{
    fn with_path<P: AsRef<Path>>(
        path: P,
    ) -> Result<EozinDecoder<BufReader<File>, D, C>, EozinError> {
        let file = File::open(path)?;
        let reader = BufReader::new(file);
        Self::new(reader)
    }
}

type DynamicDecoderBase<R> =
    EozinDecoder<R, dynamic_decoder::DynamicDecoder, dynamic_decoder::DynamicDecoderConstructor>;

#[allow(dead_code)]
impl<R: Read + Seek> DynamicDecoderBase<R> {
    pub fn slide_format(&self) -> SlideFormat {
        self.decoder.slide_format()
    }

    /*
    pub fn expect_aperio(self) -> Option<AperioDecoderBase<R>> {
        let EozinDecoder { decoder, r, .. } = self;
        if let dynamic_decoder::DynamicDecoder::Aperio(decoder) = decoder {
            Some(EozinDecoder {
                decoder,
                r,
                _c: PhantomData,
            })
        } else {
            None
        }
    }

    pub fn expect_philips(self) -> Option<PhilipsDecoderBase<R>> {
        let EozinDecoder { decoder, r, .. } = self;
        if let dynamic_decoder::DynamicDecoder::Philips(decoder) = decoder {
            Some(EozinDecoder {
                decoder,
                r,
                _c: PhantomData,
            })
        } else {
            None
        }
    }
    */
}

/*
type AperioDecoderBase<R> =
    EozinDecoder<R, aperio::AperioDecoder, aperio::AperioDecoderConstructor>;

#[allow(dead_code)]
type PhilipsDecoderBase<R> =
    EozinDecoder<R, philips::PhilipsDecoder, philips::PhilipsDecoderConstructor>;

type NdpiDecoderBase<R> = EozinDecoder<R, ndpi::NdpiDecoder, ndpi::NdpiDecoderConstructor>;

type OlympusDecoderBase<R> = EozinDecoder<R, olympus::EtsDecoder, olympus::EtsDecoderConstructor>;

#[allow(dead_code)]
type GenericTiffDecoderBase<R> =
    EozinDecoder<R, generic_tiff::GenericTiffDecoder, generic_tiff::GenericTiffDecoderConstructor>;
*/

fn excecute_read<R, C>(mut r: &mut R, input: C::Input) -> Result<C::Output, EozinError>
where
    R: Read + Seek,
    C: ReadConsumer<ErrorKind = EozinError>,
{
    let (mut c, mut cmd) = C::dispatch(input);
    for _ in 0..MAX_LOOP_COUNT {
        match cmd {
            NoCmd => return c.receive(&[]),
            ReadBytes { offset, count } => {
                let buf = read_bytes(&mut r, offset, count)?;
                return c.receive(&buf);
            }
            ReadBytesStep { offset, count } => {
                let buf = read_bytes(&mut r, offset, count)?;
                cmd = c.step(&buf)?;
            }
        }
    }
    Err(UnableToAllocateLargeSize)
}

fn read_bytes<R: Read + Seek>(
    data: &mut R,
    offset: u64,
    count: u64,
) -> Result<Vec<u8>, EozinError> {
    if count > MAX_ALLOCATION {
        return Err(UnableToAllocateLargeSize);
    }
    let mut buffer = vec![0_u8; count as usize];
    data.seek(SeekFrom::Start(offset))?;
    let l = data.read(&mut buffer)?;
    if l == count as usize {
        Ok(buffer)
    } else {
        Err(UnexpectedStep)
    }
}