dng 1.6.0

A pure Rust library for reading/writing of DNG files, providing access to the raw data
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
use crate::byte_order_rw::ByteOrderReader;
use crate::ifd::{Ifd, IfdEntryRef, IfdPath};
use crate::ifd_reader::IfdReader;
use crate::tags::{ifd, IfdType, IfdTypeInterpretation};
use crate::FileType;
use std::cell::RefCell;
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::io;
use std::io::{Read, Seek, SeekFrom};
use std::ops::DerefMut;

/// The error-type produced by [DngReader]
#[derive(Debug)]
pub enum DngReaderError {
    IoError(io::Error),
    FormatError(String),
    Other(String),
}

impl From<io::Error> for DngReaderError {
    fn from(e: io::Error) -> Self {
        Self::IoError(e)
    }
}

impl Display for DngReaderError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            DngReaderError::IoError(e) => f.write_fmt(format_args!("IoError: '{:?}'", e)),
            DngReaderError::FormatError(e) => f.write_fmt(format_args!("FormatError: '{}'", e)),
            DngReaderError::Other(e) => f.write_fmt(format_args!("Other: '{}'", e)),
        }
    }
}

impl Error for DngReaderError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            DngReaderError::IoError(e) => Some(e),
            DngReaderError::FormatError(_) => None,
            DngReaderError::Other(_) => None,
        }
    }
}

/// The main entrypoint for reading DNG/DCP files.
///
/// # Examples
///
/// ```
/// use std::fs::File;
/// use dng::DngReader;
///
/// let file = File::open("src/testdata/test.dng").expect("couldnt find file");
/// let dng = DngReader::read(file).expect("couldnt read file as dng");
///
/// // Migth read multiple buffers for tiled images.
/// let buffers = dng.main_image_data().expect("couldnt read buffers");
/// println!("successfully read {} buffers", buffers.len())
/// ```
#[derive(Debug)]
pub struct DngReader<R: Read + Seek> {
    ifds: Vec<Ifd>,
    reader: RefCell<ByteOrderReader<R>>,
    _file_type: FileType,
}

/// TIFF image type
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ImageType {
    /// An image possibly divided into strips of rows.
    Stripped,
    /// An image divided into tiles.
    Tiled,
}

