exr 0.6.0

Read and write OpenEXR files without any unsafe code
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818

//! Read and write all supported aspects of an exr image, including deep data and multiresolution levels.
//! Use `exr::image::simple` if you do not need deep data or resolution levels.
//!
//! __This module is currently under construction.__
//! It will be made public as soon as deep data is supported.

// Tasks:
// - [x] fix channel sampling allocation size
// - [ ] nice api to construct and inspect images
//      - [ ] validation
// - [ ] deep data

#![doc(hidden)]

use smallvec::SmallVec;
use half::f16;
use crate::io::*;
use crate::meta::*;
use crate::meta::attributes::*;
use crate::error::{Result, PassiveResult, Error};
use crate::math::*;
use std::io::{Seek, BufReader, BufWriter};
use crate::io::Data;
use crate::image::{Line, LineIndex};

// FIXME this needs some of the changes that were made in simple.rs !!!

/// Specify how to write an exr image.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct WriteOptions {

    /// Enable multicore compression.
    pub parallel_compression: bool,

    /// If enabled, writing an image throws errors
    /// for files that may look invalid to other exr readers.
    pub pedantic: bool,
}

/// Specify how to read an exr image.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ReadOptions {

    /// Enable multicore decompression.
    pub parallel_decompression: bool,
}

/// An exr image.
///
/// Supports all possible exr image features.
/// An exr image may contain multiple layers.
/// All meta data is encoded in this image,
/// including custom attributes.
#[derive(Clone, PartialEq, Debug)]
pub struct Image {

    /// All layers contained in the image file
    pub layers: Layers,

    /// The rectangle positioned anywhere in the infinite 2D space that
    /// clips all contents of the file, limiting what should be rendered.
    pub display_window: IntRect,

    /// Aspect ratio of each pixel in this layer.
    pub pixel_aspect: f32,
}

pub type Layers = SmallVec<[Layer; 3]>;

/// A single layer of an exr image.
/// Contains meta data and actual pixel information of the channels.
#[derive(Clone, PartialEq, Debug)]
pub struct Layer {

    /// The name of the layer.
    /// This is optional for files with only one layer.
    pub name: Option<Text>,

    /// The remaining attributes which are not already in the `Layer`.
    /// Includes custom attributes.
    pub attributes: Attributes,

    /// The rectangle that positions this layer
    /// within the global infinite 2D space of the file.
    pub data_window: IntRect,

    /// Part of the perspective projection. Default should be `(0, 0)`.
    pub screen_window_center: Vec2<f32>,

    /// Part of the perspective projection. Default should be `1`.
    pub screen_window_width: f32,

    /// In what order the tiles of this header occur in the file.
    pub line_order: LineOrder,

    /// How the pixel data of all channels in this layer is compressed. May be `Compression::Uncompressed`.
    pub compression: Compression,

    /// Describes how the pixels of this layer are divided into smaller blocks in the file.
    /// A single block can be loaded without processing all bytes of a file.
    ///
    /// Also describes whether a file contains multiple resolution levels: mip maps or rip maps.
    /// This allows loading not the full resolution, but the smallest sensible resolution.
    pub blocks: Blocks,

    /// List of channels in this layer.
    /// Contains the actual pixel data of the image.
    pub channels: Channels,
}


pub type Channels = SmallVec<[Channel; 5]>;

/// Contains an arbitrary list of pixel data.
/// Each channel can have a different pixel type,
/// either f16, f32, or u32.
#[derive(Clone, Debug, PartialEq)]
pub struct Channel {

    /// One of "R", "G", or "B" most of the time.
    pub name: Text,

    /// Actual pixel data.
    pub content: ChannelData,

    /// Are the samples in this channel in linear color space?
    pub is_linear: bool,

    /// How many of the samples are skipped compared to the other channels in this layer.
    ///
    /// Can be used for chroma subsampling for manual lossy data compression.
    /// Values other than 1 are allowed only in flat, scan-line based images.
    /// If an image is deep or tiled, x and y sampling rates for all of its channels must be 1.
    pub sampling: Vec2<usize>,
}

