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
extern crate rgb;
extern crate gif;
extern crate imgref;
extern crate imagequant;
extern crate resize;
extern crate lodepng;
extern crate gif_dispose;
extern crate rayon;
extern crate pbr;
#[macro_use] extern crate error_chain;
use gif::*;
use rgb::*;
use imgref::*;
use imagequant::*;
mod error;
pub use error::*;
mod ordqueue;
use ordqueue::*;
pub mod progress;
use progress::*;
pub mod c_api;
use std::path::PathBuf;
use std::io::prelude::*;
use std::sync::Arc;
use std::borrow::Cow;
use std::thread;
type DecodedImage = CatResult<(ImgVec<RGBA8>, u16)>;
#[derive(Copy, Clone)]
pub struct Settings {
pub width: Option<u32>,
pub height: Option<u32>,
pub quality: u8,
pub once: bool,
pub fast: bool,
}
pub struct Collector {
width: Option<u32>,
height: Option<u32>,
queue: OrdQueue<DecodedImage>,
}
pub struct Writer {
queue_iter: Option<OrdQueueIter<DecodedImage>>,
settings: Settings,
}
struct GIFFrame {
image: ImgVec<u8>,
pal: Vec<RGBA8>,
delay: u16,
}
enum WriteInitState<W: Write> {
Uninit(W),
Init(Encoder<W>),
}
pub fn new(settings: Settings) -> CatResult<(Collector, Writer)> {
let (queue, queue_iter) = ordqueue::new(4);
Ok((Collector {
queue,
width: settings.width,
height: settings.height,
}, Writer {
queue_iter: Some(queue_iter),
settings,
}))
}
impl Collector {
pub fn add_frame_rgba(&mut self, frame_index: usize, image: ImgVec<RGBA8>, delay: u16) -> CatResult<()> {
self.queue.push(frame_index, Ok((Self::resized(image, self.width, self.height), delay)))
}
pub fn add_frame_png_file(&mut self, frame_index: usize, path: PathBuf, delay: u16) -> CatResult<()> {
let width = self.width;
let height = self.height;
let image = lodepng::decode32_file(&path)
.chain_err(|| format!("Can't load {}", path.display()))?;
self.queue.push(frame_index, Ok((Self::resized(ImgVec::new(image.buffer, image.width, image.height), width, height), delay)))
}
fn resized(mut image: ImgVec<RGBA8>, width: Option<u32>, height: Option<u32>) -> ImgVec<RGBA8> {
if let Some(width) = width {
if image.width() != image.stride() {
let mut contig = Vec::with_capacity(image.width()*image.height());
contig.extend(image.rows().flat_map(|r| r.iter().cloned()));
image = ImgVec::new(contig, image.width(), image.height());
}
let dst_width = (width as usize).min(image.width());
let dst_height = height.map(|h| (h as usize).min(image.height())).unwrap_or(image.height() * dst_width / image.width());
let mut r = resize::new(image.width(), image.height(), dst_width, dst_height, resize::Pixel::RGBA, resize::Type::Lanczos3);
let mut dst = vec![RGBA::new(0,0,0,0); dst_width * dst_height];
r.resize(image.buf.as_bytes(), dst.as_bytes_mut());
ImgVec::new(dst, dst_width, dst_height)
} else {
image
}
}
}
impl Writer {
fn quantize(image: ImgRef<RGBA8>, importance_map: &[u8], background: Option<ImgRef<RGBA8>>, settings: &Settings) -> CatResult<(ImgVec<u8>, Vec<RGBA8>)> {
let mut liq = Attributes::new();
if settings.fast {
liq.set_speed(10);
}
let quality = if background.is_some() {
settings.quality.into()
} else {
100
};
liq.set_quality(0, quality);
let mut img = liq.new_image_stride(image.buf, image.width(), image.height(), image.stride(), 0.)?;
img.set_importance_map(importance_map)?;
if let Some(bg) = background {
img.set_background(liq.new_image(bg.buf, bg.width(), bg.height(), 0.)?)?;
}
img.add_fixed_color(RGBA8::new(0,0,0,0));
let mut res = liq.quantize(&img)?;
res.set_dithering_level(0.5);
let (pal, pal_img) = res.remapped(&mut img)?;
debug_assert_eq!(img.width() * img.height(), pal_img.len());
Ok((Img::new(pal_img, img.width(), img.height()), pal))
}
fn write_frames<W: Write + Send>(write_queue_iter: OrdQueueIter<Arc<GIFFrame>>, outfile: W, settings: &Settings, reporter: &mut ProgressReporter) -> CatResult<()> {
let mut enc = WriteInitState::Uninit(outfile);
for f in write_queue_iter {
let GIFFrame {ref pal, ref image, delay} = *f;
reporter.increase();
let mut transparent_index = None;
let mut pal_rgb = Vec::with_capacity(3 * pal.len());
for (i, p) in pal.into_iter().enumerate() {
if p.a == 0 {
transparent_index = Some(i as u8);
}
pal_rgb.extend_from_slice([p.rgb()].as_bytes());
}
enc = match enc {
WriteInitState::Uninit(w) => {
let mut enc = Encoder::new(w, image.width() as u16, image.height() as u16, &[])?;
if !settings.once {
enc.write_extension(gif::ExtensionData::Repetitions(gif::Repeat::Infinite))?;
}
WriteInitState::Init(enc)
},
x => x,
};
let enc = match enc {
WriteInitState::Init(ref mut r) => r,
_ => unreachable!(),
};
enc.write_frame(&Frame {
delay,
dispose: DisposalMethod::Keep,
transparent: transparent_index,
needs_user_input: false,
top: 0,
left: 0,
width: image.width() as u16,
height: image.height() as u16,
interlaced: false,
palette: Some(pal_rgb),
buffer: Cow::Borrowed(&image.buf),
})?;
}
Ok(())
}
pub fn write<W: Write + Send>(mut self, outfile: W, reporter: &mut ProgressReporter) -> CatResult<()> {
let (write_queue, write_queue_iter) = ordqueue::new(4);
let queue_iter = self.queue_iter.take().unwrap();
let settings = self.settings.clone();
let make_thread = thread::spawn(move || {
Self::make_frames(queue_iter, write_queue, &settings)
});
Self::write_frames(write_queue_iter, outfile, &self.settings, reporter)?;
make_thread.join().unwrap()?;
Ok(())
}
fn make_frames(queue_iter: OrdQueueIter<DecodedImage>, mut write_queue: OrdQueue<Arc<GIFFrame>>, settings: &Settings) -> CatResult<()> {
let mut decode_iter = queue_iter.enumerate().map(|(i,tmp)| tmp.map(|(image, delay)|(i,image,delay)));
let mut screen = None;
let mut curr_frame = if let Some(a) = decode_iter.next() {
Some(a?)
} else {
Err("Found no usable frames to encode")?
};
let mut importance_map = vec![255u8; curr_frame.as_ref().unwrap().1.buf.len()];
let mut next_frame = if let Some(a) = decode_iter.next() {
Some(a?)
} else {
None
};
while let Some((i, image, delay)) = curr_frame.take() {
curr_frame = next_frame.take();
next_frame = if let Some(a) = decode_iter.next() {
Some(a?)
} else {
None
};
if let Some((_, ref next, _)) = next_frame {
if next.width() != image.width() || next.height() != image.height() {
Err(format!("Frame {} has wrong size ({}×{}, expected {}×{})", i+1,
next.width(), next.height(), image.width(), image.height()))?;
}
debug_assert_eq!(next.width(), image.width());
importance_map.clear();
importance_map.extend(next.rows().zip(image.rows()).flat_map(|(a,b)| a.iter().cloned().zip(b.iter().cloned())).map(|(a,b)| {
255 - (colordiff(a,b) / (255*255*6/170)) as u8
}));
};
if screen.is_none() {
screen = Some(gif_dispose::Screen::new(image.width(), image.height(), RGBA8::new(0,0,0,0), None));
}
let screen = screen.as_mut().unwrap();
let has_prev_frame = i > 0;
if has_prev_frame {
let q = 100 - settings.quality as u32;
let min_diff = 80 + q * q;
debug_assert_eq!(image.width(), screen.pixels.width());
importance_map.chunks_mut(image.width()).zip(screen.pixels.rows().zip(image.rows()))
.flat_map(|(px, (a,b))| {
px.iter_mut().zip(a.iter().cloned().zip(b.iter().cloned()))
})
.for_each(|(px, (a,b))| {
let diff = colordiff(a,b);
*px = if diff < min_diff {
0
} else {
let t = diff / 32;
((t * t).min(256) as u16 * u16::from(*px) / 256) as u8
}
});
}
let (image8, image8_pal) = {
let bg = if has_prev_frame {Some(screen.pixels.as_ref())} else {None};
Self::quantize(image.as_ref(), &importance_map, bg, settings)?
};
let transparent_index = image8_pal.iter().position(|p| p.a == 0).map(|i| i as u8);
let frame = Arc::new(GIFFrame {
image: image8,
pal: image8_pal,
delay,
});
write_queue.push(i, frame.clone())?;
screen.blit(Some(&frame.pal), gif::DisposalMethod::Keep, 0, 0, frame.image.as_ref(), transparent_index)?;
}
Ok(())
}
}
#[inline]
fn colordiff(a: RGBA8, b: RGBA8) -> u32 {
if a.a == 0 || b.a == 0 {
return 255*255*6;
}
(i32::from(a.r as i16 - b.r as i16) * i32::from(a.r as i16 - b.r as i16)) as u32 * 2 +
(i32::from(a.g as i16 - b.g as i16) * i32::from(a.g as i16 - b.g as i16)) as u32 * 3 +
(i32::from(a.b as i16 - b.b as i16) * i32::from(a.b as i16 - b.b as i16)) as u32
}