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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#![crate_type = "lib"]
#![allow(improper_ctypes)]

/// http://pngquant.org/lib/

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;
use std::ptr;

#[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;

    pub enum liq_attr {}
    pub enum liq_image {}
    pub enum liq_result {}
    pub enum liq_histogram {}

    #[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: &mut liq_image);

        pub fn liq_histogram_create(attr: &liq_attr) -> *mut liq_histogram;
        pub fn liq_histogram_add_image(hist: &mut liq_histogram, attr: &liq_attr, image: &liq_image) -> liq_error;
        pub fn liq_histogram_destroy(hist: &mut liq_histogram);

        pub fn liq_quantize_image(options: &liq_attr, input_image: &liq_image) -> *mut liq_result;
        pub fn liq_histogram_quantize(input_hist: &liq_histogram, options: &liq_attr, result_output: &mut *mut liq_result) -> liq_error;
        pub fn liq_image_quantize(input_image: &liq_image, options: &liq_attr, result_output: &mut *mut liq_result) -> liq_error;

        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: &mut liq_result) -> *const liq_palette;

        pub fn liq_write_remapped_image(result: &mut liq_result, input_image: &liq_image, buffer: *mut u8, buffer_size: size_t) -> liq_error;
        pub fn liq_write_remapped_image_rows(result: &mut 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: &mut 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,
}

pub struct Histogram<'a> {
    attr: &'a Attributes,
    handle: *mut ffi::liq_histogram,
}

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<'a> Drop for Histogram<'a> {
    fn drop(&mut self) {
        unsafe {
            ffi::liq_histogram_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 {
        let handle = unsafe { ffi::liq_attr_create() };
        assert!(!handle.is_null());
        Attributes { handle: handle }
    }

    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 new_histogram(&self) -> Histogram {
        Histogram::new(&self)
    }

    pub fn quantize(&mut self, image: &Image) -> Result<QuantizationResult, liq_error> {
        unsafe {
            let mut h = ptr::null_mut();
            match ffi::liq_image_quantize(&mut *image.handle, &mut *self.handle, &mut h) {
                liq_error::LIQ_OK if !h.is_null() => Ok(QuantizationResult { handle: h }),
                err => Err(err),
            }
        }
    }
}

pub fn new() -> Attributes {
    Attributes::new()
}

impl<'a> Histogram<'a> {
    pub fn new(attr: &'a Attributes) -> Histogram<'a> {
        Histogram {
            attr: attr,
            handle: unsafe { ffi::liq_histogram_create(&*attr.handle) }
        }
    }

    pub fn add_image(&mut self, image: &Image) -> liq_error {
        unsafe {
            ffi::liq_histogram_add_image(&mut *self.handle, &*self.attr.handle, &*image.handle)
        }
    }

    pub fn quantize(&mut self) -> Result<QuantizationResult, liq_error> {
        unsafe {
            let mut h = ptr::null_mut();
            match ffi::liq_histogram_quantize(&mut *self.handle, &*self.attr.handle, &mut h) {
                liq_error::LIQ_OK if !h.is_null() => Ok(QuantizationResult { handle: h }),
                err => Err(err),
            }
        }
    }
}

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 ref pal = *ffi::liq_get_palette(&mut *self.handle);
            pal.entries.iter().cloned().take(pal.count as usize).collect()
        }
    }

    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); // Creates uninitialized buffer
            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();

    #[allow(dead_code)]
    #[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());

    #[allow(dead_code)]
    #[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 histogram() {
    let attr = Attributes::new();
    let mut hist = attr.new_histogram();

    let bitmap1 = vec![0u8; 4];
    let image1 = attr.new_image(&bitmap1[..], 1, 1, 0.0).unwrap();
    hist.add_image(&image1);

    let bitmap2 = vec![255u8; 4];
    let image2 = attr.new_image(&bitmap2[..], 1, 1, 0.0).unwrap();
    hist.add_image(&image2);

    let mut res = hist.quantize().unwrap();
    let pal = res.palette();
    assert_eq!(2, pal.len());
}

#[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;

    // Configure the library
    let mut liq = Attributes::new();
    liq.set_speed(5);
    liq.set_quality(70, 99);

    // Describe the bitmap
    let ref mut img = liq.new_image(&fakebitmap[..], width, height, 0.0).unwrap();

    // The magic happens in quantize()
    let mut res = match liq.quantize(img) {
        Ok(res) => res,
        Err(err) => panic!("Quantization failed, because: {:?}", err),
    };

    // Enable dithering for subsequent remappings
    res.set_dithering_level(1.0);

    // You can reuse the result to generate several images with the same palette
    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]);
}