/// Actual pixel data in a channel. Is either one of f16, f32, or u32.
#[derive(Clone, Debug, PartialEq)]
pub enum ChannelData {

    /// The representation of 16-bit floating-point numbers is analogous to IEEE 754,
    /// but with 5 exponent bits and 10 bits for the fraction.
    ///
    /// Currently this crate is using the `half` crate, which is an implementation of the IEEE 754-2008 standard, meeting that requirement.
    F16(SampleMaps<f16>),

    /// 32-bit float samples.
    F32(SampleMaps<f32>),

    /// 32-bit unsigned int samples.
    /// Used for segmentation of layers.
    U32(SampleMaps<u32>),
}

/// Contains either deep data or flat data.
#[derive(Clone, Debug, PartialEq)]
pub enum SampleMaps<Sample> {

    /// Each pixel has one value per channel.
    Flat (Levels<FlatSamples<Sample>>),

    /// Each pixel has an arbitrary number of samples per channel.
    Deep (Levels<DeepSamples<Sample>>),
}

/// The different resolution levels of the layer.
// FIXME should be descending and starting with full-res instead!
#[derive(Clone, PartialEq)]
pub enum Levels<Samples> {

    /// Just the full resolution image.
    Singular(SampleBlock<Samples>),

    /// In addition to the full resolution image,
    /// this layer also contains smaller versions with the same aspect ratio.
    Mip(LevelMaps<Samples>),

    /// In addition to the full resolution image,
    /// this layer also contains smaller versions,
    /// and each smaller version has further versions with varying aspect ratios.
    Rip(RipMaps<Samples>),
}

pub type LevelMaps<Samples> = Vec<SampleBlock<Samples>>;

/// In addition to the full resolution image,
/// this layer also contains smaller versions,
/// and each smaller version has further versions with varying aspect ratios.
#[derive(Clone, PartialEq, Debug)]
pub struct RipMaps<Samples> {

    /// The actual pixel data
    pub map_data: LevelMaps<Samples>,

    /// The number of levels that were generated along the x-axis and y-axis.
    pub level_count: Vec2<usize>,
}

/// The actual pixel data, finally.
/// Contains a vector of samples.
#[derive(Clone, PartialEq, Debug)]
pub struct SampleBlock<Samples> {

    /// The dimensions of this sample collection
    pub resolution: Vec2<usize>,

    /// The actual pixel samples
    pub samples: Samples
}

/// The samples of a 2D grid, flattened in a single vector.
/// The vector contains each row, one after another.
/// A specific pixel value can be found at the index `samples[y_index * width + x_index]`.
pub type FlatSamples<Sample> = Vec<Sample>;

/// A collection of deep sample lines.
// TODO do not store line by line in a separate vector!
pub type DeepSamples<Sample> = Vec<DeepLine<Sample>>;


/// A single line of deep data.
#[derive(Clone, Debug, PartialEq)]
pub struct DeepLine<Sample> {

    /// The samples of this row of pixels.
    // TODO do not store line by line in a separate vector!
    pub samples: Vec<Sample>,

    /// For each column, this specifies the index in `samples` where to find the next sample.
    /// Therefore, `samples[index_table[column_index - 1]]` contains the start position of the sample.
    pub index_table: Vec<u32>,
}


impl Default for WriteOptions {
    fn default() -> Self { Self::high() }
}

impl Default for ReadOptions {
    fn default() -> Self { Self::high() }
}


impl WriteOptions {

    /// Higher speed, but higher memory requirements, and __higher risk of incompatibility to other exr readers__.
    pub fn higher() -> Self {
        WriteOptions {
            parallel_compression: true,
            pedantic: false
        }
    }

    /// Higher speed but also higher memory requirements.
    pub fn high() -> Self {
        WriteOptions {
            parallel_compression: true,
            pedantic: true,
        }
    }

