tiff-writer 0.4.0

Pure-Rust TIFF/BigTIFF encoder with compression, tiling, and streaming writes
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
//! Low-level TIFF byte emission: header writing, IFD serialization, offset patching.

use std::io::{Seek, SeekFrom, Write};

use tiff_core::{ByteOrder, Tag, TagValue};

use crate::error::Result;

pub const CLASSIC_HEADER_LEN: u64 = 8;
pub const BIGTIFF_HEADER_LEN: u64 = 16;

fn classic_offset_u32(offset: u64) -> Result<u32> {
    u32::try_from(offset).map_err(|_| crate::error::Error::ClassicOffsetOverflow { offset })
}

fn classic_byte_count_u32(byte_count: u64) -> Result<u32> {
    u32::try_from(byte_count)
        .map_err(|_| crate::error::Error::ClassicByteCountOverflow { byte_count })
}

/// Write the TIFF header. Classic = 8 bytes, BigTIFF = 16 bytes.
/// The first-IFD offset is set to 0 and must be patched later.
pub const fn header_len(is_bigtiff: bool) -> u64 {
    if is_bigtiff {
        BIGTIFF_HEADER_LEN
    } else {
        CLASSIC_HEADER_LEN
    }
}

pub fn write_header<W: Write + Seek>(
    sink: &mut W,
    byte_order: ByteOrder,
    is_bigtiff: bool,
) -> Result<u64> {
    let pos = sink.stream_position()?;
    sink.write_all(&byte_order.magic())?;
    if is_bigtiff {
        sink.write_all(&byte_order.write_u16(43))?;
        sink.write_all(&byte_order.write_u16(8))?; // offset size
        sink.write_all(&byte_order.write_u16(0))?; // reserved
        sink.write_all(&byte_order.write_u64(0))?; // placeholder
    } else {
        sink.write_all(&byte_order.write_u16(42))?;
        sink.write_all(&byte_order.write_u32(0))?; // placeholder
    }
    Ok(pos)
}

/// Patch the first-IFD offset in the file header.
pub fn patch_first_ifd<W: Write + Seek>(
    sink: &mut W,
    header_offset: u64,
    byte_order: ByteOrder,
    is_bigtiff: bool,
    ifd_offset: u64,
) -> Result<()> {
    if is_bigtiff {
        sink.seek(SeekFrom::Start(header_offset + 8))?;
        sink.write_all(&byte_order.write_u64(ifd_offset))?;
    } else {
        sink.seek(SeekFrom::Start(header_offset + 4))?;
        sink.write_all(&byte_order.write_u32(classic_offset_u32(ifd_offset)?))?;
    }
    Ok(())
}

/// State returned after writing an IFD, used for patching.
#[derive(Debug)]
pub struct IfdWriteResult {
    /// File offset where this IFD starts.
    pub ifd_offset: u64,
    /// File offset of the "next IFD" pointer.
    pub next_ifd_pointer_offset: u64,
    /// File offsets where the offset-array and bytecount-array deferred data reside.
    pub offsets_tag_data_offset: Option<u64>,
    pub byte_counts_tag_data_offset: Option<u64>,
    /// Whether this IFD was written in BigTIFF format.
    pub is_bigtiff: bool,
}

/// Estimate the encoded size of an IFD, including deferred tag payloads.
pub fn estimate_ifd_size(byte_order: ByteOrder, is_bigtiff: bool, tags: &[Tag]) -> u64 {
    let entry_size: u64 = if is_bigtiff { 20 } else { 12 };
    let inline_max: usize = if is_bigtiff { 8 } else { 4 };
    let next_ptr_size: u64 = if is_bigtiff { 8 } else { 4 };
    let count_size: u64 = if is_bigtiff { 8 } else { 2 };
    let deferred_len: u64 = tags
        .iter()
        .map(|tag| {
            let encoded_len = tag.value.encode(byte_order).len();
            if encoded_len > inline_max {
                encoded_len as u64
            } else {
                0
            }
        })
        .sum();

    count_size + tags.len() as u64 * entry_size + next_ptr_size + deferred_len
}

