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
use std::cmp::min;
use std::io;
use std::io::prelude::*;
use lzw;
use traits::{Parameter, WriteBytesExt};
use common::{Block, Frame, Extension, DisposalMethod};
use util;
pub enum Repeat {
Finite(u16),
Infinite
}
impl<W: Write> Parameter<Encoder<W>> for Repeat {
type Result = Result<(), io::Error>;
fn set_param(self, this: &mut Encoder<W>) -> Self::Result {
this.write_extension(ExtensionData::Repetitions(self))
}
}
pub enum ExtensionData {
Control {
flags: u8,
delay: u16,
trns: u8
},
Repetitions(Repeat)
}
impl ExtensionData {
pub fn new_control_ext(delay: u16, dispose: DisposalMethod,
needs_user_input: bool, trns: Option<u8>) -> ExtensionData {
let mut flags = 0;
let trns = match trns {
Some(trns) => {
flags |= 1;
trns as u8
},
None => 0
};
flags |= (needs_user_input as u8) << 1;
flags |= (dispose as u8) << 2;
ExtensionData::Control {
flags: flags,
delay: delay,
trns: trns
}
}
}
struct BlockWriter<'a, W: Write + 'a> {
w: &'a mut W,
bytes: usize,
buf: [u8; 0xFF]
}
impl<'a, W: Write + 'a> BlockWriter<'a, W> {
fn new(w: &'a mut W) -> BlockWriter<'a, W> {
BlockWriter {
w: w,
bytes: 0,
buf: [0; 0xFF]
}
}
}
impl<'a, W: Write + 'a> Write for BlockWriter<'a, W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let to_copy = min(buf.len(), 0xFF - self.bytes);
util::copy_memory(&buf[..to_copy], &mut self.buf[self.bytes..]);
self.bytes += to_copy;
if self.bytes == 0xFF {
self.bytes = 0;
self.w.write_le(0xFFu8)?;
self.w.write_all(&self.buf)?;
}
Ok(to_copy)
}
fn flush(&mut self) -> io::Result<()> {
return Err(io::Error::new(
io::ErrorKind::Other,
"Cannot flush a BlockWriter, use `drop` instead."
))
}
}
impl<'a, W: Write + 'a> Drop for BlockWriter<'a, W> {
#[cfg(feature = "raii_no_panic")]
fn drop(&mut self) {
if self.bytes > 0 {
let _ = self.w.write_le(self.bytes as u8);
let _ = self.w.write_all(&self.buf[..self.bytes]);
}
}
#[cfg(not(feature = "raii_no_panic"))]
fn drop(&mut self) {
if self.bytes > 0 {
self.w.write_le(self.bytes as u8).unwrap();
self.w.write_all(&self.buf[..self.bytes]).unwrap();
}
}
}
pub struct Encoder<W: Write> {
w: W,
global_palette: bool,
width: u16,
height: u16
}
impl<W: Write> Encoder<W> {
pub fn new(w: W, width: u16, height: u16, global_palette: &[u8]) -> io::Result<Self> {
Encoder {
w: w,
global_palette: false,
width: width,
height: height
}.write_global_palette(global_palette)
}
pub fn write_global_palette(mut self, palette: &[u8]) -> io::Result<Self> {
self.global_palette = true;
let mut flags = 0;
flags |= 0b1000_0000;
let num_colors = palette.len() / 3;
if num_colors > 256 {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Too many colors"));
}
flags |= flag_size(num_colors);
flags |= flag_size(num_colors) << 4;
self.write_screen_desc(flags)?;
self.write_color_table(palette)?;
Ok(self)
}
pub fn write_frame(&mut self, frame: &Frame) -> io::Result<()> {
self.write_extension(ExtensionData::new_control_ext(
frame.delay,
frame.dispose,
frame.needs_user_input,
frame.transparent
))?;
self.w.write_le(Block::Image as u8)?;
self.w.write_le(frame.left)?;
self.w.write_le(frame.top)?;
self.w.write_le(frame.width)?;
self.w.write_le(frame.height)?;
let mut flags = 0;
if frame.interlaced {
flags |= 0b0100_0000;
}
match frame.palette {
Some(ref palette) => {
flags |= 0b1000_0000;
let num_colors = palette.len() / 3;
if num_colors > 256 {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Too many colors"));
}
flags |= flag_size(num_colors);
self.w.write_le(flags)?;
self.write_color_table(palette)
},
None => if !self.global_palette {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"The GIF format requires a color palette but none was given."
))
} else {
self.w.write_le(flags)
}
}?;
self.write_image_block(&frame.buffer)
}
fn write_image_block(&mut self, data: &[u8]) -> io::Result<()> {
{
let min_code_size: u8 = match flag_size(*data.iter().max().unwrap_or(&0) as usize + 1) + 1 {
1 => 2,
n => n
};
self.w.write_le(min_code_size)?;
let mut bw = BlockWriter::new(&mut self.w);
let mut enc = lzw::Encoder::new(lzw::LsbWriter::new(&mut bw), min_code_size)?;
enc.encode_bytes(data)?;
}
self.w.write_le(0u8)
}
fn write_color_table(&mut self, table: &[u8]) -> io::Result<()> {
let num_colors = table.len() / 3;
if num_colors > 256 {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Too many colors"));
}
let size = flag_size(num_colors);
self.w.write_all(&table[..num_colors * 3])?;
for _ in 0..((2 << size) - num_colors) {
self.w.write_all(&[0, 0, 0])?
}
Ok(())
}
pub fn write_extension(&mut self, extension: ExtensionData) -> io::Result<()> {
use self::ExtensionData::*;
if let Repetitions(Repeat::Finite(0)) = extension {
return Ok(())
}
self.w.write_le(Block::Extension as u8)?;
match extension {
Control { flags, delay, trns } => {
self.w.write_le(Extension::Control as u8)?;
self.w.write_le(4u8)?;
self.w.write_le(flags)?;
self.w.write_le(delay)?;
self.w.write_le(trns)?;
}
Repetitions(repeat) => {
self.w.write_le(Extension::Application as u8)?;
self.w.write_le(11u8)?;
self.w.write(b"NETSCAPE2.0")?;
self.w.write_le(3u8)?;
self.w.write_le(1u8)?;
match repeat {
Repeat::Finite(no) => self.w.write_le(no)?,
Repeat::Infinite => self.w.write_le(0u16)?,
}
}
}
self.w.write_le(0u8)
}
pub fn write_raw_extension(&mut self, func: u8, data: &[&[u8]]) -> io::Result<()> {
self.w.write_le(Block::Extension as u8)?;
self.w.write_le(func as u8)?;
for block in data {
for chunk in block.chunks(0xFF) {
self.w.write_le(chunk.len() as u8)?;
self.w.write_all(chunk)?;
}
}
self.w.write_le(0u8)
}
fn write_screen_desc(&mut self, flags: u8) -> io::Result<()> {
self.w.write_all(b"GIF89a")?;
self.w.write_le(self.width)?;
self.w.write_le(self.height)?;
self.w.write_le(flags)?;
self.w.write_le(0u8)?;
self.w.write_le(0u8)
}
}
impl<W: Write> Drop for Encoder<W> {
#[cfg(feature = "raii_no_panic")]
fn drop(&mut self) {
let _ = self.w.write_le(Block::Trailer as u8);
}
#[cfg(not(feature = "raii_no_panic"))]
fn drop(&mut self) {
self.w.write_le(Block::Trailer as u8).unwrap()
}
}
fn flag_size(size: usize) -> u8 {
match size {
0 ...2 => 0,
3 ...4 => 1,
5 ...8 => 2,
7 ...16 => 3,
17 ...32 => 4,
33 ...64 => 5,
65 ...128 => 6,
129...256 => 7,
_ => 7
}
}