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
//! https://pngquant.org/lib/
//!
//! Converts RGBA images to 8-bit with alpha channel.
//!
//! This is based on imagequant library, which generates very high quality images.
//!
//! See `examples/` directory for example code.

extern crate imagequant_sys as ffi;

pub use ffi::liq_error;
pub use ffi::liq_error::*;
use std::os::raw::c_int;
use std::mem;
use std::ptr;

/// 8-bit RGBA. This is the only color format used by the library.
pub type Color = ffi::liq_color;
pub type HistogramEntry = ffi::liq_histogram_entry;

/// Settings for the conversion proces. Start here.
pub struct Attributes {
    handle: *mut ffi::liq_attr,
}

/// Describes image dimensions for the library.
pub struct Image<'a> {
    handle: *mut ffi::liq_image,
    _marker: std::marker::PhantomData<&'a [u8]>,
}

/// Palette inside.
pub struct QuantizationResult {
    handle: *mut ffi::liq_result,
}

/// Generate one shared palette for multiple images.
pub struct Histogram<'a> {
    attr: &'a Attributes,
    handle: *mut ffi::liq_histogram,
}

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

    /// It's better to use `set_quality()`
    pub fn set_max_colors(&mut self, value: i32) -> liq_error {
        unsafe { ffi::liq_set_max_colors(&mut *self.handle, value) }
    }

    /// Number of least significant bits to ignore.
    ///
    /// Useful for generating palettes for VGA, 15-bit textures, or other retro platforms.
    pub fn set_min_posterization(&mut self, value: i32) -> liq_error {
        unsafe { ffi::liq_set_min_posterization(&mut *self.handle, value) }
    }

    pub fn min_posterization(&mut self) -> i32 {
        unsafe { ffi::liq_get_min_posterization(&*self.handle) }
    }

    /// Range 0-100, roughly like JPEG.
    ///
    /// If minimum quality can't be met, quantization will fail.
    ///
    /// Default is min 0, max 100.
    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) }
    }

    /// Reads values set with `set_quality`
    pub fn quality(&mut self) -> (u32, u32) {
        unsafe {
            (ffi::liq_get_min_quality(&mut *self.handle) as u32,
             ffi::liq_get_max_quality(&mut *self.handle) as u32)
        }
    }

    /// 1-10.
    ///
    /// Faster speeds generate images of lower quality, but may be useful
    /// for real-time generation of images.
    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) }
    }

    /// Describe dimensions of a slice of RGBA pixels
    ///
    /// Use 0.0 for gamma if the image is sRGB (most images are).
    pub fn new_image<'a, RGBA: Copy>(&self, bitmap: &'a [RGBA], width: usize, height: usize, gamma: f64) -> Result<Image<'a>, liq_error> {
        Image::new(self, bitmap, width, height, gamma)
    }

    pub fn new_histogram(&self) -> Histogram {
        Histogram::new(&self)
    }

    /// Generate palette for the image
    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> {
    /// Creates histogram object that will be used to collect color statistics from multiple images.
    ///
    /// All options should be set on `attr` before the histogram object is created. Options changed later may not have effect.
    pub fn new(attr: &'a Attributes) -> Self {
        Histogram {
            attr: attr,
            handle: unsafe { ffi::liq_histogram_create(&*attr.handle) },
        }
    }

    /// "Learns" colors from the image, which will be later used to generate the palette.
    ///
    /// Fixed colors added to the image are also added to the histogram. If total number of fixed colors exceeds 256, this function will fail with `LIQ_BUFFER_TOO_SMALL`.
    pub fn add_image(&mut self, image: &mut Image) -> liq_error {
        unsafe { ffi::liq_histogram_add_image(&mut *self.handle, &*self.attr.handle, &mut *image.handle) }
    }

    /// Alternative to `add_image()`. Intead of counting colors in an image, it directly takes an array of colors and their counts.
    ///
    /// This function is only useful if you already have a histogram of the image from another source.
    pub fn add_colors(&mut self, colors: &[HistogramEntry], gamma: f64) -> liq_error {
        unsafe {
            ffi::liq_histogram_add_colors(&mut *self.handle, &*self.attr.handle, colors.as_ptr(), colors.len() as c_int, gamma)
        }
    }

    /// Generate palette for all images/colors added to the histogram.
    ///
    /// Palette generated using this function won't be improved during remapping.
    /// If you're generating palette for only one image, it's better not to use the `Histogram`.
    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> {
    /// Describe dimensions of a slice of RGBA pixels.
    ///
    /// `bitmap` must be either `&[u8]` or a slice with one element per pixel (`&[RGBA]`).
    ///
    /// Use `0.` for gamma if the image is sRGB (most images are).
    pub fn new<PixelType: Copy>(attr: &Attributes, bitmap: &'a [PixelType], width: usize, height: usize, gamma: f64) -> Result<Self, liq_error> {
        match mem::size_of::<PixelType>() {
            1 | 4 => {}
            _ => return Err(LIQ_UNSUPPORTED),
        }
        if bitmap.len() * mem::size_of::<PixelType>() < width*height*4 {
            eprintln!("Buffer length is {}x{} bytes, which is not enough for {}x{}x4 RGBA bytes", bitmap.len(), mem::size_of::<PixelType>(), width, height);
            return Err(LIQ_BUFFER_TOO_SMALL);
        }
        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() => Ok(Image {
                    handle: h,
                    _marker: std::marker::PhantomData,
                }),
                _ => Err(LIQ_INVALID_POINTER),
            }
        }
    }

    pub fn width(&self) -> usize {
        unsafe { ffi::liq_image_get_width(&*self.handle) as usize }
    }

    pub fn height(&self) -> usize {
        unsafe { ffi::liq_image_get_height(&*self.handle) as usize }
    }

    /// Reserves a color in the output palette created from this image. It behaves as if the given color was used in the image and was very important.
    ///
    /// RGB values of liq_color are assumed to have the same gamma as the image.
    ///
    /// It must be called before the image is quantized.
    ///
    /// Returns error if more than 256 colors are added. If image is quantized to fewer colors than the number of fixed colors added, then excess fixed colors will be ignored.
    pub fn add_fixed_color(&mut self, color: ffi::liq_color) -> liq_error {
        unsafe {
            ffi::liq_image_add_fixed_color(&mut *self.handle, color)
        }
    }
}