    /// Lower speed but also lower memory requirements.
    pub fn low() -> Self {
        WriteOptions {
            parallel_compression: false,
            pedantic: true,
        }
    }
}

impl ReadOptions {

    /// Higher speed but also higher memory requirements.
    pub fn high() -> Self { ReadOptions { parallel_decompression: true } }

    /// Lower speed but also lower memory requirements.
    pub fn low() -> Self { ReadOptions { parallel_decompression: false } }
}


impl<S> std::fmt::Debug for Levels<S> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Levels::Singular(image) => write!(
                formatter, "Singular ([{}x{}])",
                image.resolution.0, image.resolution.1
            ),
            Levels::Mip(levels) => write!(
                formatter, "Mip ({:?})",
                levels.iter().map(|level| level.resolution).collect::<Vec<_>>(),
            ),
            Levels::Rip(maps) => write!(
                formatter, "Rip ({:?})",
                maps.map_data.iter().map(|level| level.resolution).collect::<Vec<_>>()
            )
        }
    }
}


impl Image {

    /// Read the exr image from a file.
    /// Use `read_from_unbuffered` instead, if you do not have a file.
    #[must_use]
    pub fn read_from_file(path: impl AsRef<std::path::Path>, options: ReadOptions) -> Result<Self> {
        Self::read_from_unbuffered(std::fs::File::open(path)?, options)
    }

    /// Buffer the reader and then read the exr image from it.
    /// Use `read_from_buffered` instead, if your reader is an in-memory reader.
    /// Use `read_from_file` instead, if you have a file path.
    #[must_use]
    pub fn read_from_unbuffered(unbuffered: impl Read + Send, options: ReadOptions) -> Result<Self> {
        Self::read_from_buffered(BufReader::new(unbuffered), options)
    }

    /// Read the exr image from a reader.
    /// Use `read_from_file` instead, if you have a file path.
    /// Use `read_from_unbuffered` instead, if this is not an in-memory reader.
    #[must_use]
    pub fn read_from_buffered(read: impl Read + Send, options: ReadOptions) -> Result<Self> {
        crate::image::read_all_lines_from_buffered(read, options.parallel_decompression, Image::allocate, Image::insert_line)
    }

    /// Write the exr image to a file.
    /// Use `write_to_unbuffered` instead if you do not have a file.
    #[must_use]
    pub fn write_to_file(&self, path: impl AsRef<std::path::Path>, options: WriteOptions) -> PassiveResult {
        self.write_to_unbuffered(std::fs::File::create(path)?, options)
    }

    /// Buffer the reader and then write the exr image to it.
    /// Use `read_from_buffered` instead, if your reader is an in-memory writer.
    /// Use `read_from_file` instead, if you have a file path.
    /// If your writer cannot seek, you can write to an in-memory vector of bytes first, using `write_to_buffered`.
    #[must_use]
    pub fn write_to_unbuffered(&self, unbuffered: impl Write + Seek, options: WriteOptions) -> PassiveResult {
        self.write_to_buffered(BufWriter::new(unbuffered), options)
    }

    /// Write the exr image from a reader.
    /// Use `read_from_file` instead, if you have a file path.
    /// Use `read_from_unbuffered` instead, if this is not an in-memory writer.
    /// If your writer cannot seek, you can write to an in-memory vector of bytes first.
    #[must_use]
    pub fn write_to_buffered(&self, write: impl Write + Seek, options: WriteOptions) -> PassiveResult {
        crate::image::write_all_lines_to_buffered(
            write, options.parallel_compression, options.pedantic, self.infer_meta_data(),
            |location, write| {
                self.extract_line(location, write)
            }
        )
    }
}

impl Image {