/// Write an IFD (Classic or BigTIFF). Tags must be sorted by code.
pub fn write_ifd<W: Write + Seek>(
    sink: &mut W,
    byte_order: ByteOrder,
    is_bigtiff: bool,
    tags: &[Tag],
    offsets_tag_code: u16,
    byte_counts_tag_code: u16,
    _num_blocks: usize,
) -> Result<IfdWriteResult> {
    if !is_bigtiff && tags.len() > u16::MAX as usize {
        return Err(crate::error::Error::Other(
            "classic TIFF IFD entry count exceeds u16::MAX".into(),
        ));
    }

    let ifd_offset = sink.stream_position()?;

    // Sizes depend on format
    let entry_size: u64 = if is_bigtiff { 20 } else { 12 };
    let inline_max: usize = if is_bigtiff { 8 } else { 4 };
    let next_ptr_size: u64 = if is_bigtiff { 8 } else { 4 };
    let count_size: u64 = if is_bigtiff { 8 } else { 2 };

    // Entry count
    if is_bigtiff {
        sink.write_all(&byte_order.write_u64(tags.len() as u64))?;
    } else {
        sink.write_all(&byte_order.write_u16(tags.len() as u16))?;
    }

    // Calculate deferred data area start
    let entries_total = tags.len() as u64 * entry_size;
    let deferred_start = ifd_offset + count_size + entries_total + next_ptr_size;
    let mut deferred_offset = deferred_start;

    struct DeferredEntry {
        data: Vec<u8>,
        offset: u64,
    }
    let mut deferred_entries = Vec::new();
    let mut offsets_data_offset = None;
    let mut byte_counts_data_offset = None;

    // First pass: determine which tags are deferred and their offsets
    for tag in tags {
        let encoded = tag.value.encode(byte_order);
        if encoded.len() > inline_max {
            if tag.code == offsets_tag_code {
                offsets_data_offset = Some(deferred_offset);
            } else if tag.code == byte_counts_tag_code {
                byte_counts_data_offset = Some(deferred_offset);
            }
            let len = encoded.len() as u64;
            deferred_entries.push(DeferredEntry {
                data: encoded,
                offset: deferred_offset,
            });
            deferred_offset += len;
        }
    }

    // Second pass: write entries
    let mut deferred_idx = 0;
    for tag in tags {
        sink.write_all(&byte_order.write_u16(tag.code))?;
        sink.write_all(&byte_order.write_u16(tag.tag_type.to_code()))?;

        if is_bigtiff {
            sink.write_all(&byte_order.write_u64(tag.count))?;
        } else {
            let tag_count = u32::try_from(tag.count).map_err(|_| {
                crate::error::Error::Other(format!(
                    "classic TIFF tag {} count exceeds u32::MAX",
                    tag.code
                ))
            })?;
            sink.write_all(&byte_order.write_u32(tag_count))?;
        }

        let encoded = tag.value.encode(byte_order);
        if encoded.len() <= inline_max {
            let mut inline = vec![0u8; inline_max];
            inline[..encoded.len()].copy_from_slice(&encoded);
            sink.write_all(&inline)?;
        } else {
            let offset = deferred_entries[deferred_idx].offset;
            if is_bigtiff {
                sink.write_all(&byte_order.write_u64(offset))?;
            } else {
                sink.write_all(&byte_order.write_u32(classic_offset_u32(offset)?))?;
            }
            deferred_idx += 1;
        }
    }

    // Next-IFD pointer
    let next_ifd_pointer_offset = sink.stream_position()?;
    if is_bigtiff {
        sink.write_all(&byte_order.write_u64(0))?;
    } else {
        sink.write_all(&byte_order.write_u32(0))?;
    }

    // Write deferred data
    for entry in &deferred_entries {
        debug_assert_eq!(sink.stream_position()?, entry.offset);
        sink.write_all(&entry.data)?;
    }

    Ok(IfdWriteResult {
        ifd_offset,
        next_ifd_pointer_offset,
        offsets_tag_data_offset: offsets_data_offset,
        byte_counts_tag_data_offset: byte_counts_data_offset,
        is_bigtiff,
    })
}

/// Patch the block offsets array in a previously written IFD.
pub fn patch_block_offsets<W: Write + Seek>(
    sink: &mut W,
    byte_order: ByteOrder,
    is_bigtiff: bool,
    data_offset: u64,
    offsets: &[u64],
) -> Result<()> {
    sink.seek(SeekFrom::Start(data_offset))?;
    for &offset in offsets {
        if is_bigtiff {
            sink.write_all(&byte_order.write_u64(offset))?;
        } else {
            sink.write_all(&byte_order.write_u32(classic_offset_u32(offset)?))?;
        }
    }
    Ok(())
}

/// Patch the block byte-counts array in a previously written IFD.
pub fn patch_block_byte_counts<W: Write + Seek>(
    sink: &mut W,
    byte_order: ByteOrder,
    is_bigtiff: bool,
    data_offset: u64,
    byte_counts: &[u64],
) -> Result<()> {
    sink.seek(SeekFrom::Start(data_offset))?;
    for &count in byte_counts {
        if is_bigtiff {
            sink.write_all(&byte_order.write_u64(count))?;
        } else {
            sink.write_all(&byte_order.write_u32(classic_byte_count_u32(count)?))?;
        }
    }
    Ok(())
}

/// Patch the next-IFD pointer.
pub fn patch_next_ifd<W: Write + Seek>(
    sink: &mut W,
    byte_order: ByteOrder,
    is_bigtiff: bool,
    pointer_offset: u64,
    next_ifd: u64,
) -> Result<()> {
    sink.seek(SeekFrom::Start(pointer_offset))?;
    if is_bigtiff {
        sink.write_all(&byte_order.write_u64(next_ifd))?;
    } else {
        sink.write_all(&byte_order.write_u32(classic_offset_u32(next_ifd)?))?;
    }
    Ok(())
}