impl<R: Read + Seek> DngReader<R> {
    /// reads and parses the DNG file IFD-tree eagerly.
    ///
    /// NOTE: OFFSETS (where the image data is located) are not yet read.
    ///
    /// For doing that, you can either use a combination of these functions for reading the data
    /// from OFFSETS entries on a low level:
    /// [get_entry_by_path][Self::get_entry_by_path],
    /// [needed_buffer_size_for_offsets][Self::needed_buffer_size_for_offsets],
    /// [read_offsets_to_buffer][Self::read_offsets_to_buffer]
    ///
    /// Or for a bit higher level direct image data access:
    /// [main_image_data_ifd_path][Self::main_image_data_ifd_path],
    /// [needed_buffer_length_for_image_data][Self::needed_buffer_length_for_image_data],
    /// [read_image_data_to_buffer][Self::read_image_data_to_buffer].
    /// (see usage example).
    pub fn read(mut reader: R) -> Result<Self, DngReaderError> {
        // the first two bytes set the byte order
        let mut header = vec![0u8; 2];
        reader.read_exact(&mut header)?;
        let is_little_endian = match (header[0], header[1]) {
            (0x49, 0x49) => Ok(true),
            (0x4D, 0x4D) => Ok(false),
            (_, _) => Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "invalid header bytes",
            )),
        }?;
        let mut reader = ByteOrderReader::new(reader, is_little_endian);
        let magic = reader.read_u16()?;
        let _file_type = FileType::from_magic(magic).ok_or_else(|| {
            DngReaderError::FormatError(format!(
                "invalid magic byte sequence (expected 42, got {}",
                magic
            ))
        })?;

        let mut next_ifd_offset = reader.read_u32()?;
        let mut unprocessed_ifds = Vec::new();

        while next_ifd_offset != 0 {
            reader.seek(SeekFrom::Start(next_ifd_offset as u64))?;
            unprocessed_ifds.push(IfdReader::read(&mut reader)?);
            next_ifd_offset = reader.read_u32()?;
        }
        let ifds: Result<Vec<_>, _> = unprocessed_ifds
            .iter()
            .map(|ifd| ifd.process(IfdType::Ifd, &mut reader))
            .collect();

        Ok(Self {
            reader: RefCell::new(reader),
            ifds: ifds?,
            _file_type,
        })
    }

    /// Returns the first toplevel IFD of the DNG file.
    pub fn first_ifd(&self) -> &Ifd {
        &self.ifds[0]
    }

    /// Returns the first toplevel IFD of the DNG file.
    #[deprecated(
        since = "1.6.0",
        note = "`get_` prefixes are non-canonical Rust; use `first_ifd()` instead"
    )]
    pub fn get_ifd0(&self) -> &Ifd {
        self.first_ifd()
    }

    pub fn entry_by_path<'a>(&'a self, path: &'a IfdPath) -> Option<IfdEntryRef<'a>> {
        for ifd in &self.ifds {
            let result = ifd.entry_by_path(path);
            if result.is_some() {
                return result;
            }
        }
        None
    }

    #[deprecated(
        since = "1.6.0",
        note = "`get_` prefixes are non-canonical Rust; use `entry_by_path()` instead"
    )]
    pub fn get_entry_by_path<'a>(&'a self, path: &'a IfdPath) -> Option<IfdEntryRef<'a>> {
        self.entry_by_path(path)
    }

    /// This low-level function returns the length of a single OFFSETS field.
    ///
    /// Lists are not supported (you must query the individual list member)
    pub fn needed_buffer_size_for_offsets(
        &self,
        entry: IfdEntryRef,
    ) -> Result<usize, DngReaderError> {
        if let Some(IfdTypeInterpretation::Offsets { lengths }) = entry.tag.type_interpretation() {
            let lengths_paths = entry.path.with_last_tag_replaced(lengths.as_maybe());
            let lengths_value = self.entry_by_path(&lengths_paths);
            if let Some(entry) = lengths_value {
                entry
                    .value
                    .as_u32()
                    .map(|v| v as usize)
                    .ok_or(DngReaderError::Other(format!(
                        "length tag {lengths_paths:?} for {:?} does not have integer value",
                        entry.path
                    )))
            } else {
                Err(DngReaderError::Other(format!(
                    "length tag {lengths_paths:?} for {:?} not found",
                    entry.path
                )))
            }
        } else {
            Err(DngReaderError::Other(format!(
                "entry {entry:?} is not of type offsets"
            )))
        }
    }
    /// This low-level function can read a single entry from an OFFSETS field to a buffer.
    ///
    /// Lists are not supported (you must query the individual list member)
    pub fn read_offsets_to_buffer(
        &self,
        entry: IfdEntryRef,
        buffer: &mut [u8],
    ) -> Result<(), DngReaderError> {
        let buffer_size = self.needed_buffer_size_for_offsets(entry)?;
        if buffer_size != buffer.len() {
            Err(DngReaderError::Other(format!(
                "buffer has wrong size (expected {buffer_size} found {}",
                buffer.len()
            )))
        } else {
            let mut reader = self.reader.borrow_mut();
            reader.seek(SeekFrom::Start(entry.value.as_u32().ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("entry {entry:?} cant be read into buffer. it is not a single OFFSETS"),
                )
            })? as u64))?;
            reader.read_exact(buffer)?;
            Ok(())
        }
    }

    /// Returns the Path to the IFD in which the main image data (not a preview) is stored.
    pub fn main_image_data_ifd_path(&self) -> IfdPath {
        self.first_ifd()
            .find_entry(|entry| {
                entry.tag == &ifd::NewSubfileType.as_maybe() && entry.value.as_u32() == Some(0)
            })
            .map(|entry| entry.parent())
            .unwrap_or_default()
    }

    /// Returns the image type for the image in the `ifd_path`; `None` if no image is present.
    pub fn image_type(&self, ifd_path: &IfdPath) -> Option<ImageType> {
        if self
            .entry_by_path(&ifd_path.chain_tag(ifd::StripOffsets))
            .is_some()
        {
            Some(ImageType::Stripped)
        } else if self
            .entry_by_path(&ifd_path.chain_tag(ifd::TileOffsets))
            .is_some()
        {
            Some(ImageType::Tiled)
        } else {
            None
        }
    }

    /// Returns the length in bytes needed for a buffer to store the image data from a given IFD.
    ///
    /// The IFD must contain a stripped image, otherwise an error is returned.
    pub fn needed_buffer_length_for_image_data(
        &self,
        ifd_path: &IfdPath,
    ) -> Result<usize, DngReaderError> {
        // we try the different options one after another
        if let (Some(offsets), Some(lengths)) = (
            self.entry_by_path(&ifd_path.chain_tag(ifd::StripOffsets)),
            self.entry_by_path(&ifd_path.chain_tag(ifd::StripByteCounts)),
        ) {
            lengths
                .value
                .as_list()
                .try_fold(0, |acc, x| {
                    x.as_u32()
                        .map(|v| acc + v)
                        .ok_or(DngReaderError::Other(format!(
                            "length tag {:?} for {:?} does not have integer value",
                            lengths.path, offsets.path
                        )))
                })
                .map(|v| v as usize)
        } else {
            Err(DngReaderError::Other(
                "No image stripe was found in the specified IFD or the path didnt lead to an IFD"
                    .to_string(),
            ))
        }
    }

    /// Reads the image data from a given IFD into a given buffer.
    ///
    /// The IFD must contain a stripped image, otherwise an error is returned.
    pub fn read_image_data_to_buffer(
        &self,
        ifd_path: &IfdPath,
        buffer: &mut [u8],
    ) -> Result<(), DngReaderError> {
        // we try the different options one after another
        if let (Some(offsets), Some(lengths)) = (
            self.entry_by_path(&ifd_path.chain_tag(ifd::StripOffsets)),
            self.entry_by_path(&ifd_path.chain_tag(ifd::StripByteCounts)),
        ) {
            let mut reader = self.reader.borrow_mut();
            let count = offsets.value.count();
            if count != lengths.value.count() {
                return Err(DngReaderError::FormatError(
                    "the counts of OFFSETS and LENGTHS must be the same".to_string(),
                ));
            }
            let mut buffer_offset = 0;
            for (offset, length) in offsets.value.as_list().zip(lengths.value.as_list()) {
                let offset = offset.as_u32().ok_or(DngReaderError::Other(format!(
                    "offset tag {offset:?} for  {:?} does not have integer value",
                    offsets.path
                )))?;
                let length = length.as_u32().ok_or(DngReaderError::Other(format!(
                    "length tag {length:?} for  {:?} does not have integer value",
                    offsets.path
                )))?;

                reader.seek(SeekFrom::Start(offset as u64))?;
                let buffer_slice =
                    &mut buffer[(buffer_offset as usize)..((buffer_offset + length) as usize)];
                reader.read_exact(buffer_slice)?;

                buffer_offset += length;
            }
            Ok(())
        } else {
            Err(DngReaderError::Other(
                "No image stripe was found in the specified IFD or the path didnt lead to an IFD"
                    .to_string(),
            ))
        }
    }

    /// Returns the length in bytes needed for a buffer to store the image tiles from a given IFD.
    ///
    /// The IFD must contain a tiled image, otherwise an error is returned.
    pub fn needed_buffer_lengths_for_tile_data(
        &self,
        ifd_path: &IfdPath,
    ) -> Result<Vec<usize>, DngReaderError> {
        // we try the different options one after another
        if let (Some(_offsets), Some(lengths)) = (
            self.entry_by_path(&ifd_path.chain_tag(ifd::TileOffsets)),
            self.entry_by_path(&ifd_path.chain_tag(ifd::TileByteCounts)),
        ) {
            lengths
                .value
                .as_list()
                .map(|v| v.as_u32().map(|v| v as usize))
                .collect::<Option<Vec<_>>>()
                .ok_or(DngReaderError::Other(
                    "Invalid tile length data in the specified IFD".to_string(),
                ))
        } else {
            Err(DngReaderError::Other(
                "No tile length data was found in the specified IFD or the path didnt lead to an IFD"
                    .to_string(),
            ))
        }
    }

    /// Reads the image tiles from a given IFD into given buffers.
    ///
    /// The IFD must contain a tiled image, otherwise an error is returned.
    pub fn read_tile_data_to_buffers<'a, I: Iterator<Item = &'a mut [u8]>>(
        &self,
        ifd_path: &IfdPath,
        buffers: I,
    ) -> Result<(), DngReaderError> {
        if let (Some(offsets), Some(lengths)) = (
            self.entry_by_path(&ifd_path.chain_tag(ifd::TileOffsets)),
            self.entry_by_path(&ifd_path.chain_tag(ifd::TileByteCounts)),
        ) {
            let mut reader = self.reader.borrow_mut();
            let count = offsets.value.count();
            if count != lengths.value.count() {
                return Err(DngReaderError::FormatError(
                    "the counts of OFFSETS and LENGTHS must be the same".to_string(),
                ));
            }
            for (offset, buffer) in offsets.value.as_list().zip(buffers) {
                let offset = offset.as_u32().ok_or(DngReaderError::Other(format!(
                    "offset tag {offset:?} for  {:?} does not have integer value",
                    offsets.path
                )))?;
                reader.seek(SeekFrom::Start(offset as u64))?;
                reader.read_exact(buffer)?;
            }
            Ok(())
        } else {
            Err(DngReaderError::Other(
                "No image data was found in the specified IFD or the path didnt lead to an IFD"
                    .to_string(),
            ))
        }
    }

    /// Reads the image data into a newly alloated buffers. May return more buffers if the image is tiled,
    /// or none if the IFD contains no images.
    pub fn image_data(&self, ifd_path: &IfdPath) -> Result<Vec<Vec<u8>>, DngReaderError> {
        match self.image_type(ifd_path) {
            Some(ImageType::Stripped) => {
                let len = self.needed_buffer_length_for_image_data(ifd_path)?;
                let mut buffer = vec![0; len];
                self.read_image_data_to_buffer(ifd_path, &mut buffer)?;
                Ok(vec![buffer])
            }
            Some(ImageType::Tiled) => {
                let lens = self.needed_buffer_lengths_for_tile_data(ifd_path)?;
                let mut buffers: Vec<_> = lens.into_iter().map(|len| vec![0; len]).collect();
                self.read_tile_data_to_buffers(
                    ifd_path,
                    buffers.iter_mut().map(DerefMut::deref_mut),
                )?;
                Ok(buffers)
            }
            None => Ok(Vec::with_capacity(0)),
        }
    }

    /// Reads the main image data into a newly alloated buffers. May return more buffers if the image is tiled,
    /// or none if the IFD contains no images.
    pub fn main_image_data(&self) -> Result<Vec<Vec<u8>>, DngReaderError> {
        let ifd_path = self.main_image_data_ifd_path();
        self.image_data(&ifd_path)
    }
}