    /// Allocate an image ready to be filled with pixel data.
    pub fn allocate(headers: &[Header]) -> Result<Self> {
        let display_window = headers.iter()
            .map(|header| header.display_window)
            .next().unwrap_or(IntRect::zero()); // default value if no headers are found

        let pixel_aspect = headers.iter()
            .map(|header| header.pixel_aspect)
            .next().unwrap_or(1.0); // default value if no headers are found

        let headers : Result<_> = headers.iter().map(Layer::allocate).collect();

        Ok(Image {
            layers: headers?,
            display_window,
            pixel_aspect
        })
    }

    /// Insert one line of pixel data into this image.
    /// Returns an error for invalid index or line contents.
    pub fn insert_line(&mut self, line: Line<'_>) -> PassiveResult {
        debug_assert_ne!(line.location.width, 0, "linde index bug");

        let layer = self.layers.get_mut(line.location.layer)
            .ok_or(Error::invalid("chunk layer index"))?;

        layer.insert_line(line)
    }

    /// Read one line of pixel data from this channel.
    /// Panics for an invalid index or write error.
    pub fn extract_line(&self, index: LineIndex, write: &mut impl Write) {
        debug_assert_ne!(index.width, 0, "line index bug");

        let layer = self.layers.get(index.layer)
            .expect("invalid layer index");

        layer.extract_line(index, write)
    }

    /// Create the meta data that describes this image.
    /// May produce invalid meta data. The meta data will be validated just before writing.
    pub fn infer_meta_data(&self) -> MetaData {
        let headers: Headers = self.layers.iter()
            .map(|layer| layer.infer_header(self.display_window, self.pixel_aspect))
            .collect();

        MetaData::new(headers)
    }
}



impl Layer {

    /// Allocate an layer ready to be filled with pixel data.
    pub fn allocate(header: &Header) -> Result<Self> {
        Ok(Layer {
            data_window: header.data_window,
            screen_window_center: header.screen_window_center,
            screen_window_width: header.screen_window_width,
            name: header.name.clone(),
            attributes: header.custom_attributes.clone(),
            channels: header.channels.list.iter().map(|channel| Channel::allocate(header, channel)).collect(),
            compression: header.compression,
            blocks: header.blocks,
            line_order: header.line_order,
        })
    }

    /// Insert one line of pixel data into this layer.
    /// Returns an error for invalid index or line contents.
    pub fn insert_line(&mut self, line: Line<'_>) -> PassiveResult {
        debug_assert!(line.location.position.0 + line.location.width <= self.data_window.size.0, "line index bug");
        debug_assert!(line.location.position.1 < self.data_window.size.1, "line index bug");

        self.channels.get_mut(line.location.channel)
            .expect("invalid channel index")
            .insert_line(line)
    }

    /// Read one line of pixel data from this layer.
    /// Panics for an invalid index or write error.
    pub fn extract_line(&self, index: LineIndex, write: &mut impl Write) {
        debug_assert!(index.position.0 + index.width <= self.data_window.size.0, "line index bug");
        debug_assert!(index.position.1 < self.data_window.size.1, "line index bug");

        self.channels.get(index.channel)
            .expect("invalid channel index")
            .extract_line(index, write)
    }

    /// Create the meta data that describes this layer.
    /// May produce invalid meta data. The meta data will be validated just before writing.
    pub fn infer_header(&self, display_window: IntRect, pixel_aspect: f32) -> Header {
        let chunk_count = compute_chunk_count(
            self.compression, self.data_window, self.blocks
        );

        Header {
            chunk_count,

            name: self.name.clone(),
            data_window: self.data_window,
            screen_window_center: self.screen_window_center,
            screen_window_width: self.screen_window_width,
            compression: self.compression,
            blocks: self.blocks,
            channels: ChannelList::new(self.channels.iter().map(Channel::infer_channel_attribute).collect()),
            line_order: self.line_order,

            custom_attributes: self.attributes.clone(),
            display_window, pixel_aspect,

            // TODO deep data:
            deep_data_version: None,
            max_samples_per_pixel: None,
            deep: false
        }
    }


}

impl Channel {