/// Parameters for building image tags.
#[derive(Debug)]
pub struct ImageTagParams<'a> {
    pub width: u32,
    pub height: u32,
    pub samples_per_pixel: u16,
    pub bits_per_sample: u16,
    pub sample_format: u16,
    pub compression: u16,
    pub photometric: u16,
    pub predictor: u16,
    pub planar_configuration: u16,
    pub subfile_type: u32,
    pub extra_tags: &'a [Tag],
    pub offsets_tag_code: u16,
    pub byte_counts_tag_code: u16,
    pub num_blocks: usize,
    pub layout_tags: &'a [Tag],
    pub is_bigtiff: bool,
}

/// Build standard TIFF tags for an image.
/// For BigTIFF, offset/bytecount arrays use Long8 instead of Long.
pub fn build_image_tags(p: &ImageTagParams<'_>) -> Vec<Tag> {
    let ImageTagParams {
        width,
        height,
        samples_per_pixel,
        bits_per_sample,
        sample_format,
        compression,
        photometric,
        predictor,
        planar_configuration,
        subfile_type,
        extra_tags,
        offsets_tag_code,
        byte_counts_tag_code,
        num_blocks,
        layout_tags,
        is_bigtiff,
    } = p;
    let mut tags = Vec::with_capacity(16 + extra_tags.len());

    if *subfile_type != 0 {
        tags.push(Tag::new(
            tiff_core::TAG_NEW_SUBFILE_TYPE,
            TagValue::Long(vec![*subfile_type]),
        ));
    }
    tags.push(Tag::new(
        tiff_core::TAG_IMAGE_WIDTH,
        TagValue::Long(vec![*width]),
    ));
    tags.push(Tag::new(
        tiff_core::TAG_IMAGE_LENGTH,
        TagValue::Long(vec![*height]),
    ));
    tags.push(Tag::new(
        tiff_core::TAG_BITS_PER_SAMPLE,
        TagValue::Short(vec![*bits_per_sample; *samples_per_pixel as usize]),
    ));
    tags.push(Tag::new(
        tiff_core::TAG_COMPRESSION,
        TagValue::Short(vec![*compression]),
    ));
    tags.push(Tag::new(
        tiff_core::TAG_PHOTOMETRIC_INTERPRETATION,
        TagValue::Short(vec![*photometric]),
    ));
    tags.push(Tag::new(
        tiff_core::TAG_SAMPLES_PER_PIXEL,
        TagValue::Short(vec![*samples_per_pixel]),
    ));
    if *planar_configuration != 1 {
        tags.push(Tag::new(
            tiff_core::TAG_PLANAR_CONFIGURATION,
            TagValue::Short(vec![*planar_configuration]),
        ));
    }
    if *predictor != 1 {
        tags.push(Tag::new(
            tiff_core::TAG_PREDICTOR,
            TagValue::Short(vec![*predictor]),
        ));
    }
    tags.push(Tag::new(
        tiff_core::TAG_SAMPLE_FORMAT,
        TagValue::Short(vec![*sample_format; *samples_per_pixel as usize]),
    ));

    for lt in *layout_tags {
        tags.push(lt.clone());
    }

    // Offset and bytecount placeholder arrays
    if *is_bigtiff {
        tags.push(Tag::new(
            *offsets_tag_code,
            TagValue::Long8(vec![0u64; *num_blocks]),
        ));
        tags.push(Tag::new(
            *byte_counts_tag_code,
            TagValue::Long8(vec![0u64; *num_blocks]),
        ));
    } else {
        tags.push(Tag::new(
            *offsets_tag_code,
            TagValue::Long(vec![0u32; *num_blocks]),
        ));
        tags.push(Tag::new(
            *byte_counts_tag_code,
            TagValue::Long(vec![0u32; *num_blocks]),
        ));
    }

    for tag in *extra_tags {
        tags.push(tag.clone());
    }

    tags.sort_by_key(|t| t.code);
    tags
}

/// Find the position of a tag's inline value within a written IFD.
pub fn find_inline_tag_value_offset(
    ifd_offset: u64,
    is_bigtiff: bool,
    tags: &[Tag],
    target_code: u16,
) -> Option<u64> {
    let count_size: u64 = if is_bigtiff { 8 } else { 2 };
    let entry_size: u64 = if is_bigtiff { 20 } else { 12 };
    // Value/offset field is the last 4 (classic) or 8 (BigTIFF) bytes of each entry.
    // Entry: code(2) + type(2) + count(4 or 8) + value(4 or 8)
    let value_field_offset: u64 = if is_bigtiff { 12 } else { 8 };

    for (i, tag) in tags.iter().enumerate() {
        if tag.code == target_code {
            return Some(ifd_offset + count_size + (i as u64) * entry_size + value_field_offset);
        }
    }
    None
}