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
use std::convert::TryFrom;
use std::fmt::Debug;
use std::io::{Read, Seek};
use smallvec::alloc::sync::Arc;
use crate::block::{BlockIndex, UncompressedBlock};
use crate::block::chunk::{Chunk, TileCoordinates};
use crate::compression::Compression;
use crate::error::{Error, Result, u64_to_usize, UnitResult};
use crate::io::{PeekRead, Tracking};
use crate::meta::{MetaData, OffsetTables};
use crate::meta::header::Header;
#[derive(Debug)]
pub struct Reader<R> {
meta_data: MetaData,
remaining_reader: PeekRead<Tracking<R>>, }
impl<R: Read + Seek> Reader<R> {
pub fn read_from_buffered(read: R, pedantic: bool) -> Result<Self> {
let mut remaining_reader = PeekRead::new(Tracking::new(read));
let meta_data = MetaData::read_validated_from_buffered_peekable(&mut remaining_reader, pedantic)?;
Ok(Self { meta_data, remaining_reader })
}
pub fn meta_data(&self) -> &MetaData { &self.meta_data }
pub fn headers(&self) -> &[Header] { &self.meta_data.headers }
pub fn into_meta_data(self) -> MetaData { self.meta_data }
pub fn all_chunks(mut self, pedantic: bool) -> Result<AllChunksReader<R>> {
let total_chunk_count = {
if pedantic {
let offset_tables = MetaData::read_offset_tables(&mut self.remaining_reader, &self.meta_data.headers)?;
validate_offset_tables(self.meta_data.headers.as_slice(), &offset_tables, self.remaining_reader.byte_position())?;
offset_tables.iter().map(|table| table.len()).sum()
}
else {
usize::try_from(MetaData::skip_offset_tables(&mut self.remaining_reader, &self.meta_data.headers)?)
.expect("too large chunk count for this machine")
}
};
Ok(AllChunksReader {
meta_data: self.meta_data,
remaining_chunks: 0 .. total_chunk_count,
remaining_bytes: self.remaining_reader,
pedantic
})
}
pub fn filter_chunks(mut self, pedantic: bool, mut filter: impl FnMut(&MetaData, TileCoordinates, BlockIndex) -> bool) -> Result<FilteredChunksReader<R>> {
let offset_tables = MetaData::read_offset_tables(&mut self.remaining_reader, &self.meta_data.headers)?;
if pedantic {
validate_offset_tables(
self.meta_data.headers.as_slice(), &offset_tables,
self.remaining_reader.byte_position()
)?;
}
let mut filtered_offsets = Vec::with_capacity(
(self.meta_data.headers.len() * 32).min(2*2048)
);
for (header_index, header) in self.meta_data.headers.iter().enumerate() { for (block_index, tile) in header.blocks_increasing_y_order().enumerate() { let data_indices = header.get_absolute_block_pixel_coordinates(tile.location)?;
let block = BlockIndex {
layer: header_index,
level: tile.location.level_index,
pixel_position: data_indices.position.to_usize("data indices start")?,
pixel_size: data_indices.size,
};
if filter(&self.meta_data, tile.location, block) {
filtered_offsets.push(offset_tables[header_index][block_index]) }
};
}
filtered_offsets.sort_unstable(); if pedantic {
if filtered_offsets.windows(2).any(|pair| pair[0] == pair[1]) {
return Err(Error::invalid("chunk offset table"))
}
}
Ok(FilteredChunksReader {
meta_data: self.meta_data,
expected_filtered_chunk_count: filtered_offsets.len(),
remaining_filtered_chunk_indices: filtered_offsets.into_iter(),
remaining_bytes: self.remaining_reader
})
}
}
fn validate_offset_tables(headers: &[Header], offset_tables: &OffsetTables, chunks_start_byte: usize) -> UnitResult {
let max_pixel_bytes: usize = headers.iter() .map(|header| header.max_pixel_file_bytes())
.sum();
let end_byte = chunks_start_byte + max_pixel_bytes;
let is_invalid = offset_tables.iter().flatten().map(|&u64| u64_to_usize(u64))
.any(|chunk_start| chunk_start < chunks_start_byte || chunk_start > end_byte);
if is_invalid { Err(Error::invalid("offset table")) }
else { Ok(()) }
}
#[derive(Debug)]
pub struct FilteredChunksReader<R> {
meta_data: MetaData,
expected_filtered_chunk_count: usize,
remaining_filtered_chunk_indices: std::vec::IntoIter<u64>,
remaining_bytes: PeekRead<Tracking<R>>,
}
#[derive(Debug)]
pub struct AllChunksReader<R> {
meta_data: MetaData,
remaining_chunks: std::ops::Range<usize>,
remaining_bytes: PeekRead<Tracking<R>>,
pedantic: bool,
}
#[derive(Debug)]
pub struct OnProgressChunksReader<R, F> {
chunks_reader: R,
decoded_chunks: usize,
callback: F,
}
pub trait ChunksReader: Sized + Iterator<Item=Result<Chunk>> + ExactSizeIterator {
fn meta_data(&self) -> &MetaData;
fn headers(&self) -> &[Header] { &self.meta_data().headers }
fn expected_chunk_count(&self) -> usize;
fn read_next_chunk(&mut self) -> Option<Result<Chunk>> { self.next() }
fn on_progress<F>(self, on_progress: F) -> OnProgressChunksReader<Self, F> where F: FnMut(f64) {
OnProgressChunksReader { chunks_reader: self, callback: on_progress, decoded_chunks: 0 }
}
fn decompress_parallel(
self, pedantic: bool,
mut insert_block: impl FnMut(&MetaData, UncompressedBlock) -> UnitResult
) -> UnitResult
{
let mut decompressor = match self.parallel_decompressor(pedantic) {
Err(old_self) => return old_self.decompress_sequential(pedantic, insert_block),
Ok(decompressor) => decompressor,
};
while let Some(block) = decompressor.next() {
insert_block(decompressor.meta_data(), block?)?;
}
debug_assert_eq!(decompressor.len(), 0, "compressed blocks left after decompressing all blocks");
Ok(())
}
fn parallel_decompressor(self, pedantic: bool) -> std::result::Result<ParallelBlockDecompressor<Self>, Self> {
let pool = threadpool::Builder::new()
.thread_name("OpenEXR Block Decompressor".to_string())
.build();
ParallelBlockDecompressor::new(self, pedantic, pool)
}
fn decompress_sequential(
self, pedantic: bool,
mut insert_block: impl FnMut(&MetaData, UncompressedBlock) -> UnitResult
) -> UnitResult
{
let mut decompressor = self.sequential_decompressor(pedantic);
while let Some(block) = decompressor.next() {
insert_block(decompressor.meta_data(), block?)?;
}
debug_assert_eq!(decompressor.len(), 0, "compressed blocks left after decompressing all blocks");
Ok(())
}
fn sequential_decompressor(self, pedantic: bool) -> SequentialBlockDecompressor<Self> {
SequentialBlockDecompressor { remaining_chunks_reader: self, pedantic }
}
}
impl<R, F> ChunksReader for OnProgressChunksReader<R, F> where R: ChunksReader, F: FnMut(f64) {
fn meta_data(&self) -> &MetaData { self.chunks_reader.meta_data() }
fn expected_chunk_count(&self) -> usize { self.chunks_reader.expected_chunk_count() }
}
impl<R, F> ExactSizeIterator for OnProgressChunksReader<R, F> where R: ChunksReader, F: FnMut(f64) {}
impl<R, F> Iterator for OnProgressChunksReader<R, F> where R: ChunksReader, F: FnMut(f64) {
type Item = Result<Chunk>;
fn next(&mut self) -> Option<Self::Item> {
self.chunks_reader.next().map(|item|{
{
let total_chunks = self.expected_chunk_count() as f64;
let callback = &mut self.callback;
callback(self.decoded_chunks as f64 / total_chunks);
}
self.decoded_chunks += 1;
item
})
.or_else(||{
debug_assert_eq!(
self.decoded_chunks, self.expected_chunk_count(),
"chunks reader finished but not all chunks are decompressed"
);
let callback = &mut self.callback;
callback(1.0);
None
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.chunks_reader.size_hint()
}
}
impl<R: Read + Seek> ChunksReader for AllChunksReader<R> {
fn meta_data(&self) -> &MetaData { &self.meta_data }
fn expected_chunk_count(&self) -> usize { self.remaining_chunks.end }
}
impl<R: Read + Seek> ExactSizeIterator for AllChunksReader<R> {}
impl<R: Read + Seek> Iterator for AllChunksReader<R> {
type Item = Result<Chunk>;
fn next(&mut self) -> Option<Self::Item> {
let next_chunk = self.remaining_chunks.next()
.map(|_| Chunk::read(&mut self.remaining_bytes, &self.meta_data));
if self.pedantic && next_chunk.is_none() && self.remaining_bytes.peek_u8().is_ok() {
return Some(Err(Error::invalid("end of file expected")));
}
next_chunk
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.remaining_chunks.len(), Some(self.remaining_chunks.len()))
}
}
impl<R: Read + Seek> ChunksReader for FilteredChunksReader<R> {
fn meta_data(&self) -> &MetaData { &self.meta_data }
fn expected_chunk_count(&self) -> usize { self.expected_filtered_chunk_count }
}
impl<R: Read + Seek> ExactSizeIterator for FilteredChunksReader<R> {}
impl<R: Read + Seek> Iterator for FilteredChunksReader<R> {
type Item = Result<Chunk>;
fn next(&mut self) -> Option<Self::Item> {
self.remaining_filtered_chunk_indices.next().map(|next_chunk_location|{
self.remaining_bytes.skip_to( usize::try_from(next_chunk_location)
.expect("too large chunk position for this machine")
)?;
let meta_data = &self.meta_data;
Chunk::read(&mut self.remaining_bytes, meta_data)
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.remaining_filtered_chunk_indices.len(), Some(self.remaining_filtered_chunk_indices.len()))
}
}
#[derive(Debug)]
pub struct SequentialBlockDecompressor<R: ChunksReader> {
remaining_chunks_reader: R,
pedantic: bool,
}
impl<R: ChunksReader> SequentialBlockDecompressor<R> {
pub fn meta_data(&self) -> &MetaData { self.remaining_chunks_reader.meta_data() }
pub fn decompress_next_block(&mut self) -> Option<Result<UncompressedBlock>> {
self.remaining_chunks_reader.read_next_chunk().map(|compressed_chunk|{
UncompressedBlock::decompress_chunk(compressed_chunk?, &self.remaining_chunks_reader.meta_data(), self.pedantic)
})
}
}
#[derive(Debug)]
pub struct ParallelBlockDecompressor<R: ChunksReader> {
remaining_chunks: R,
sender: flume::Sender<Result<UncompressedBlock>>,
receiver: flume::Receiver<Result<UncompressedBlock>>,
currently_decompressing_count: usize,
max_threads: usize,
shared_meta_data_ref: Arc<MetaData>,
pedantic: bool,
pool: threadpool::ThreadPool,
}
impl<R: ChunksReader> ParallelBlockDecompressor<R> {
pub fn new(chunks: R, pedantic: bool, pool: threadpool::ThreadPool) -> std::result::Result<Self, R> {
if chunks.meta_data().headers.iter()
.all(|head|head.compression == Compression::Uncompressed)
{
return Err(chunks);
}
let max_threads = pool.max_count().max(1).min(chunks.len()) + 2; let (send, recv) = flume::unbounded(); Ok(Self {
shared_meta_data_ref: Arc::new(chunks.meta_data().clone()),
currently_decompressing_count: 0,
remaining_chunks: chunks,
sender: send,
receiver: recv,
pedantic,
max_threads,
pool,
})
}
pub fn decompress_next_block(&mut self) -> Option<Result<UncompressedBlock>> {
assert_eq!( self.pool.panic_count(), 0,
"OpenEXR decompressor thread panicked \
(maybe a debug assertion failed) - \
Use non-parallel decompression to see panic messages."
);
while self.currently_decompressing_count < self.max_threads {
let block = self.remaining_chunks.next();
if let Some(block) = block {
let block = match block {
Ok(block) => block,
Err(error) => return Some(Err(error))
};
let sender = self.sender.clone();
let meta = self.shared_meta_data_ref.clone();
let pedantic = self.pedantic;
self.currently_decompressing_count += 1;
self.pool.execute(move || {
let decompressed_or_err = UncompressedBlock::decompress_chunk(
block, &meta, pedantic
);
let _ = sender.send(decompressed_or_err);
});
}
else {
break;
}
}
if self.currently_decompressing_count > 0 {
let next = self.receiver.recv()
.expect("all decompressing senders hung up but more messages were expected");
self.currently_decompressing_count -= 1;
Some(next)
}
else {
debug_assert!(self.receiver.try_recv().is_err(), "uncompressed chunks left in channel after decompressing all chunks"); debug_assert_eq!(self.len(), 0, "compressed chunks left after decompressing all chunks");
None
}
}
pub fn meta_data(&self) -> &MetaData { self.remaining_chunks.meta_data() }
}
impl<R: ChunksReader> ExactSizeIterator for SequentialBlockDecompressor<R> {}
impl<R: ChunksReader> Iterator for SequentialBlockDecompressor<R> {
type Item = Result<UncompressedBlock>;
fn next(&mut self) -> Option<Self::Item> { self.decompress_next_block() }
fn size_hint(&self) -> (usize, Option<usize>) { self.remaining_chunks_reader.size_hint() }
}
impl<R: ChunksReader> ExactSizeIterator for ParallelBlockDecompressor<R> {}
impl<R: ChunksReader> Iterator for ParallelBlockDecompressor<R> {
type Item = Result<UncompressedBlock>;
fn next(&mut self) -> Option<Self::Item> { self.decompress_next_block() }
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = self.remaining_chunks.len() + self.currently_decompressing_count;
(remaining, Some(remaining))
}
}