    /// Allocate a channel ready to be filled with pixel data.
    pub fn allocate(header: &Header, channel: &attributes::Channel) -> Self {
        Channel {
            name: channel.name.clone(),
            is_linear: channel.is_linear,
            sampling: channel.sampling,

            content: match channel.pixel_type {
                PixelType::F16 => ChannelData::F16(SampleMaps::allocate(header, channel)),
                PixelType::F32 => ChannelData::F32(SampleMaps::allocate(header, channel)),
                PixelType::U32 => ChannelData::U32(SampleMaps::allocate(header, channel)),
            },
        }
    }

    /// Insert one line of pixel data into this channel.
    pub fn insert_line(&mut self, line: Line<'_>) -> PassiveResult {
        match &mut self.content {
            ChannelData::F16(maps) => maps.insert_line(line),
            ChannelData::F32(maps) => maps.insert_line(line),
            ChannelData::U32(maps) => maps.insert_line(line),
        }
    }

    /// Read one line of pixel data from this channel.
    /// Panics for an invalid index or write error.
    pub fn extract_line(&self, index: LineIndex, block: &mut impl Write) {
        match &self.content {
            ChannelData::F16(maps) => maps.extract_line(index, block),
            ChannelData::F32(maps) => maps.extract_line(index, block),
            ChannelData::U32(maps) => maps.extract_line(index, block),
        }
    }

    /// Create the meta data that describes this channel.
    pub fn infer_channel_attribute(&self) -> attributes::Channel {
        attributes::Channel {
            pixel_type: match self.content {
                ChannelData::F16(_) => PixelType::F16,
                ChannelData::F32(_) => PixelType::F32,
                ChannelData::U32(_) => PixelType::U32,
            },

            name: self.name.clone(),
            is_linear: self.is_linear,
            sampling: self.sampling,
        }
    }
}


impl<Sample: Data + std::fmt::Debug> SampleMaps<Sample> {

    /// Allocate a collection of resolution maps ready to be filled with pixel data.
    pub fn allocate(header: &Header, channel: &attributes::Channel) -> Self {
        if header.deep {
            SampleMaps::Deep(Levels::allocate(header, channel))
        }
        else {
            SampleMaps::Flat(Levels::allocate(header, channel))
        }
    }

    /// Insert one line of pixel data into a level.
    pub fn insert_line(&mut self, line: Line<'_>) -> PassiveResult {
        match self {
            SampleMaps::Deep(ref mut levels) => levels.insert_line(line),
            SampleMaps::Flat(ref mut levels) => levels.insert_line(line),
        }
    }

    /// Read one line of pixel data from a level.
    /// Panics for an invalid index or write error.
    pub fn extract_line(&self, index: LineIndex, block: &mut impl Write) {
        match self {
            SampleMaps::Deep(ref levels) => levels.extract_line(index, block),
            SampleMaps::Flat(ref levels) => levels.extract_line(index, block),
        }
    }

    pub fn as_flat_samples(&self) -> Option<&Levels<FlatSamples<Sample>>> {
        match self {
            SampleMaps::Flat(ref levels) => Some(levels),
            _ => None
        }
    }

    pub fn as_deep_samples(&self) -> Option<&Levels<DeepSamples<Sample>>> {
        match self {
            SampleMaps::Deep(ref levels) => Some(levels),
            _ => None
        }
    }

    pub fn level_mode(&self) -> LevelMode {
        match self {
            SampleMaps::Flat(levels) => levels.level_mode(),
            SampleMaps::Deep(levels) => levels.level_mode(),
        }
    }
}

impl<S: Samples> Levels<S> {

