1
2//! Lossy compression for F32 data, but lossless compression for U32 and F16 data.
3// see https://github.com/AcademySoftwareFoundation/openexr/blob/master/OpenEXR/IlmImf/ImfPxr24Compressor.cpp
4
5// This compressor is based on source code that was contributed to
6// OpenEXR by Pixar Animation Studios. The compression method was
7// developed by Loren Carpenter.
8
9
10// The compressor preprocesses the pixel data to reduce entropy, and then calls zlib.
11// Compression of HALF and UINT channels is lossless, but compressing
12// FLOAT channels is lossy: 32-bit floating-point numbers are converted
13// to 24 bits by rounding the significand to 15 bits.
14//
15// When the compressor is invoked, the caller has already arranged
16// the pixel data so that the values for each channel appear in a
17// contiguous block of memory. The compressor converts the pixel
18// values to unsigned integers: For UINT, this is a no-op. HALF
19// values are simply re-interpreted as 16-bit integers. FLOAT
20// values are converted to 24 bits, and the resulting bit patterns
21// are interpreted as integers. The compressor then replaces each
22// value with the difference between the value and its left neighbor.
23// This turns flat fields in the image into zeroes, and ramps into
24// strings of similar values. Next, each difference is split into
25// 2, 3 or 4 bytes, and the bytes are transposed so that all the
26// most significant bytes end up in a contiguous block, followed
27// by the second most significant bytes, and so on. The resulting
28// string of bytes is compressed with zlib.
29
30use super::*;
31
32use crate::error::Result;
33use lebe::io::ReadPrimitive;
34
35
36// scanline decompression routine, see https://github.com/openexr/openexr/blob/master/OpenEXR/IlmImf/ImfScanLineInputFile.cpp
37// 1. Uncompress the data, if necessary (If the line is uncompressed, it's in XDR format, regardless of the compressor's output format.)
38// 3. Convert one scan line's worth of pixel data back from the machine-independent representation
39// 4. Fill the frame buffer with pixel data, respective to sampling and whatnot
40
41
42#[cfg_attr(target_endian = "big", allow(unused, unreachable_code))]
43pub fn compress(channels: &ChannelList, remaining_bytes: ByteVec, area: IntegerBounds) -> Result<ByteVec> {
44 #[cfg(target_endian = "big")] {
45 return Err(Error::unsupported(
46 "PXR24 compression method not supported yet on big endian processor architecture"
47 ))
48 }
49
50 if remaining_bytes.is_empty() { return Ok(Vec::new()); }
51
52 // see https://github.com/AcademySoftwareFoundation/openexr/blob/3bd93f85bcb74c77255f28cdbb913fdbfbb39dfe/OpenEXR/IlmImf/ImfTiledOutputFile.cpp#L750-L842
53 let remaining_bytes = super::convert_current_to_little_endian(remaining_bytes, channels, area);
54 let mut remaining_bytes = remaining_bytes.as_slice(); // TODO less allocation
55
56 let bytes_per_pixel: usize = channels.list.iter()
57 .map(|channel| match channel.sample_type {
58 SampleType::F16 => 2, SampleType::F32 => 3, SampleType::U32 => 4,
59 })
60 .sum();
61
62 let mut raw = vec![0_u8; bytes_per_pixel * area.size.area()];
63
64 {
65 let mut write = raw.as_mut_slice();
66
67 // TODO this loop should be an iterator in the `IntegerBounds` class, as it is used in all compressio methods
68 for y in area.position.1..area.end().1 {
69 for channel in &channels.list {
70 if mod_p(y, usize_to_i32(channel.sampling.1)) != 0 { continue; }
71
72 // this apparently can't be a closure in Rust 1.43 due to borrowing ambiguity
73 let sample_count_x = channel.subsampled_resolution(area.size).0;
74 macro_rules! split_off_write_slice { () => {{
75 let (slice, rest) = write.split_at_mut(sample_count_x);
76 write = rest;
77 slice
78 }}; }
79
80 let mut previous_pixel: u32 = 0;
81
82 match channel.sample_type {
83 SampleType::F16 => {
84 let out_byte_tuples = split_off_write_slice!().iter_mut()
85 .zip(split_off_write_slice!());
86
87 for (out_byte_0, out_byte_1) in out_byte_tuples {
88 let pixel = u16::read_from_native_endian(&mut remaining_bytes).unwrap() as u32;
89 let [byte_1, byte_0] = (pixel.wrapping_sub(previous_pixel) as u16).to_ne_bytes();
90
91 *out_byte_0 = byte_0;
92 *out_byte_1 = byte_1;
93 previous_pixel = pixel;
94 }
95 },
96
97 SampleType::U32 => {
98 let out_byte_quadruplets = split_off_write_slice!().iter_mut()
99 .zip(split_off_write_slice!())
100 .zip(split_off_write_slice!())
101 .zip(split_off_write_slice!());
102
103 for (((out_byte_0, out_byte_1), out_byte_2), out_byte_3) in out_byte_quadruplets {
104 let pixel = u32::read_from_native_endian(&mut remaining_bytes).unwrap();
105 let [byte_3, byte_2, byte_1, byte_0] = pixel.wrapping_sub(previous_pixel).to_ne_bytes();
106
107 *out_byte_0 = byte_0;
108 *out_byte_1 = byte_1;
109 *out_byte_2 = byte_2;
110 *out_byte_3 = byte_3;
111 previous_pixel = pixel;
112 }
113 },
114
115 SampleType::F32 => {
116 let out_byte_triplets = split_off_write_slice!().iter_mut()
117 .zip(split_off_write_slice!())
118 .zip(split_off_write_slice!());
119
120 for ((out_byte_0, out_byte_1), out_byte_2) in out_byte_triplets {
121 let pixel = f32_to_f24(f32::read_from_native_endian(&mut remaining_bytes).unwrap());
122 let [byte_2, byte_1, byte_0, _] = pixel.wrapping_sub(previous_pixel).to_ne_bytes();
123 previous_pixel = pixel;
124
125 *out_byte_0 = byte_0;
126 *out_byte_1 = byte_1;
127 *out_byte_2 = byte_2;
128 }
129 },
130 }
131 }
132 }
133
134 debug_assert_eq!(write.len(), 0, "bytes left after compression");
135 }
136
137 Ok(miniz_oxide::deflate::compress_to_vec_zlib(raw.as_slice(), 4))
138}
139
140#[cfg_attr(target_endian = "big", allow(unused, unreachable_code))]
141pub fn decompress(channels: &ChannelList, bytes: ByteVec, area: IntegerBounds, expected_byte_size: usize, pedantic: bool) -> Result<ByteVec> {
142 #[cfg(target_endian = "big")] {
143 return Err(Error::unsupported(
144 "PXR24 decompression method not supported yet on big endian processor architecture"
145 ))
146 }
147
148 let options = zune_inflate::DeflateOptions::default().set_limit(expected_byte_size).set_size_hint(expected_byte_size);
149 let mut decoder = zune_inflate::DeflateDecoder::new_with_options(&bytes, options);
150 let raw = decoder.decode_zlib()
151 .map_err(|_| Error::invalid("zlib-compressed data malformed"))?; // TODO share code with zip?
152
153 let mut read = raw.as_slice();
154 let mut out = Vec::with_capacity(expected_byte_size.min(2048*4));
155
156 for y in area.position.1 .. area.end().1 {
157 for channel in &channels.list {
158 if mod_p(y, usize_to_i32(channel.sampling.1)) != 0 { continue; }
159
160 let sample_count_x = channel.subsampled_resolution(area.size).0;
161 let mut read_sample_line = ||{
162 if sample_count_x > read.len() { return Err(Error::invalid("not enough data")) }
163 let (samples, rest) = read.split_at(sample_count_x);
164 read = rest;
165 Ok(samples)
166 };
167
168 let mut pixel_accumulation: u32 = 0;
169
170 match channel.sample_type {
171 SampleType::F16 => {
172 let sample_byte_pairs = read_sample_line()?.iter()
173 .zip(read_sample_line()?);
174
175 for (&in_byte_0, &in_byte_1) in sample_byte_pairs {
176 let difference = u16::from_ne_bytes([in_byte_1, in_byte_0]) as u32;
177 pixel_accumulation = pixel_accumulation.overflowing_add(difference).0;
178 out.extend_from_slice(&(pixel_accumulation as u16).to_ne_bytes());
179 }
180 },
181
182 SampleType::U32 => {
183 let sample_byte_quads = read_sample_line()?.iter()
184 .zip(read_sample_line()?)
185 .zip(read_sample_line()?)
186 .zip(read_sample_line()?);
187
188 for (((&in_byte_0, &in_byte_1), &in_byte_2), &in_byte_3) in sample_byte_quads {
189 let difference = u32::from_ne_bytes([in_byte_3, in_byte_2, in_byte_1, in_byte_0]);
190 pixel_accumulation = pixel_accumulation.overflowing_add(difference).0;
191 out.extend_from_slice(&pixel_accumulation.to_ne_bytes());
192 }
193 },
194
195 SampleType::F32 => {
196 let sample_byte_triplets = read_sample_line()?.iter()
197 .zip(read_sample_line()?).zip(read_sample_line()?);
198
199 for ((&in_byte_0, &in_byte_1), &in_byte_2) in sample_byte_triplets {
200 let difference = u32::from_ne_bytes([0, in_byte_2, in_byte_1, in_byte_0]);
201 pixel_accumulation = pixel_accumulation.overflowing_add(difference).0;
202 out.extend_from_slice(&pixel_accumulation.to_ne_bytes());
203 }
204 }
205 }
206 }
207 }
208
209 if pedantic && !read.is_empty() {
210 return Err(Error::invalid("too much data"));
211 }
212
213 Ok(super::convert_little_endian_to_current(out, channels, area))
214}
215
216
217
218
219/// Conversion from 32-bit to 24-bit floating-point numbers.
220/// Reverse conversion is just a simple 8-bit left shift.
221pub fn f32_to_f24(float: f32) -> u32 {
222 let bits = float.to_bits();
223
224 let sign = bits & 0x80000000;
225 let exponent = bits & 0x7f800000;
226 let mantissa = bits & 0x007fffff;
227
228 let result = if exponent == 0x7f800000 {
229 if mantissa != 0 {
230 // F is a NAN; we preserve the sign bit and
231 // the 15 leftmost bits of the significand,
232 // with one exception: If the 15 leftmost
233 // bits are all zero, the NAN would turn
234 // into an infinity, so we have to set at
235 // least one bit in the significand.
236
237 let mantissa = mantissa >> 8;
238 (exponent >> 8) | mantissa | if mantissa == 0 { 1 } else { 0 }
239 }
240 else { // F is an infinity.
241 exponent >> 8
242 }
243 }
244 else { // F is finite, round the significand to 15 bits.
245 let result = ((exponent | mantissa) + (mantissa & 0x00000080)) >> 8;
246
247 if result >= 0x7f8000 {
248 // F was close to FLT_MAX, and the significand was
249 // rounded up, resulting in an exponent overflow.
250 // Avoid the overflow by truncating the significand
251 // instead of rounding it.
252
253 (exponent | mantissa) >> 8
254 }
255 else {
256 result
257 }
258 };
259
260 return (sign >> 8) | result;
261}