forked from image-rs/image-gif
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconverter.rs
More file actions
345 lines (320 loc) · 12.4 KB
/
Copy pathconverter.rs
File metadata and controls
345 lines (320 loc) · 12.4 KB
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
use alloc::borrow::Cow;
use alloc::vec::Vec;
use core::iter;
use core::mem;
use super::decoder::{DecodingError, OutputBuffer, PLTE_CHANNELS};
use crate::MemoryLimit;
use crate::common::Frame;
pub(crate) const N_CHANNELS: usize = 4;
/// Output mode for the image data
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum ColorOutput {
/// The decoder expands the image data to 32bit RGBA.
/// This affects:
///
/// - The buffer buffer of the `Frame` returned by [`Decoder::read_next_frame`].
/// - `Decoder::fill_buffer`, `Decoder::buffer_size` and `Decoder::line_length`.
RGBA = 0,
/// The decoder returns the raw indexed data.
Indexed = 1,
}
pub(crate) type FillBufferCallback<'a> =
&'a mut dyn FnMut(&mut OutputBuffer<'_>) -> Result<usize, DecodingError>;
/// Deinterlaces and expands to RGBA if needed
pub(crate) struct PixelConverter {
color_output: ColorOutput,
buffer: Vec<u8>,
global_palette: Option<Vec<u8>>,
}
impl PixelConverter {
pub(crate) const fn new(color_output: ColorOutput) -> Self {
Self {
color_output,
buffer: Vec::new(),
global_palette: None,
}
}
pub(crate) fn check_buffer_size(
&self,
frame: &Frame<'_>,
memory_limit: &MemoryLimit,
) -> Result<usize, DecodingError> {
let pixel_bytes = memory_limit
.buffer_size(self.color_output, frame.width, frame.height)
.ok_or_else(|| DecodingError::OutOfMemory)?;
debug_assert_eq!(
pixel_bytes,
self.buffer_size(frame).unwrap(),
"Checked computation diverges from required buffer size"
);
Ok(pixel_bytes)
}
#[inline]
pub(crate) fn read_frame(
&mut self,
frame: &mut Frame<'_>,
data_callback: FillBufferCallback<'_>,
memory_limit: &MemoryLimit,
) -> Result<(), DecodingError> {
let pixel_bytes = self.check_buffer_size(frame, memory_limit)?;
let mut vec = match mem::replace(&mut frame.buffer, Cow::Borrowed(&[])) {
// reuse buffer if possible without reallocating
Cow::Owned(mut vec) if vec.capacity() >= pixel_bytes => {
vec.resize(pixel_bytes, 0);
vec
}
// resizing would realloc anyway, and 0-init is faster than a copy
_ => vec![0; pixel_bytes],
};
self.read_into_buffer(frame, &mut vec, data_callback)?;
frame.buffer = Cow::Owned(vec);
frame.interlaced = false;
Ok(())
}
#[inline]
pub(crate) const fn buffer_size(&self, frame: &Frame<'_>) -> Option<usize> {
self.line_length(frame).checked_mul(frame.height as usize)
}
#[inline]
pub(crate) const fn line_length(&self, frame: &Frame<'_>) -> usize {
use self::ColorOutput::{Indexed, RGBA};
match self.color_output {
RGBA => frame.width as usize * N_CHANNELS,
Indexed => frame.width as usize,
}
}
/// Use `read_into_buffer` to deinterlace
#[inline(never)]
pub(crate) fn fill_buffer(
&mut self,
current_frame: &Frame<'_>,
mut buf: &mut [u8],
data_callback: FillBufferCallback<'_>,
) -> Result<usize, DecodingError> {
let original_len = buf.len();
loop {
let decode_into = match self.color_output {
// When decoding indexed data, LZW can write the pixels directly
ColorOutput::Indexed => &mut buf[..],
// When decoding RGBA, the pixel data will be expanded by a factor of 4,
// and it's simpler to decode indexed pixels to another buffer first
ColorOutput::RGBA => {
let buffer_size = buf.len() / N_CHANNELS;
if buffer_size == 0 {
return Err(DecodingError::format("odd-sized buffer"));
}
if self.buffer.len() < buffer_size {
self.buffer.resize(buffer_size, 0);
}
&mut self.buffer[..buffer_size]
}
};
match data_callback(&mut OutputBuffer::Slice(decode_into)) {
Ok(0) => return Ok(original_len - buf.len()),
Ok(bytes_decoded) => {
match self.color_output {
ColorOutput::RGBA => {
let transparent = current_frame.transparent;
let palette: &[u8] = current_frame
.palette
.as_deref()
.or(self.global_palette.as_deref())
.unwrap_or_default(); // next_frame_info already checked it won't happen
let (pixels, rest) = buf.split_at_mut(bytes_decoded * N_CHANNELS);
buf = rest;
for (rgba, idx) in pixels
.chunks_exact_mut(N_CHANNELS)
.zip(self.buffer.iter().copied().take(bytes_decoded))
{
let plte_offset = PLTE_CHANNELS * idx as usize;
if let Some(colors) =
palette.get(plte_offset..plte_offset + PLTE_CHANNELS)
{
rgba[0] = colors[0];
rgba[1] = colors[1];
rgba[2] = colors[2];
rgba[3] = if let Some(t) = transparent {
if t == idx { 0x00 } else { 0xFF }
} else {
0xFF
};
}
}
}
ColorOutput::Indexed => {
buf = &mut buf[bytes_decoded..];
}
}
if buf.is_empty() {
return Ok(original_len);
}
}
Err(DecodingError::UnexpectedEof) => {
return Ok(original_len - buf.len());
}
Err(e) => return Err(e),
}
}
}
pub(crate) fn global_palette(&self) -> Option<&[u8]> {
self.global_palette.as_deref()
}
pub(crate) fn set_global_palette(&mut self, palette: Vec<u8>) {
self.global_palette = if !palette.is_empty() {
Some(palette)
} else {
None
};
}
/// Applies deinterlacing
///
/// Set `frame.interlaced = false` afterwards if you're putting the buffer back into the `Frame`
pub(crate) fn read_into_buffer(
&mut self,
frame: &Frame<'_>,
buf: &mut [u8],
data_callback: FillBufferCallback<'_>,
) -> Result<(), DecodingError> {
if frame.interlaced {
let width = self.line_length(frame);
let mut row_iter = InterlaceIterator {
len: frame.height,
next: 0,
pass: 0,
};
let mut truncated = false;
for (row, pass) in &mut row_iter {
// this can't overflow 32-bit, because row never equals (maximum) height
let start = row * width;
// Handle a too-small buffer and 32-bit usize overflow without panicking
let line = buf
.get_mut(start..)
.and_then(|b| b.get_mut(..width))
.ok_or_else(|| DecodingError::format("buffer too small"))?;
let filled = self.fill_buffer(frame, line, data_callback)?;
if filled < line.len() {
truncated = true;
match pass {
0 => line[filled..].fill(0),
1 => buf.copy_within((row - 4) * width..(row - 4) * width + width, start),
2 => buf.copy_within((row - 2) * width..(row - 2) * width + width, start),
3 => buf.copy_within((row - 1) * width..(row - 1) * width + width, start),
_ => unreachable!(),
};
}
}
if truncated {
return Err(DecodingError::Truncated);
}
} else {
let buf = self
.buffer_size(frame)
.and_then(|buffer_size| buf.get_mut(..buffer_size))
.ok_or_else(|| DecodingError::format("buffer too small"))?;
let filled = self.fill_buffer(frame, buf, data_callback)?;
if filled < buf.len() {
// Once MSRV is >= 1.95:
// core::hint::cold_path();
buf[filled..].fill(0);
return Err(DecodingError::Truncated);
}
};
Ok(())
}
}
struct InterlaceIterator {
len: u16,
next: usize,
pass: usize,
}
impl iter::Iterator for InterlaceIterator {
type Item = (usize, usize);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.len == 0 {
return None;
}
let current_pass = self.pass;
// although the pass never goes out of bounds thanks to len==0,
// the optimizer doesn't see it. get()? avoids costlier panicking code.
let mut next = self.next + *[8, 8, 4, 2].get(self.pass)?;
while next >= self.len as usize {
debug_assert!(self.pass < 4);
next = *[4, 2, 1, 0].get(self.pass)?;
self.pass += 1;
}
mem::swap(&mut next, &mut self.next);
Some((next, current_pass))
}
}
#[cfg(test)]
mod test {
use alloc::vec::Vec;
use super::InterlaceIterator;
#[rustfmt::skip]
#[test]
fn test_interlace_iterator_row() {
for &(len, expect) in &[
(0, &[][..]),
(1, &[0][..]),
(2, &[0, 1][..]),
(3, &[0, 2, 1][..]),
(4, &[0, 2, 1, 3][..]),
(5, &[0, 4, 2, 1, 3][..]),
(6, &[0, 4, 2, 1, 3, 5][..]),
(7, &[0, 4, 2, 6, 1, 3, 5][..]),
(8, &[0, 4, 2, 6, 1, 3, 5, 7][..]),
(9, &[0, 8, 4, 2, 6, 1, 3, 5, 7][..]),
(10, &[0, 8, 4, 2, 6, 1, 3, 5, 7, 9][..]),
(11, &[0, 8, 4, 2, 6, 10, 1, 3, 5, 7, 9][..]),
(12, &[0, 8, 4, 2, 6, 10, 1, 3, 5, 7, 9, 11][..]),
(13, &[0, 8, 4, 12, 2, 6, 10, 1, 3, 5, 7, 9, 11][..]),
(14, &[0, 8, 4, 12, 2, 6, 10, 1, 3, 5, 7, 9, 11, 13][..]),
(15, &[0, 8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13][..]),
(16, &[0, 8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15][..]),
(17, &[0, 8, 16, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15][..]),
] {
let iter = InterlaceIterator { len, next: 0, pass: 0 };
let lines = iter.map(|(r, _)| r).collect::<Vec<_>>();
assert_eq!(lines, expect);
}
}
#[rustfmt::skip]
#[test]
fn test_interlace_iterator_pass() {
for &(len, expect) in &[
(0, &[][..]),
(1, &[0][..]),
(2, &[0, 3][..]),
(3, &[0, 2, 3][..]),
(4, &[0, 2, 3, 3][..]),
(5, &[0, 1, 2, 3, 3][..]),
(6, &[0, 1, 2, 3, 3, 3][..]),
(7, &[0, 1, 2, 2, 3, 3, 3][..]),
(8, &[0, 1, 2, 2, 3, 3, 3, 3][..]),
(9, &[0, 0, 1, 2, 2, 3, 3, 3, 3][..]),
(10, &[0, 0, 1, 2, 2, 3, 3, 3, 3, 3][..]),
(11, &[0, 0, 1, 2, 2, 2, 3, 3, 3, 3, 3][..]),
(12, &[0, 0, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3][..]),
(13, &[0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3][..]),
(14, &[0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3][..]),
(15, &[0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3][..]),
(16, &[0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3][..]),
(17, &[0, 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3][..]),
] {
let iter = InterlaceIterator { len, next: 0, pass: 0 };
let passes = iter.map(|(_, p)| p).collect::<Vec<_>>();
assert_eq!(passes, expect);
}
}
#[test]
fn interlace_max() {
let iter = InterlaceIterator {
len: 0xFFFF,
next: 0,
pass: 0,
};
assert_eq!((65533, 3), iter.last().unwrap());
}
}