impl QuantizationResult {
    /// Set to 1.0 to get nice smooth image
    pub fn set_dithering_level(&mut self, value: f32) -> liq_error {
        unsafe { ffi::liq_set_dithering_level(&mut *self.handle, value) }
    }

    /// The default is sRGB gamma (~1/2.2)
    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) }
    }

    /// Number 0-100 guessing how nice the input image will look if remapped to this palette
    pub fn quantization_quality(&mut self) -> i32 {
        unsafe { ffi::liq_get_quantization_quality(&*self.handle) as i32 }
    }

    /// Approximate mean square error of the palette
    pub fn quantization_error(&mut self) -> Option<f64> {
        match unsafe { ffi::liq_get_quantization_error(&*self.handle) } {
            x if x < 0. => None,
            x => Some(x),
        }
    }

    /// Final palette
    ///
    /// It's slighly better if you get palette from the `remapped()` call instead
    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()
        }
    }

    /// Remap image
    ///
    /// Returns palette and 1-byte-per-pixel uncompresed bitmap
    pub fn remapped(&mut self, image: &mut Image) -> Result<(Vec<Color>, Vec<u8>), liq_error> {
        let len = image.width() * image.height();
        let mut buf = Vec::with_capacity(len);
        unsafe {
            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()) {
                LIQ_OK => Ok((self.palette(), buf)),
                err => Err(err),
            }
        }
    }
}

unsafe impl Send for Attributes {}
unsafe impl Send for QuantizationResult {}
unsafe impl<'a> Send for Image<'a> {}
unsafe impl<'a> Send for Histogram<'a> {}

#[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_err());
    assert!(liq.new_image(&img, 4, 3, 0.0).is_err());

    #[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_err());
    assert!(liq.new_image(&badimg, 100, 100, 0.0).is_err());
}

#[test]
fn histogram() {
    let attr = Attributes::new();
    let mut hist = attr.new_histogram();

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

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

    hist.add_colors(&[HistogramEntry{
        color: Color::new(255,128,255,128),
        count: 10,
    }], 0.0);

    let mut res = hist.quantize().unwrap();
    let pal = res.palette();
    assert_eq!(3, 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);
    liq.set_min_posterization(1);
    assert_eq!(1, liq.min_posterization());
    liq.set_min_posterization(0);

    // 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]);
}

#[test]
fn thread() {
    let liq = Attributes::new();
    std::thread::spawn(move || {
        let b = vec![0u8;4];
        liq.new_image(&b, 1, 1, 0.).unwrap();
    }).join().unwrap();
}