    /// Allocate a collection of resolution maps ready to be filled with pixel data.
    pub fn allocate(header: &Header, channel: &attributes::Channel) -> Self {
        let data_size = header.data_window.size / channel.sampling;

        if let Blocks::Tiles(tiles) = &header.blocks {
            let round = tiles.rounding_mode;

            match tiles.level_mode {
                LevelMode::Singular => Levels::Singular(SampleBlock::allocate(data_size)),

                LevelMode::MipMap => Levels::Mip(
                    mip_map_levels(round, data_size)
                        .map(|(_, level_size)| SampleBlock::allocate(level_size)).collect()
                ),

                // TODO put this into Levels::new(..) ?
                LevelMode::RipMap => Levels::Rip({
                    let level_count_x = compute_level_count(round, data_size.0);
                    let level_count_y = compute_level_count(round, data_size.1);
                    let maps = rip_map_levels(round, data_size)
                        .map(|(_, level_size)| SampleBlock::allocate(level_size)).collect();

                    RipMaps {
                        map_data: maps,
                        level_count: Vec2(level_count_x, level_count_y)
                    }
                })
            }
        }

        // scan line blocks never have mip maps
        else {
            Levels::Singular(SampleBlock::allocate(data_size))
        }
    }

    /// Insert one line of pixel data into a level.
    pub fn insert_line(&mut self, line: Line<'_>) -> PassiveResult {
        self.get_level_mut(line.location.level)?.insert_line(line)
    }

    /// Read one line of pixel data from a level.
    /// Panics for an invalid index or write error.
    pub fn extract_line(&self, index: LineIndex, write: &mut impl Write) {
        self.get_level(index.level)
            .expect("invalid level index")
            .extract_line(index, write)
    }

    pub fn get_level(&self, level: Vec2<usize>) -> Result<&SampleBlock<S>> {
        match self {
            Levels::Singular(ref block) => {
                debug_assert_eq!(level, Vec2(0,0), "singular image cannot write leveled blocks bug");
                Ok(block)
            },

            Levels::Mip(block) => {
                debug_assert_eq!(level.0, level.1, "mip map levels must be equal on x and y bug");
                block.get(level.0).ok_or(Error::invalid("block mip level index"))
            },

            Levels::Rip(block) => {
                block.get_by_level(level).ok_or(Error::invalid("block rip level index"))
            }
        }
    }

    pub fn get_level_mut(&mut self, level: Vec2<usize>) -> Result<&mut SampleBlock<S>> {
        match self {
            Levels::Singular(ref mut block) => {
                debug_assert_eq!(level, Vec2(0,0), "singular image cannot write leveled blocks bug");
                Ok(block)
            },

            Levels::Mip(block) => {
                debug_assert_eq!(level.0, level.1, "mip map levels must be equal on x and y bug");
                block.get_mut(level.0).ok_or(Error::invalid("block mip level index"))
            },

            Levels::Rip(block) => {
                block.get_by_level_mut(level).ok_or(Error::invalid("block rip level index"))
            }
        }
    }

    pub fn largest(&self) -> Result<&SampleBlock<S>> {
        self.get_level(Vec2(0,0))
    }

    pub fn as_slice(&self) -> &[SampleBlock<S>] {
        match self {
            Levels::Singular(ref data) => std::slice::from_ref(data),
            Levels::Mip(ref maps) => maps,
            Levels::Rip(ref rip_map) => &rip_map.map_data,
        }
    }


    pub fn level_mode(&self) -> LevelMode {
        match self {
            Levels::Singular(_) => LevelMode::Singular,
            Levels::Mip(_) => LevelMode::MipMap,
            Levels::Rip(_) => LevelMode::RipMap,
        }
    }
}


impl<S: Samples> SampleBlock<S> {

    /// Allocate a sample block ready to be filled with pixel data.
    pub fn allocate(resolution: Vec2<usize>) -> Self {
        SampleBlock { resolution, samples: S::allocate(resolution) }
    }

    /// Insert one line of pixel data into this sample block.
    pub fn insert_line(&mut self, line: Line<'_>) -> PassiveResult {
        debug_assert_ne!(line.location.width, 0, "line index bug");

        if line.location.position.0 + line.location.width > self.resolution.0 {
            return Err(Error::invalid("data block x coordinate"))
        }

        if line.location.position.1 > self.resolution.1 {
            return Err(Error::invalid("data block y coordinate"))
        }

        self.samples.insert_line(line, self.resolution.0)
    }

