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
#![crate_type = "lib"]
#![allow(improper_ctypes)]
extern crate libc;
pub use ffi::liq_error;
pub use ffi::liq_error::*;
use libc::{c_int, size_t};
use std::option::Option;
use std::vec::Vec;
use std::fmt;
use std::mem;
#[repr(C)]
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}
impl fmt::Debug for Color {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.a {
            255 => write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b),
            _ => write!(f, "rgba({},{},{},{})", self.r, self.g, self.b, self.a),
        }
    }
}
#[allow(dead_code)]
#[allow(non_camel_case_types)]
pub mod ffi {
    use libc::{c_int, size_t};
    use std::fmt;
    #[repr(C)]
    #[allow(missing_copy_implementations)]
    pub struct liq_attr;
    #[repr(C)]
    #[allow(missing_copy_implementations)]
    pub struct liq_image;
    #[repr(C)]
    #[allow(missing_copy_implementations)]
    pub struct liq_result;
    #[repr(C)]
    #[derive(Copy, Clone)]
    pub enum liq_error {
        LIQ_OK = 0,
        LIQ_QUALITY_TOO_LOW = 99,
        LIQ_VALUE_OUT_OF_RANGE = 100,
        LIQ_OUT_OF_MEMORY,
        LIQ_NOT_READY,
        LIQ_BITMAP_NOT_AVAILABLE,
        LIQ_BUFFER_TOO_SMALL,
        LIQ_INVALID_POINTER,
    }
    #[allow(non_camel_case_types)]
    #[repr(C)]
    #[derive(Copy, Clone)]
    pub enum liq_ownership {
        LIQ_OWN_ROWS=4,
        LIQ_OWN_PIXELS=8,
        LIQ_OWN_QUALITY_MAP=16,
    }
    #[allow(non_camel_case_types)]
    #[repr(C)]
    pub struct liq_palette {
        pub count: c_int,
        pub entries: [super::Color; 256],
    }
    impl fmt::Debug for liq_error {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "{}", match *self {
                liq_error::LIQ_OK => "OK",
                liq_error::LIQ_QUALITY_TOO_LOW => "LIQ_QUALITY_TOO_LOW",
                liq_error::LIQ_VALUE_OUT_OF_RANGE => "VALUE_OUT_OF_RANGE",
                liq_error::LIQ_OUT_OF_MEMORY => "OUT_OF_MEMORY",
                liq_error::LIQ_NOT_READY => "NOT_READY",
                liq_error::LIQ_BITMAP_NOT_AVAILABLE => "BITMAP_NOT_AVAILABLE",
                liq_error::LIQ_BUFFER_TOO_SMALL => "BUFFER_TOO_SMALL",
                liq_error::LIQ_INVALID_POINTER => "INVALID_POINTER",
            })
        }
    }
    #[link(name="imagequant", kind="static")]
    extern {
        pub fn liq_attr_create() -> *mut liq_attr;
        pub fn liq_attr_copy(orig: &liq_attr) -> *mut liq_attr;
        pub fn liq_attr_destroy(attr: &mut liq_attr);
        pub fn liq_set_max_colors(attr: &mut liq_attr, colors: c_int) -> liq_error;
        pub fn liq_get_max_colors(attr: &liq_attr) -> c_int;
        pub fn liq_set_speed(attr: &mut liq_attr, speed: c_int) -> liq_error;
        pub fn liq_get_speed(attr: &liq_attr) -> c_int;
        pub fn liq_set_min_posterization(attr: &mut liq_attr, bits: c_int) -> liq_error;
        pub fn liq_get_min_posterization(attr: &liq_attr) -> c_int;
        pub fn liq_set_quality(attr: &mut liq_attr, minimum: c_int, maximum: c_int) -> liq_error;
        pub fn liq_get_min_quality(attr: &liq_attr) -> c_int;
        pub fn liq_get_max_quality(attr: &liq_attr) -> c_int;
        pub fn liq_set_last_index_transparent(attr: &mut liq_attr, is_last: c_int);
        pub fn liq_image_create_rgba_rows(attr: &liq_attr, rows: *const *const u8, width: c_int, height: c_int, gamma: f64) -> *mut liq_image;
        pub fn liq_image_create_rgba(attr: &liq_attr, bitmap: *const u8, width: c_int, height: c_int, gamma: f64) -> *mut liq_image;
        pub fn liq_image_get_width(img: &liq_image) -> c_int;
        pub fn liq_image_get_height(img: &liq_image) -> c_int;
        pub fn liq_image_destroy(img: &liq_image);
        pub fn liq_quantize_image(options: &liq_attr, input_image: &liq_image) -> *mut liq_result;
        pub fn liq_set_dithering_level(res: &liq_result, dither_level: f32) -> liq_error;
        pub fn liq_set_output_gamma(res: &liq_result, gamma: f64) -> liq_error;
        pub fn liq_get_output_gamma(result: &liq_result) -> f64;
        pub fn liq_get_palette(result: &liq_result) -> *const liq_palette;
        pub fn liq_write_remapped_image(result: &liq_result, input_image: &liq_image, buffer: *mut u8, buffer_size: size_t) -> liq_error;
        pub fn liq_write_remapped_image_rows(result: &liq_result, input_image: &liq_image, row_pointers: *const *mut u8) -> liq_error;
        pub fn liq_get_quantization_error(result: &liq_result) -> f64;
        pub fn liq_get_quantization_quality(result: &liq_result) -> c_int;
        pub fn liq_result_destroy(res: &liq_result);
    }
}
pub struct Attributes {
    handle: *mut ffi::liq_attr,
}
pub struct Image<'a> {
    handle: *mut ffi::liq_image,
    _marker: std::marker::PhantomData<&'a [u8]>,
}
pub struct QuantizationResult {
    handle: *mut ffi::liq_result,
}
impl Drop for Attributes {
    fn drop(&mut self) {
        unsafe {
            ffi::liq_attr_destroy(&mut *self.handle);
        }
    }
}
impl<'a> Drop for Image<'a> {
    fn drop(&mut self) {
        unsafe {
            ffi::liq_image_destroy(&mut *self.handle);
        }
    }
}
impl Drop for QuantizationResult {
    fn drop(&mut self) {
        unsafe {
            ffi::liq_result_destroy(&mut *self.handle);
        }
    }
}
impl Clone for Attributes {
    fn clone(&self) -> Attributes {
        unsafe {
            Attributes { handle: ffi::liq_attr_copy(&*self.handle) }
        }
    }
}
impl Attributes {
    pub fn new() -> Attributes {
        unsafe {
            Attributes { handle: ffi::liq_attr_create() }
        }
    }
    pub fn set_max_colors(&mut self, value: i32) -> liq_error {
        unsafe {
            ffi::liq_set_max_colors(&mut *self.handle, value)
        }
    }
    pub fn set_min_posterization(&mut self, value: i32) -> liq_error {
        unsafe {
            ffi::liq_set_min_posterization(&mut *self.handle, value)
        }
    }
    pub fn set_quality(&mut self, min: u32, max: u32) -> liq_error {
        unsafe {
            ffi::liq_set_quality(&mut *self.handle, min as c_int, max as c_int)
        }
    }
    pub fn set_speed(&mut self, value: i32) -> liq_error {
        unsafe {
            ffi::liq_set_speed(&mut *self.handle, value)
        }
    }
    pub fn set_last_index_transparent(&mut self, value: bool) -> () {
        unsafe {
            ffi::liq_set_last_index_transparent(&mut *self.handle, value as c_int)
        }
    }
    pub fn speed(&mut self) -> i32 {
        unsafe {
            ffi::liq_get_speed(&*self.handle)
        }
    }
    pub fn max_colors(&mut self) -> i32 {
        unsafe {
            ffi::liq_get_max_colors(&*self.handle)
        }
    }
    pub fn new_image<'a, T: Copy + Clone>(&self, bitmap: &'a [T], width: usize, height: usize, gamma: f64) -> Option<Image<'a>> {
        Image::new(self, bitmap, width, height, gamma)
    }
    pub fn quantize(&mut self, image: &Image) -> Result<QuantizationResult,liq_error> {
        unsafe {
            match ffi::liq_quantize_image(&mut *self.handle, &mut *image.handle) {
                h if !h.is_null() => Ok(QuantizationResult { handle: h }),
                _ => Err(LIQ_QUALITY_TOO_LOW),
            }
        }
    }
}
pub fn new() -> Attributes {
    Attributes::new()
}
impl<'a> Image<'a> {
    pub fn new<T: Copy + Clone>(attr: &Attributes, bitmap: &'a [T], width: usize, height: usize, gamma: f64) -> Option<Image<'a>> {
        match mem::size_of::<T>() {
            1 | 4 => {},
            _ => return None,
        }
        if bitmap.len() * mem::size_of::<T>() < width*height*4 {
            println!("Buffer length is {}x{} bytes, which is not enough for {}x{}x4 RGBA bytes", bitmap.len(), mem::size_of::<T>(), width, height);
            return None;
        }
        unsafe {
            match ffi::liq_image_create_rgba(&*attr.handle, mem::transmute(bitmap.as_ptr()), width as c_int, height as c_int, gamma) {
                h if !h.is_null() => Some(Image {
                    handle: h,
                    _marker: std::marker::PhantomData::<&'a [u8]>,
                }),
                _ => None,
            }
        }
    }
    pub fn width(&mut self) -> usize {
        unsafe {
            ffi::liq_image_get_width(&*self.handle) as usize
        }
    }
    pub fn height(&mut self) -> usize {
        unsafe {
            ffi::liq_image_get_height(&*self.handle) as usize
        }
    }
}
impl QuantizationResult {
    pub fn set_dithering_level(&mut self, value: f32) -> liq_error {
        unsafe {
            ffi::liq_set_dithering_level(&mut *self.handle, value)
        }
    }
    pub fn set_output_gamma(&mut self, value: f64) -> liq_error {
        unsafe {
            ffi::liq_set_output_gamma(&mut *self.handle, value)
        }
    }
    pub fn output_gamma(&mut self) -> f64 {
        unsafe {
            ffi::liq_get_output_gamma(&*self.handle)
        }
    }
    pub fn quantization_quality(&mut self) -> isize {
        unsafe {
            ffi::liq_get_quantization_quality(&*self.handle) as isize
        }
    }
    pub fn palette(&mut self) -> Vec<Color> {
        unsafe {
            let pal = ffi::liq_get_palette(&mut *self.handle);
            (*pal).entries.to_vec()
        }
    }
    pub fn remapped(&mut self, image: &mut Image) -> Option<(Vec<Color>, Vec<u8>)> {
        unsafe {
            let len = image.width() * image.height();
            let mut buf = Vec::with_capacity(len);
            buf.set_len(len); 
            match ffi::liq_write_remapped_image(&mut *self.handle, &mut *image.handle, buf.as_mut_ptr(), buf.len() as size_t) {
                LIQ_OK => Some((self.palette(), buf)),
                _ => None,
            }
        }
    }
}
#[test]
fn takes_rgba() {
    let liq = Attributes::new();
    #[derive(Copy, Clone)]
    struct RGBA {r:u8, g:u8, b:u8, a:u8};
    let img = vec![RGBA {r:0, g:0, b:0, a:0}; 8];
    liq.new_image(&img, 1,1, 0.0).unwrap();
    liq.new_image(&img, 4,2, 0.0).unwrap();
    liq.new_image(&img, 8,1, 0.0).unwrap();
    assert!(liq.new_image(&img, 9,1, 0.0).is_none());
    assert!(liq.new_image(&img, 4,3, 0.0).is_none());
    #[derive(Copy, Clone)]
    struct RGB {r:u8, g:u8, b:u8};
    let badimg = vec![RGB {r:0, g:0, b:0}; 8];
    assert!(liq.new_image(&badimg, 1,1, 0.0).is_none());
    assert!(liq.new_image(&badimg, 100,100, 0.0).is_none());
}
#[test]
fn poke_it() {
    let width = 10usize;
    let height = 10usize;
    let mut fakebitmap = vec![255u8; 4*width*height];
    fakebitmap[0] = 0x55;
    fakebitmap[1] = 0x66;
    fakebitmap[2] = 0x77;
    
    let mut liq = Attributes::new();
    liq.set_speed(5);
    liq.set_quality(70, 99);
    
    let ref mut img = liq.new_image(&fakebitmap[..], width, height, 0.0).unwrap();
    
    let mut res = match liq.quantize(img) {
        Ok(res) => res,
        Err(err) => panic!("Quantization failed, because: {:?}", err),
    };
    
    res.set_dithering_level(1.0);
    
    let (palette, pixels) = res.remapped(img).unwrap();
    assert_eq!(width*height, pixels.len());
    assert_eq!(100, res.quantization_quality());
    assert_eq!(Color{r:255,g:255,b:255,a:255}, palette[0]);
    assert_eq!(Color{r:0x55,g:0x66,b:0x77,a:255}, palette[1]);
}