    /// Read one line of pixel data from this sample block.
    /// Panics for an invalid index or write error.
    pub fn extract_line(&self, index: LineIndex, write: &mut impl Write) {
        debug_assert!(index.position.0 + index.width <= self.resolution.0, "line index bug");
        debug_assert!(index.position.1 < self.resolution.1, "line index bug");
        debug_assert_ne!(index.width, 0, "line index bug");

        self.samples.extract_line(index, write, self.resolution.0)
    }
}

pub trait Samples {

    /// Allocate a sample block ready to be filled with pixel data.
    fn allocate(resolution: Vec2<usize>) -> Self;

    /// Insert one line of pixel data into this sample collection.
    fn insert_line(&mut self, line: Line<'_>, image_width: usize) -> PassiveResult;

    /// Read one line of pixel data from this sample collection.
    /// Panics for an invalid index or write error.
    fn extract_line(&self, index: LineIndex, write: &mut impl Write, image_width: usize);
}

impl<Sample: crate::io::Data> Samples for DeepSamples<Sample> {
    fn allocate(resolution: Vec2<usize>) -> Self {
        vec![
            DeepLine { samples: Vec::new(), index_table: vec![0; resolution.0] };
            resolution.1
        ]
    }

    fn insert_line(&mut self, _line: Line<'_>, _width: usize) -> PassiveResult {
//        debug_assert_ne!(image_width, 0);
//        debug_assert_ne!(length, 0);

        unimplemented!("deep data not supported yet");

        // TODO err on invalid tile position
//        self[_position.1 as usize] = DeepLine {
//            samples: Sample::read_vec(read, length, 1024*1024*1024)?, // FIXME where tiles, will not be hole line
//            index_table:
//        };
//
//        Ok(())
    }

    fn extract_line(&self, _index: LineIndex, _write: &mut impl Write, image_width: usize) {
        debug_assert_ne!(image_width, 0, "deep image width bug");
        unimplemented!("deep data not supported yet");
    }
}

impl<Sample: crate::io::Data + Default + Clone + std::fmt::Debug> Samples for FlatSamples<Sample> {
    fn allocate(resolution: Vec2<usize>) -> Self {
        let resolution = (resolution.0, resolution.1);
        vec![Sample::default(); resolution.0 * resolution.1]
    }

    fn insert_line(&mut self, line: Line<'_>, image_width: usize) -> PassiveResult {
        debug_assert_ne!(image_width, 0, "image width calculation bug");
        debug_assert_ne!(line.location.width, 0, "line width calculation bug");

        let start_index = line.location.position.1 * image_width + line.location.position.0;
        let end_index = start_index + line.location.width;

        line.read_samples(&mut self[start_index .. end_index])
    }

    fn extract_line(&self, index: LineIndex, write: &mut impl Write, image_width: usize) {
        debug_assert_ne!(image_width, 0, "image width calculation bug");

        let start_index = index.position.1 * image_width + index.position.0;
        let end_index = start_index + index.width;

        LineIndex::write_samples(&self[start_index .. end_index], write)
            .expect("writing line bytes failed");
    }
}

impl<Samples> RipMaps<Samples> {

    /// Flatten the 2D level index to a one dimensional index.
    pub fn get_level_index(&self, level: Vec2<usize>) -> usize {
        self.level_count.0 * level.1 + level.0
    }

    /// Return a level by level index. Level `0` has the largest resolution.
    pub fn get_by_level(&self, level: Vec2<usize>) -> Option<&SampleBlock<Samples>> {
        self.map_data.get(self.get_level_index(level))
    }

    /// Return a mutable level reference by level index. Level `0` has the largest resolution.
    pub fn get_by_level_mut(&mut self, level: Vec2<usize>) -> Option<&mut SampleBlock<Samples>> {
        let index = self.get_level_index(level);
        self.map_data.get_mut(index)
    }
}