1 /* pngquant.c - quantize the colors in an alphamap down to a specified number
2 **
3 ** Copyright (C) 1989, 1991 by Jef Poskanzer.
4 ** Copyright (C) 1997, 2000, 2002 by Greg Roelofs; based on an idea by
5 ** Stefan Schneider.
6 ** © 2009-2013 by Kornel Lesinski.
7 **
8 ** Permission to use, copy, modify, and distribute this software and its
9 ** documentation for any purpose and without fee is hereby granted, provided
10 ** that the above copyright notice appear in all copies and that both that
11 ** copyright notice and this permission notice appear in supporting
12 ** documentation. This software is provided "as is" without express or
13 ** implied warranty.
14 */
15
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <stdarg.h>
20 #include <stdbool.h>
21 #include <stdint.h>
22 #include <limits.h>
23
24 #if !(defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199900L) && !(defined(_MSC_VER) && _MSC_VER >= 1800)
25 #error "This program requires C99, e.g. -std=c99 switch in GCC or it requires MSVC 18.0 or higher."
26 #error "Ignore torrent of syntax errors that may follow. It's only because compiler is set to use too old C version."
27 #endif
28
29 #ifdef _OPENMP
30 #include <omp.h>
31 #else
32 #define omp_get_max_threads() 1
33 #define omp_get_thread_num() 0
34 #endif
35
36 #include "libimagequant.h"
37
38 #include "pam.h"
39 #include "mediancut.h"
40 #include "nearest.h"
41 #include "blur.h"
42 #include "viter.h"
43
44 #define LIQ_HIGH_MEMORY_LIMIT (1<<26) /* avoid allocating buffers larger than 64MB */
45
46 // each structure has a pointer as a unique identifier that allows type checking at run time
47 static const char *const liq_attr_magic = "liq_attr", *const liq_image_magic =
48 "liq_image", *const liq_result_magic =
49 "liq_result", *const liq_remapping_result_magic =
50 "liq_remapping_result", *const liq_freed_magic = "free";
51 #define CHECK_STRUCT_TYPE(attr, kind) liq_crash_if_invalid_handle_pointer_given((const liq_attr*)attr, kind ## _magic)
52 #define CHECK_USER_POINTER(ptr) liq_crash_if_invalid_pointer_given(ptr)
53
54 struct liq_attr
55 {
56 const char *magic_header;
57 void *(*malloc) (size_t);
58 void (*free) (void *);
59
60 double target_mse, max_mse, voronoi_iteration_limit;
61 float min_opaque_val;
62 unsigned int max_colors, max_histogram_entries;
63 unsigned int min_posterization_output /* user setting */ ,
64 min_posterization_input /* speed setting */ ;
65 unsigned int voronoi_iterations, feedback_loop_trials;
66 bool last_index_transparent, use_contrast_maps, use_dither_map, fast_palette;
67 unsigned int speed;
68 liq_log_callback_function *log_callback;
69 void *log_callback_user_info;
70 liq_log_flush_callback_function *log_flush_callback;
71 void *log_flush_callback_user_info;
72 };
73
74 struct liq_image
75 {
76 const char *magic_header;
77 void *(*malloc) (size_t);
78 void (*free) (void *);
79
80 f_pixel *f_pixels;
81 rgba_pixel **rows;
82 double gamma;
83 unsigned int width, height;
84 unsigned char *noise, *edges, *dither_map;
85 rgba_pixel *pixels, *temp_row;
86 f_pixel *temp_f_row;
87 liq_image_get_rgba_row_callback *row_callback;
88 void *row_callback_user_info;
89 float min_opaque_val;
90 f_pixel fixed_colors[256];
91 unsigned short fixed_colors_count;
92 bool free_pixels, free_rows, free_rows_internal;
93 };
94
95 typedef struct liq_remapping_result
96 {
97 const char *magic_header;
98 void *(*malloc) (size_t);
99 void (*free) (void *);
100
101 unsigned char *pixels;
102 colormap *palette;
103 liq_palette int_palette;
104 double gamma, palette_error;
105 float dither_level;
106 bool use_dither_map;
107 } liq_remapping_result;
108
109 struct liq_result
110 {
111 const char *magic_header;
112 void *(*malloc) (size_t);
113 void (*free) (void *);
114
115 liq_remapping_result *remapping;
116 colormap *palette;
117 liq_palette int_palette;
118 float dither_level;
119 double gamma, palette_error;
120 int min_posterization_output;
121 bool use_dither_map, fast_palette;
122 };
123
124 static liq_result *pngquant_quantize (histogram * hist,
125 const liq_attr * options, const liq_image * img);
126 static void modify_alpha (liq_image * input_image,
127 rgba_pixel * const row_pixels);
128 static void contrast_maps (liq_image * image);
129 static histogram *get_histogram (liq_image * input_image,
130 const liq_attr * options);
131 static const rgba_pixel *liq_image_get_row_rgba (liq_image * input_image,
132 unsigned int row);
133 static const f_pixel *liq_image_get_row_f (liq_image * input_image,
134 unsigned int row);
135 static void liq_remapping_result_destroy (liq_remapping_result * result);
136
137 static void
liq_verbose_printf(const liq_attr * context,const char * fmt,...)138 liq_verbose_printf (const liq_attr * context, const char *fmt, ...)
139 {
140 if (context->log_callback) {
141 va_list va;
142 int required_space;
143 char *buf;
144
145 va_start (va, fmt);
146 required_space = vsnprintf (NULL, 0, fmt, va) + 1; // +\0
147 va_end (va);
148
149 buf = g_alloca (required_space);
150
151 va_start (va, fmt);
152 vsnprintf (buf, required_space, fmt, va);
153 va_end (va);
154
155 context->log_callback (context, buf, context->log_callback_user_info);
156 }
157 }
158
159 inline static void
verbose_print(const liq_attr * attr,const char * msg)160 verbose_print (const liq_attr * attr, const char *msg)
161 {
162 if (attr->log_callback) {
163 attr->log_callback (attr, msg, attr->log_callback_user_info);
164 }
165 }
166
167 static void
liq_verbose_printf_flush(liq_attr * attr)168 liq_verbose_printf_flush (liq_attr * attr)
169 {
170 if (attr->log_flush_callback) {
171 attr->log_flush_callback (attr, attr->log_flush_callback_user_info);
172 }
173 }
174
175 #if USE_SSE
176 inline static bool
is_sse_available(void)177 is_sse_available (void)
178 {
179 #if (defined(__x86_64__) || defined(__amd64))
180 return true;
181 #else
182 int a, b, c, d;
183 cpuid (1, a, b, c, d);
184 return d & (1 << 25); // edx bit 25 is set when SSE is present
185 #endif
186 }
187 #endif
188
189 /* make it clear in backtrace when user-supplied handle points to invalid memory */
190 NEVER_INLINE LIQ_EXPORT bool liq_crash_if_invalid_handle_pointer_given (const
191 liq_attr * user_supplied_pointer, const char *const expected_magic_header);
192 LIQ_EXPORT bool
liq_crash_if_invalid_handle_pointer_given(const liq_attr * user_supplied_pointer,const char * const expected_magic_header)193 liq_crash_if_invalid_handle_pointer_given (const liq_attr *
194 user_supplied_pointer, const char *const expected_magic_header)
195 {
196 if (!user_supplied_pointer) {
197 return false;
198 }
199
200 if (user_supplied_pointer->magic_header == liq_freed_magic) {
201 fprintf (stderr, "%s used after being freed", expected_magic_header);
202 // this is not normal error handling, this is programmer error that should crash the program.
203 // program cannot safely continue if memory has been used after it's been freed.
204 // abort() is nasty, but security vulnerability may be worse.
205 abort ();
206 }
207
208 return user_supplied_pointer->magic_header == expected_magic_header;
209 }
210
211 NEVER_INLINE LIQ_EXPORT bool liq_crash_if_invalid_pointer_given (void *pointer);
212 LIQ_EXPORT bool
liq_crash_if_invalid_pointer_given(void * pointer)213 liq_crash_if_invalid_pointer_given (void *pointer)
214 {
215 char test_access;
216
217 if (!pointer) {
218 return false;
219 }
220 // Force a read from the given (potentially invalid) memory location in order to check early whether this crashes the program or not.
221 // It doesn't matter what value is read, the code here is just to shut the compiler up about unused read.
222 test_access = *((volatile char *) pointer);
223 return test_access || true;
224 }
225
226 static void
liq_log_error(const liq_attr * attr,const char * msg)227 liq_log_error (const liq_attr * attr, const char *msg)
228 {
229 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
230 return;
231 liq_verbose_printf (attr, " error: %s", msg);
232 }
233
234 static double
quality_to_mse(long quality)235 quality_to_mse (long quality)
236 {
237 const double extra_low_quality_fudge =
238 MAX (0, 0.016 / (0.001 + quality) - 0.001);
239 if (quality == 0) {
240 return MAX_DIFF;
241 }
242 if (quality == 100) {
243 return 0;
244 }
245 // curve fudged to be roughly similar to quality of libjpeg
246 // except lowest 10 for really low number of colors
247 return extra_low_quality_fudge + 2.5 / pow (210.0 + quality,
248 1.2) * (100.1 - quality) / 100.0;
249 }
250
251 static unsigned int
mse_to_quality(double mse)252 mse_to_quality (double mse)
253 {
254 int i;
255 for (i = 100; i > 0; i--) {
256 if (mse <= quality_to_mse (i) + 0.000001) { // + epsilon for floating point errors
257 return i;
258 }
259 }
260 return 0;
261 }
262
263 LIQ_EXPORT liq_error
liq_set_quality(liq_attr * attr,int minimum,int target)264 liq_set_quality (liq_attr * attr, int minimum, int target)
265 {
266 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
267 return LIQ_INVALID_POINTER;
268 if (target < 0 || target > 100 || target < minimum || minimum < 0)
269 return LIQ_VALUE_OUT_OF_RANGE;
270
271 attr->target_mse = quality_to_mse (target);
272 attr->max_mse = quality_to_mse (minimum);
273 return LIQ_OK;
274 }
275
276 LIQ_EXPORT int
liq_get_min_quality(const liq_attr * attr)277 liq_get_min_quality (const liq_attr * attr)
278 {
279 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
280 return -1;
281 return mse_to_quality (attr->max_mse);
282 }
283
284 LIQ_EXPORT int
liq_get_max_quality(const liq_attr * attr)285 liq_get_max_quality (const liq_attr * attr)
286 {
287 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
288 return -1;
289 return mse_to_quality (attr->target_mse);
290 }
291
292
293 LIQ_EXPORT liq_error
liq_set_max_colors(liq_attr * attr,int colors)294 liq_set_max_colors (liq_attr * attr, int colors)
295 {
296 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
297 return LIQ_INVALID_POINTER;
298 if (colors < 2 || colors > 256)
299 return LIQ_VALUE_OUT_OF_RANGE;
300
301 attr->max_colors = colors;
302 return LIQ_OK;
303 }
304
305 LIQ_EXPORT int
liq_get_max_colors(const liq_attr * attr)306 liq_get_max_colors (const liq_attr * attr)
307 {
308 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
309 return -1;
310
311 return attr->max_colors;
312 }
313
314 LIQ_EXPORT liq_error
liq_set_min_posterization(liq_attr * attr,int bits)315 liq_set_min_posterization (liq_attr * attr, int bits)
316 {
317 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
318 return LIQ_INVALID_POINTER;
319 if (bits < 0 || bits > 4)
320 return LIQ_VALUE_OUT_OF_RANGE;
321
322 attr->min_posterization_output = bits;
323 return LIQ_OK;
324 }
325
326 LIQ_EXPORT int
liq_get_min_posterization(const liq_attr * attr)327 liq_get_min_posterization (const liq_attr * attr)
328 {
329 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
330 return -1;
331
332 return attr->min_posterization_output;
333 }
334
335 LIQ_EXPORT liq_error
liq_set_speed(liq_attr * attr,int speed)336 liq_set_speed (liq_attr * attr, int speed)
337 {
338 int iterations;
339
340 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
341 return LIQ_INVALID_POINTER;
342 if (speed < 1 || speed > 10)
343 return LIQ_VALUE_OUT_OF_RANGE;
344
345 iterations = MAX (8 - speed, 0);
346 iterations += iterations * iterations / 2;
347 attr->voronoi_iterations = iterations;
348 attr->voronoi_iteration_limit = 1.0 / (double) (1 << (23 - speed));
349 attr->feedback_loop_trials = MAX (56 - 9 * speed, 0);
350
351 attr->max_histogram_entries = (1 << 17) + (1 << 18) * (10 - speed);
352 attr->min_posterization_input = (speed >= 8) ? 1 : 0;
353 attr->fast_palette = (speed >= 7);
354 attr->use_dither_map = (speed <= (omp_get_max_threads () > 1 ? 7 : 5)); // parallelized dither map might speed up floyd remapping
355 attr->use_contrast_maps = (speed <= 7) || attr->use_dither_map;
356 attr->speed = speed;
357 return LIQ_OK;
358 }
359
360 LIQ_EXPORT int
liq_get_speed(const liq_attr * attr)361 liq_get_speed (const liq_attr * attr)
362 {
363 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
364 return -1;
365
366 return attr->speed;
367 }
368
369 LIQ_EXPORT liq_error
liq_set_output_gamma(liq_result * res,double gamma)370 liq_set_output_gamma (liq_result * res, double gamma)
371 {
372 if (!CHECK_STRUCT_TYPE (res, liq_result))
373 return LIQ_INVALID_POINTER;
374 if (gamma <= 0 || gamma >= 1.0)
375 return LIQ_VALUE_OUT_OF_RANGE;
376
377 if (res->remapping) {
378 liq_remapping_result_destroy (res->remapping);
379 res->remapping = NULL;
380 }
381
382 res->gamma = gamma;
383 return LIQ_OK;
384 }
385
386 LIQ_EXPORT liq_error
liq_set_min_opacity(liq_attr * attr,int min)387 liq_set_min_opacity (liq_attr * attr, int min)
388 {
389 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
390 return LIQ_INVALID_POINTER;
391 if (min < 0 || min > 255)
392 return LIQ_VALUE_OUT_OF_RANGE;
393
394 attr->min_opaque_val = (double) min / 255.0;
395 return LIQ_OK;
396 }
397
398 LIQ_EXPORT int
liq_get_min_opacity(const liq_attr * attr)399 liq_get_min_opacity (const liq_attr * attr)
400 {
401 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
402 return -1;
403
404 return MIN (255, 256.0 * attr->min_opaque_val);
405 }
406
407 LIQ_EXPORT void
liq_set_last_index_transparent(liq_attr * attr,int is_last)408 liq_set_last_index_transparent (liq_attr * attr, int is_last)
409 {
410 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
411 return;
412
413 attr->last_index_transparent = ! !is_last;
414 }
415
416 LIQ_EXPORT void
liq_set_log_callback(liq_attr * attr,liq_log_callback_function * callback,void * user_info)417 liq_set_log_callback (liq_attr * attr, liq_log_callback_function * callback,
418 void *user_info)
419 {
420 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
421 return;
422
423 liq_verbose_printf_flush (attr);
424 attr->log_callback = callback;
425 attr->log_callback_user_info = user_info;
426 }
427
428 LIQ_EXPORT void
liq_set_log_flush_callback(liq_attr * attr,liq_log_flush_callback_function * callback,void * user_info)429 liq_set_log_flush_callback (liq_attr * attr,
430 liq_log_flush_callback_function * callback, void *user_info)
431 {
432 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
433 return;
434
435 attr->log_flush_callback = callback;
436 attr->log_flush_callback_user_info = user_info;
437 }
438
439 LIQ_EXPORT liq_attr *
liq_attr_create(void)440 liq_attr_create (void)
441 {
442 return liq_attr_create_with_allocator (NULL, NULL);
443 }
444
445 LIQ_EXPORT void
liq_attr_destroy(liq_attr * attr)446 liq_attr_destroy (liq_attr * attr)
447 {
448 if (!CHECK_STRUCT_TYPE (attr, liq_attr)) {
449 return;
450 }
451
452 liq_verbose_printf_flush (attr);
453
454 attr->magic_header = liq_freed_magic;
455 attr->free (attr);
456 }
457
458 LIQ_EXPORT liq_attr *
liq_attr_copy(liq_attr * orig)459 liq_attr_copy (liq_attr * orig)
460 {
461 liq_attr *attr;
462 if (!CHECK_STRUCT_TYPE (orig, liq_attr)) {
463 return NULL;
464 }
465
466 attr = orig->malloc (sizeof (liq_attr));
467 if (!attr)
468 return NULL;
469 *attr = *orig;
470 return attr;
471 }
472
473 static void *
liq_aligned_malloc(size_t size)474 liq_aligned_malloc (size_t size)
475 {
476 unsigned char *ptr = malloc (size + 16);
477 uintptr_t offset;
478 if (!ptr) {
479 return NULL;
480 }
481
482 offset = 16 - ((uintptr_t) ptr & 15); // also reserves 1 byte for ptr[-1]
483 ptr += offset;
484 assert (0 == (((uintptr_t) ptr) & 15));
485 ptr[-1] = offset ^ 0x59; // store how much pointer was shifted to get the original for free()
486 return ptr;
487 }
488
489 static void
liq_aligned_free(void * inptr)490 liq_aligned_free (void *inptr)
491 {
492 unsigned char *ptr = inptr;
493 size_t offset = ptr[-1] ^ 0x59;
494 assert (offset > 0 && offset <= 16);
495 free (ptr - offset);
496 }
497
498 LIQ_EXPORT liq_attr *
liq_attr_create_with_allocator(void * (* custom_malloc)(size_t),void (* custom_free)(void *))499 liq_attr_create_with_allocator (void *(*custom_malloc) (size_t),
500 void (*custom_free) (void *))
501 {
502 liq_attr *attr;
503 #if USE_SSE
504 if (!is_sse_available ()) {
505 return NULL;
506 }
507 #endif
508 if (!custom_malloc && !custom_free) {
509 custom_malloc = liq_aligned_malloc;
510 custom_free = liq_aligned_free;
511 } else if (!custom_malloc != !custom_free) {
512 return NULL; // either specify both or none
513 }
514
515 attr = custom_malloc (sizeof (liq_attr));
516 if (!attr)
517 return NULL;
518 *attr = (liq_attr) {
519 .magic_header = liq_attr_magic,.malloc = custom_malloc,.free = custom_free,.max_colors = 256,.min_opaque_val = 1, // whether preserve opaque colors for IE (1.0=no, does not affect alpha)
520 .last_index_transparent = false, // puts transparent color at last index. This is workaround for blu-ray subtitles.
521 .target_mse = 0,.max_mse = MAX_DIFF,};
522 liq_set_speed (attr, 3);
523 return attr;
524 }
525
526 LIQ_EXPORT liq_error
liq_image_add_fixed_color(liq_image * img,liq_color color)527 liq_image_add_fixed_color (liq_image * img, liq_color color)
528 {
529 float gamma_lut[256];
530 rgba_pixel pix = (rgba_pixel) {
531 .r = color.r,
532 .g = color.g,
533 .b = color.b,
534 .a = color.a
535 };
536
537 if (!CHECK_STRUCT_TYPE (img, liq_image))
538 return LIQ_INVALID_POINTER;
539 if (img->fixed_colors_count > 255)
540 return LIQ_BUFFER_TOO_SMALL;
541
542 to_f_set_gamma (gamma_lut, img->gamma);
543 img->fixed_colors[img->fixed_colors_count++] = to_f (gamma_lut, pix);
544 return LIQ_OK;
545 }
546
547 static bool
liq_image_use_low_memory(liq_image * img)548 liq_image_use_low_memory (liq_image * img)
549 {
550 img->temp_f_row =
551 img->malloc (sizeof (img->f_pixels[0]) * img->width *
552 omp_get_max_threads ());
553 return img->temp_f_row != NULL;
554 }
555
556 static bool
liq_image_should_use_low_memory(liq_image * img,const bool low_memory_hint)557 liq_image_should_use_low_memory (liq_image * img, const bool low_memory_hint)
558 {
559 return img->width * img->height > (low_memory_hint ? LIQ_HIGH_MEMORY_LIMIT / 8 : LIQ_HIGH_MEMORY_LIMIT) / sizeof (f_pixel); // Watch out for integer overflow
560 }
561
562 static liq_image *
liq_image_create_internal(liq_attr * attr,rgba_pixel * rows[],liq_image_get_rgba_row_callback * row_callback,void * row_callback_user_info,int width,int height,double gamma)563 liq_image_create_internal (liq_attr * attr, rgba_pixel * rows[],
564 liq_image_get_rgba_row_callback * row_callback,
565 void *row_callback_user_info, int width, int height, double gamma)
566 {
567 liq_image *img;
568 if (gamma < 0 || gamma > 1.0) {
569 liq_log_error (attr, "gamma must be >= 0 and <= 1 (try 1/gamma instead)");
570 return NULL;
571 }
572
573 if (!rows && !row_callback) {
574 liq_log_error (attr, "missing row data");
575 return NULL;
576 }
577
578 img = attr->malloc (sizeof (liq_image));
579 if (!img)
580 return NULL;
581 *img = (liq_image) {
582 .magic_header = liq_image_magic,.malloc = attr->malloc,.free =
583 attr->free,.width = width,.height = height,.gamma =
584 gamma ? gamma : 0.45455,.rows = rows,.row_callback =
585 row_callback,.row_callback_user_info =
586 row_callback_user_info,.min_opaque_val = attr->min_opaque_val,};
587
588 if (!rows || attr->min_opaque_val < 1.f) {
589 img->temp_row =
590 attr->malloc (sizeof (img->temp_row[0]) * width *
591 omp_get_max_threads ());
592 if (!img->temp_row)
593 return NULL;
594 }
595 // if image is huge or converted pixels are not likely to be reused then don't cache converted pixels
596 if (liq_image_should_use_low_memory (img, !img->temp_row
597 && !attr->use_contrast_maps && !attr->use_dither_map)) {
598 verbose_print (attr, " conserving memory");
599 if (!liq_image_use_low_memory (img))
600 return NULL;
601 }
602
603 if (img->min_opaque_val < 1.f) {
604 verbose_print (attr,
605 " Working around IE6 bug by making image less transparent...");
606 }
607
608 return img;
609 }
610
611 LIQ_EXPORT liq_error
liq_image_set_memory_ownership(liq_image * img,int ownership_flags)612 liq_image_set_memory_ownership (liq_image * img, int ownership_flags)
613 {
614 if (!CHECK_STRUCT_TYPE (img, liq_image))
615 return LIQ_INVALID_POINTER;
616 if (!img->rows || !ownership_flags
617 || (ownership_flags & ~(LIQ_OWN_ROWS | LIQ_OWN_PIXELS))) {
618 return LIQ_VALUE_OUT_OF_RANGE;
619 }
620
621 if (ownership_flags & LIQ_OWN_ROWS) {
622 if (img->free_rows_internal)
623 return LIQ_VALUE_OUT_OF_RANGE;
624 img->free_rows = true;
625 }
626
627 if (ownership_flags & LIQ_OWN_PIXELS) {
628 img->free_pixels = true;
629 if (!img->pixels) {
630 // for simplicity of this API there's no explicit bitmap argument,
631 // so the row with the lowest address is assumed to be at the start of the bitmap
632 img->pixels = img->rows[0];
633 for (unsigned int i = 1; i < img->height; i++) {
634 img->pixels = MIN (img->pixels, img->rows[i]);
635 }
636 }
637 }
638
639 return LIQ_OK;
640 }
641
642 static bool
check_image_size(const liq_attr * attr,const int width,const int height)643 check_image_size (const liq_attr * attr, const int width, const int height)
644 {
645 if (!CHECK_STRUCT_TYPE (attr, liq_attr)) {
646 return false;
647 }
648
649 if (width <= 0 || height <= 0) {
650 liq_log_error (attr, "width and height must be > 0");
651 return false;
652 }
653 if (width > INT_MAX / height) {
654 liq_log_error (attr, "image too large");
655 return false;
656 }
657 return true;
658 }
659
660 LIQ_EXPORT liq_image *
liq_image_create_custom(liq_attr * attr,liq_image_get_rgba_row_callback * row_callback,void * user_info,int width,int height,double gamma)661 liq_image_create_custom (liq_attr * attr,
662 liq_image_get_rgba_row_callback * row_callback, void *user_info, int width,
663 int height, double gamma)
664 {
665 if (!check_image_size (attr, width, height)) {
666 return NULL;
667 }
668 return liq_image_create_internal (attr, NULL, row_callback, user_info, width,
669 height, gamma);
670 }
671
672 LIQ_EXPORT liq_image *
liq_image_create_rgba_rows(liq_attr * attr,void * rows[],int width,int height,double gamma)673 liq_image_create_rgba_rows (liq_attr * attr, void *rows[], int width,
674 int height, double gamma)
675 {
676 if (!check_image_size (attr, width, height)) {
677 return NULL;
678 }
679
680 for (int i = 0; i < height; i++) {
681 if (!CHECK_USER_POINTER (rows + i) || !CHECK_USER_POINTER (rows[i])) {
682 liq_log_error (attr, "invalid row pointers");
683 return NULL;
684 }
685 }
686 return liq_image_create_internal (attr, (rgba_pixel **) rows, NULL, NULL,
687 width, height, gamma);
688 }
689
690 LIQ_EXPORT liq_image *
liq_image_create_rgba(liq_attr * attr,void * bitmap,int width,int height,double gamma)691 liq_image_create_rgba (liq_attr * attr, void *bitmap, int width, int height,
692 double gamma)
693 {
694 rgba_pixel *pixels;
695 rgba_pixel **rows;
696 liq_image *image;
697
698 if (!check_image_size (attr, width, height)) {
699 return NULL;
700 }
701 if (!CHECK_USER_POINTER (bitmap)) {
702 liq_log_error (attr, "invalid bitmap pointer");
703 return NULL;
704 }
705
706 pixels = bitmap;
707 rows = attr->malloc (sizeof (rows[0]) * height);
708 if (!rows)
709 return NULL;
710
711 for (int i = 0; i < height; i++) {
712 rows[i] = pixels + width * i;
713 }
714
715 image =
716 liq_image_create_internal (attr, rows, NULL, NULL, width, height, gamma);
717 image->free_rows = true;
718 image->free_rows_internal = true;
719 return image;
720 }
721
722 NEVER_INLINE LIQ_EXPORT void
723 liq_executing_user_callback (liq_image_get_rgba_row_callback * callback,
724 liq_color * temp_row, int row, int width, void *user_info);
725 LIQ_EXPORT void
liq_executing_user_callback(liq_image_get_rgba_row_callback * callback,liq_color * temp_row,int row,int width,void * user_info)726 liq_executing_user_callback (liq_image_get_rgba_row_callback * callback,
727 liq_color * temp_row, int row, int width, void *user_info)
728 {
729 assert (callback);
730 assert (temp_row);
731 callback (temp_row, row, width, user_info);
732 }
733
734 inline static bool
liq_image_can_use_rows(liq_image * img)735 liq_image_can_use_rows (liq_image * img)
736 {
737 const bool iebug = img->min_opaque_val < 1.f;
738 return (img->rows && !iebug);
739 }
740
741 static const rgba_pixel *
liq_image_get_row_rgba(liq_image * img,unsigned int row)742 liq_image_get_row_rgba (liq_image * img, unsigned int row)
743 {
744 rgba_pixel *temp_row;
745 if (liq_image_can_use_rows (img)) {
746 return img->rows[row];
747 }
748
749 assert (img->temp_row);
750 temp_row = img->temp_row + img->width * omp_get_thread_num ();
751 if (img->rows) {
752 memcpy (temp_row, img->rows[row], img->width * sizeof (temp_row[0]));
753 } else {
754 liq_executing_user_callback (img->row_callback, (liq_color *) temp_row, row,
755 img->width, img->row_callback_user_info);
756 }
757
758 if (img->min_opaque_val < 1.f)
759 modify_alpha (img, temp_row);
760 return temp_row;
761 }
762
763 static void
convert_row_to_f(liq_image * img,f_pixel * row_f_pixels,const unsigned int row,const float gamma_lut[])764 convert_row_to_f (liq_image * img, f_pixel * row_f_pixels,
765 const unsigned int row, const float gamma_lut[])
766 {
767 assert (row_f_pixels);
768 assert (!USE_SSE || 0 == ((uintptr_t) row_f_pixels & 15));
769
770 {
771 const rgba_pixel *const row_pixels = liq_image_get_row_rgba (img, row);
772 unsigned int col;
773
774 for (col = 0; col < img->width; col++) {
775 row_f_pixels[col] = to_f (gamma_lut, row_pixels[col]);
776 }
777 }
778 }
779
780 static const f_pixel *
liq_image_get_row_f(liq_image * img,unsigned int row)781 liq_image_get_row_f (liq_image * img, unsigned int row)
782 {
783 if (!img->f_pixels) {
784 if (img->temp_f_row) {
785 float gamma_lut[256];
786 f_pixel *row_for_thread;
787
788 to_f_set_gamma (gamma_lut, img->gamma);
789 row_for_thread = img->temp_f_row + img->width * omp_get_thread_num ();
790 convert_row_to_f (img, row_for_thread, row, gamma_lut);
791
792 return row_for_thread;
793 }
794
795 assert (omp_get_thread_num () == 0);
796 if (!liq_image_should_use_low_memory (img, false)) {
797 img->f_pixels =
798 img->malloc (sizeof (img->f_pixels[0]) * img->width * img->height);
799 }
800 if (!img->f_pixels) {
801 if (!liq_image_use_low_memory (img))
802 return NULL;
803 return liq_image_get_row_f (img, row);
804 }
805
806 {
807 float gamma_lut[256];
808 to_f_set_gamma (gamma_lut, img->gamma);
809 for (unsigned int i = 0; i < img->height; i++) {
810 convert_row_to_f (img, &img->f_pixels[i * img->width], i, gamma_lut);
811 }
812 }
813 }
814 return img->f_pixels + img->width * row;
815 }
816
817 LIQ_EXPORT int
liq_image_get_width(const liq_image * input_image)818 liq_image_get_width (const liq_image * input_image)
819 {
820 if (!CHECK_STRUCT_TYPE (input_image, liq_image))
821 return -1;
822 return input_image->width;
823 }
824
825 LIQ_EXPORT int
liq_image_get_height(const liq_image * input_image)826 liq_image_get_height (const liq_image * input_image)
827 {
828 if (!CHECK_STRUCT_TYPE (input_image, liq_image))
829 return -1;
830 return input_image->height;
831 }
832
833 typedef void free_func (void *);
834
835 static free_func *
get_default_free_func(liq_image * img)836 get_default_free_func (liq_image * img)
837 {
838 // When default allocator is used then user-supplied pointers must be freed with free()
839 if (img->free_rows_internal || img->free != liq_aligned_free) {
840 return img->free;
841 }
842 return free;
843 }
844
845 static void
liq_image_free_rgba_source(liq_image * input_image)846 liq_image_free_rgba_source (liq_image * input_image)
847 {
848 if (input_image->free_pixels && input_image->pixels) {
849 get_default_free_func (input_image) (input_image->pixels);
850 input_image->pixels = NULL;
851 }
852
853 if (input_image->free_rows && input_image->rows) {
854 get_default_free_func (input_image) (input_image->rows);
855 input_image->rows = NULL;
856 }
857 }
858
859 LIQ_EXPORT void
liq_image_destroy(liq_image * input_image)860 liq_image_destroy (liq_image * input_image)
861 {
862 if (!CHECK_STRUCT_TYPE (input_image, liq_image))
863 return;
864
865 liq_image_free_rgba_source (input_image);
866
867 if (input_image->noise) {
868 input_image->free (input_image->noise);
869 }
870
871 if (input_image->edges) {
872 input_image->free (input_image->edges);
873 }
874
875 if (input_image->dither_map) {
876 input_image->free (input_image->dither_map);
877 }
878
879 if (input_image->f_pixels) {
880 input_image->free (input_image->f_pixels);
881 }
882
883 if (input_image->temp_row) {
884 input_image->free (input_image->temp_row);
885 }
886
887 if (input_image->temp_f_row) {
888 input_image->free (input_image->temp_f_row);
889 }
890
891 input_image->magic_header = liq_freed_magic;
892 input_image->free (input_image);
893 }
894
895 LIQ_EXPORT liq_result *
liq_quantize_image(liq_attr * attr,liq_image * img)896 liq_quantize_image (liq_attr * attr, liq_image * img)
897 {
898 histogram *hist;
899 liq_result *result;
900
901 if (!CHECK_STRUCT_TYPE (attr, liq_attr))
902 return NULL;
903 if (!CHECK_STRUCT_TYPE (img, liq_image)) {
904 liq_log_error (attr, "invalid image pointer");
905 return NULL;
906 }
907
908 hist = get_histogram (img, attr);
909 if (!hist) {
910 return NULL;
911 }
912
913 result = pngquant_quantize (hist, attr, img);
914
915 pam_freeacolorhist (hist);
916 return result;
917 }
918
919 LIQ_EXPORT liq_error
liq_set_dithering_level(liq_result * res,float dither_level)920 liq_set_dithering_level (liq_result * res, float dither_level)
921 {
922 if (!CHECK_STRUCT_TYPE (res, liq_result))
923 return LIQ_INVALID_POINTER;
924
925 if (res->remapping) {
926 liq_remapping_result_destroy (res->remapping);
927 res->remapping = NULL;
928 }
929
930 if (res->dither_level < 0 || res->dither_level > 1.0f)
931 return LIQ_VALUE_OUT_OF_RANGE;
932 res->dither_level = dither_level;
933 return LIQ_OK;
934 }
935
936 static liq_remapping_result *
liq_remapping_result_create(liq_result * result)937 liq_remapping_result_create (liq_result * result)
938 {
939 liq_remapping_result *res;
940
941 if (!CHECK_STRUCT_TYPE (result, liq_result)) {
942 return NULL;
943 }
944
945 res = result->malloc (sizeof (liq_remapping_result));
946 if (!res)
947 return NULL;
948 *res = (liq_remapping_result) {
949 .magic_header = liq_remapping_result_magic,.malloc = result->malloc,.free =
950 result->free,.dither_level = result->dither_level,.use_dither_map =
951 result->use_dither_map,.palette_error = result->palette_error,.gamma =
952 result->gamma,.palette = pam_duplicate_colormap (result->palette),};
953 return res;
954 }
955
956 LIQ_EXPORT double
liq_get_output_gamma(const liq_result * result)957 liq_get_output_gamma (const liq_result * result)
958 {
959 if (!CHECK_STRUCT_TYPE (result, liq_result))
960 return -1;
961
962 return result->gamma;
963 }
964
965 static void
liq_remapping_result_destroy(liq_remapping_result * result)966 liq_remapping_result_destroy (liq_remapping_result * result)
967 {
968 if (!CHECK_STRUCT_TYPE (result, liq_remapping_result))
969 return;
970
971 if (result->palette)
972 pam_freecolormap (result->palette);
973 if (result->pixels)
974 result->free (result->pixels);
975
976 result->magic_header = liq_freed_magic;
977 result->free (result);
978 }
979
980 LIQ_EXPORT void
liq_result_destroy(liq_result * res)981 liq_result_destroy (liq_result * res)
982 {
983 if (!CHECK_STRUCT_TYPE (res, liq_result))
984 return;
985
986 memset (&res->int_palette, 0, sizeof (liq_palette));
987
988 if (res->remapping) {
989 memset (&res->remapping->int_palette, 0, sizeof (liq_palette));
990 liq_remapping_result_destroy (res->remapping);
991 }
992
993 pam_freecolormap (res->palette);
994
995 res->magic_header = liq_freed_magic;
996 res->free (res);
997 }
998
999 LIQ_EXPORT double
liq_get_quantization_error(liq_result * result)1000 liq_get_quantization_error (liq_result * result)
1001 {
1002 if (!CHECK_STRUCT_TYPE (result, liq_result))
1003 return -1;
1004
1005 if (result->palette_error >= 0) {
1006 return result->palette_error * 65536.0 / 6.0;
1007 }
1008
1009 if (result->remapping && result->remapping->palette_error >= 0) {
1010 return result->remapping->palette_error * 65536.0 / 6.0;
1011 }
1012
1013 return result->palette_error;
1014 }
1015
1016 LIQ_EXPORT int
liq_get_quantization_quality(liq_result * result)1017 liq_get_quantization_quality (liq_result * result)
1018 {
1019 if (!CHECK_STRUCT_TYPE (result, liq_result))
1020 return -1;
1021
1022 if (result->palette_error >= 0) {
1023 return mse_to_quality (result->palette_error);
1024 }
1025
1026 if (result->remapping && result->remapping->palette_error >= 0) {
1027 return mse_to_quality (result->remapping->palette_error);
1028 }
1029
1030 return result->palette_error;
1031 }
1032
1033 static int
compare_popularity(const void * ch1,const void * ch2)1034 compare_popularity (const void *ch1, const void *ch2)
1035 {
1036 const float v1 = ((const colormap_item *) ch1)->popularity;
1037 const float v2 = ((const colormap_item *) ch2)->popularity;
1038 return v1 > v2 ? -1 : 1;
1039 }
1040
1041 static void
sort_palette_qsort(colormap * map,int start,int nelem)1042 sort_palette_qsort (colormap * map, int start, int nelem)
1043 {
1044 qsort (map->palette + start, nelem, sizeof (map->palette[0]),
1045 compare_popularity);
1046 }
1047
1048 #define SWAP_PALETTE(map, a,b) { \
1049 const colormap_item tmp = (map)->palette[(a)]; \
1050 (map)->palette[(a)] = (map)->palette[(b)]; \
1051 (map)->palette[(b)] = tmp; }
1052
1053 static void
sort_palette(colormap * map,const liq_attr * options)1054 sort_palette (colormap * map, const liq_attr * options)
1055 {
1056 unsigned int i;
1057 unsigned int num_transparent;
1058
1059 /*
1060 ** Step 3.5 [GRR]: remap the palette colors so that all entries with
1061 ** the maximal alpha value (i.e., fully opaque) are at the end and can
1062 ** therefore be omitted from the tRNS chunk.
1063 */
1064 if (options->last_index_transparent) {
1065 for (i = 0; i < map->colors; i++) {
1066 if (map->palette[i].acolor.a < 1.0 / 256.0) {
1067 const unsigned int old = i, transparent_dest = map->colors - 1;
1068
1069 SWAP_PALETTE (map, transparent_dest, old);
1070
1071 /* colors sorted by popularity make pngs slightly more compressible */
1072 sort_palette_qsort (map, 0, map->colors - 1);
1073 return;
1074 }
1075 }
1076 }
1077 /* move transparent colors to the beginning to shrink trns chunk */
1078 num_transparent = 0;
1079 for (i = 0; i < map->colors; i++) {
1080 if (map->palette[i].acolor.a < 255.0 / 256.0) {
1081 // current transparent color is swapped with earlier opaque one
1082 if (i != num_transparent) {
1083 SWAP_PALETTE (map, num_transparent, i);
1084 i--;
1085 }
1086 num_transparent++;
1087 }
1088 }
1089
1090 liq_verbose_printf (options,
1091 " eliminated opaque tRNS-chunk entries...%d entr%s transparent",
1092 num_transparent, (num_transparent == 1) ? "y" : "ies");
1093
1094 /* colors sorted by popularity make pngs slightly more compressible
1095 * opaque and transparent are sorted separately
1096 */
1097 sort_palette_qsort (map, 0, num_transparent);
1098 sort_palette_qsort (map, num_transparent, map->colors - num_transparent);
1099
1100 if (map->colors > 16) {
1101 SWAP_PALETTE (map, 7, 1); // slightly improves compression
1102 SWAP_PALETTE (map, 8, 2);
1103 SWAP_PALETTE (map, 9, 3);
1104 }
1105 }
1106
1107 inline static unsigned int
posterize_channel(unsigned int color,unsigned int bits)1108 posterize_channel (unsigned int color, unsigned int bits)
1109 {
1110 return (color & ~((1 << bits) - 1)) | (color >> (8 - bits));
1111 }
1112
1113 static void
set_rounded_palette(liq_palette * const dest,colormap * const map,const double gamma,unsigned int posterize)1114 set_rounded_palette (liq_palette * const dest, colormap * const map,
1115 const double gamma, unsigned int posterize)
1116 {
1117 float gamma_lut[256];
1118 to_f_set_gamma (gamma_lut, gamma);
1119
1120 dest->count = map->colors;
1121 for (unsigned int x = 0; x < map->colors; ++x) {
1122 rgba_pixel px = to_rgb (gamma, map->palette[x].acolor);
1123
1124 px.r = posterize_channel (px.r, posterize);
1125 px.g = posterize_channel (px.g, posterize);
1126 px.b = posterize_channel (px.b, posterize);
1127 px.a = posterize_channel (px.a, posterize);
1128
1129 map->palette[x].acolor = to_f (gamma_lut, px); /* saves rounding error introduced by to_rgb, which makes remapping & dithering more accurate */
1130
1131 if (!px.a) {
1132 px.r = 'L';
1133 px.g = 'i';
1134 px.b = 'q';
1135 }
1136
1137 dest->entries[x] = (liq_color) {
1138 .r = px.r,.g = px.g,.b = px.b,.a = px.a};
1139 }
1140 }
1141
1142 LIQ_EXPORT const liq_palette *
liq_get_palette(liq_result * result)1143 liq_get_palette (liq_result * result)
1144 {
1145 if (!CHECK_STRUCT_TYPE (result, liq_result))
1146 return NULL;
1147
1148 if (result->remapping && result->remapping->int_palette.count) {
1149 return &result->remapping->int_palette;
1150 }
1151
1152 if (!result->int_palette.count) {
1153 set_rounded_palette (&result->int_palette, result->palette, result->gamma,
1154 result->min_posterization_output);
1155 }
1156 return &result->int_palette;
1157 }
1158
1159 #define MAX_THREADS 8
1160
1161 static float
remap_to_palette(liq_image * const input_image,unsigned char * const * const output_pixels,colormap * const map,const bool fast)1162 remap_to_palette (liq_image * const input_image,
1163 unsigned char *const *const output_pixels, colormap * const map,
1164 const bool fast)
1165 {
1166 const int rows = input_image->height;
1167 const unsigned int cols = input_image->width;
1168 const float min_opaque_val = input_image->min_opaque_val;
1169 double remapping_error = 0;
1170
1171 if (!liq_image_get_row_f (input_image, 0)) { // trigger lazy conversion
1172 return -1;
1173 }
1174
1175 {
1176 struct nearest_map *const n = nearest_init (map, fast);
1177
1178 const unsigned int max_threads = MIN (MAX_THREADS, omp_get_max_threads ());
1179 viter_state *average_color =
1180 g_alloca (sizeof (viter_state) * (VITER_CACHE_LINE_GAP +
1181 map->colors) * MAX_THREADS);
1182 unsigned int row, col;
1183
1184 viter_init (map, max_threads, average_color);
1185
1186 #pragma omp parallel for if (rows*cols > 3000) \
1187 schedule(static) default(none) shared(average_color) reduction(+:remapping_error)
1188 for (row = 0; row < rows; ++row) {
1189 const f_pixel *const row_pixels = liq_image_get_row_f (input_image, row);
1190 unsigned int last_match = 0;
1191 for (col = 0; col < cols; ++col) {
1192 f_pixel px = row_pixels[col];
1193 float diff;
1194
1195 output_pixels[row][col] = last_match =
1196 nearest_search (n, px, last_match, min_opaque_val, &diff);
1197
1198 remapping_error += diff;
1199 viter_update_color (px, 1.0, map, last_match, omp_get_thread_num (),
1200 average_color);
1201 }
1202 }
1203
1204 viter_finalize (map, max_threads, average_color);
1205
1206 nearest_free (n);
1207 }
1208
1209 return remapping_error / (input_image->width * input_image->height);
1210 }
1211
1212 inline static f_pixel
get_dithered_pixel(const float dither_level,const float max_dither_error,const f_pixel thiserr,const f_pixel px)1213 get_dithered_pixel (const float dither_level, const float max_dither_error,
1214 const f_pixel thiserr, const f_pixel px)
1215 {
1216 /* Use Floyd-Steinberg errors to adjust actual color. */
1217 const float sr = thiserr.r * dither_level,
1218 sg = thiserr.g * dither_level,
1219 sb = thiserr.b * dither_level, sa = thiserr.a * dither_level;
1220 float a;
1221 float ratio = 1.0;
1222 float dither_error;
1223
1224 // allowing some overflow prevents undithered bands caused by clamping of all channels
1225 if (px.r + sr > 1.03)
1226 ratio = MIN (ratio, (1.03 - px.r) / sr);
1227 else if (px.r + sr < 0)
1228 ratio = MIN (ratio, px.r / -sr);
1229 if (px.g + sg > 1.03)
1230 ratio = MIN (ratio, (1.03 - px.g) / sg);
1231 else if (px.g + sg < 0)
1232 ratio = MIN (ratio, px.g / -sg);
1233 if (px.b + sb > 1.03)
1234 ratio = MIN (ratio, (1.03 - px.b) / sb);
1235 else if (px.b + sb < 0)
1236 ratio = MIN (ratio, px.b / -sb);
1237
1238 a = px.a + sa;
1239 if (a > 1.0) {
1240 a = 1.0;
1241 } else if (a < 0) {
1242 a = 0;
1243 }
1244 // If dithering error is crazy high, don't propagate it that much
1245 // This prevents crazy geen pixels popping out of the blue (or red or black! ;)
1246 dither_error = sr * sr + sg * sg + sb * sb + sa * sa;
1247 if (dither_error > max_dither_error) {
1248 ratio *= 0.8;
1249 } else if (dither_error < 2.f / 256.f / 256.f) {
1250 // don't dither areas that don't have noticeable error — makes file smaller
1251 return px;
1252 }
1253
1254 return (f_pixel) {
1255 .r = px.r + sr * ratio,.g = px.g + sg * ratio,.b = px.b + sb * ratio,.a = a,};
1256 }
1257
1258 /**
1259 Uses edge/noise map to apply dithering only to flat areas. Dithering on edges creates jagged lines, and noisy areas are "naturally" dithered.
1260
1261 If output_image_is_remapped is true, only pixels noticeably changed by error diffusion will be written to output image.
1262 */
1263 static void
remap_to_palette_floyd(liq_image * input_image,unsigned char * const output_pixels[],const colormap * map,const float max_dither_error,const bool use_dither_map,const bool output_image_is_remapped,float base_dithering_level)1264 remap_to_palette_floyd (liq_image * input_image,
1265 unsigned char *const output_pixels[], const colormap * map,
1266 const float max_dither_error, const bool use_dither_map,
1267 const bool output_image_is_remapped, float base_dithering_level)
1268 {
1269 const unsigned int rows = input_image->height, cols = input_image->width;
1270 const unsigned char *dither_map =
1271 use_dither_map ? (input_image->
1272 dither_map ? input_image->dither_map : input_image->edges) : NULL;
1273 const float min_opaque_val = input_image->min_opaque_val;
1274
1275 const colormap_item *acolormap = map->palette;
1276
1277 struct nearest_map *const n = nearest_init (map, false);
1278 unsigned int col;
1279
1280 /* Initialize Floyd-Steinberg error vectors. */
1281 f_pixel *restrict thiserr, *restrict nexterr;
1282 thiserr = input_image->malloc ((cols + 2) * sizeof (*thiserr) * 2); // +2 saves from checking out of bounds access
1283 nexterr = thiserr + (cols + 2);
1284 srand (12345); /* deterministic dithering is better for comparing results */
1285 if (!thiserr)
1286 return;
1287
1288 for (col = 0; col < cols + 2; ++col) {
1289 const double rand_max = RAND_MAX;
1290 thiserr[col].r = ((double) rand () - rand_max / 2.0) / rand_max / 255.0;
1291 thiserr[col].g = ((double) rand () - rand_max / 2.0) / rand_max / 255.0;
1292 thiserr[col].b = ((double) rand () - rand_max / 2.0) / rand_max / 255.0;
1293 thiserr[col].a = ((double) rand () - rand_max / 2.0) / rand_max / 255.0;
1294 }
1295
1296 // response to this value is non-linear and without it any value < 0.8 would give almost no dithering
1297 base_dithering_level =
1298 1.0 - (1.0 - base_dithering_level) * (1.0 - base_dithering_level) * (1.0 -
1299 base_dithering_level);
1300
1301 if (dither_map) {
1302 base_dithering_level *= 1.0 / 255.0; // convert byte to float
1303 }
1304 base_dithering_level *= 15.0 / 16.0; // prevent small errors from accumulating
1305
1306 {
1307 bool fs_direction = true;
1308 unsigned int last_match = 0;
1309 for (unsigned int row = 0; row < rows; ++row) {
1310 unsigned int col = (fs_direction) ? 0 : (cols - 1);
1311 const f_pixel *const row_pixels = liq_image_get_row_f (input_image, row);
1312
1313 memset (nexterr, 0, (cols + 2) * sizeof (*nexterr));
1314
1315 do {
1316 float dither_level = base_dithering_level;
1317 f_pixel spx, xp, err;
1318 unsigned int guessed_match;
1319
1320 if (dither_map) {
1321 dither_level *= dither_map[row * cols + col];
1322 }
1323
1324 spx =
1325 get_dithered_pixel (dither_level, max_dither_error,
1326 thiserr[col + 1], row_pixels[col]);
1327
1328 guessed_match =
1329 output_image_is_remapped ? output_pixels[row][col] : last_match;
1330 output_pixels[row][col] = last_match =
1331 nearest_search (n, spx, guessed_match, min_opaque_val, NULL);
1332
1333 xp = acolormap[last_match].acolor;
1334 err.r = spx.r - xp.r;
1335 err.g = spx.r - xp.g;
1336 err.b = spx.r - xp.b;
1337 err.a = spx.r - xp.a;
1338
1339 // If dithering error is crazy high, don't propagate it that much
1340 // This prevents crazy geen pixels popping out of the blue (or red or black! ;)
1341 if (err.r * err.r + err.g * err.g + err.b * err.b + err.a * err.a >
1342 max_dither_error) {
1343 dither_level *= 0.75;
1344 }
1345
1346 {
1347 const float colorimp =
1348 (3.0f + acolormap[last_match].acolor.a) / 4.0f * dither_level;
1349 err.r *= colorimp;
1350 err.g *= colorimp;
1351 err.b *= colorimp;
1352 err.a *= dither_level;
1353 }
1354
1355 /* Propagate Floyd-Steinberg error terms. */
1356 if (fs_direction) {
1357 thiserr[col + 2].a += err.a * (7.f / 16.f);
1358 thiserr[col + 2].r += err.r * (7.f / 16.f);
1359 thiserr[col + 2].g += err.g * (7.f / 16.f);
1360 thiserr[col + 2].b += err.b * (7.f / 16.f);
1361
1362 nexterr[col + 2].a = err.a * (1.f / 16.f);
1363 nexterr[col + 2].r = err.r * (1.f / 16.f);
1364 nexterr[col + 2].g = err.g * (1.f / 16.f);
1365 nexterr[col + 2].b = err.b * (1.f / 16.f);
1366
1367 nexterr[col + 1].a += err.a * (5.f / 16.f);
1368 nexterr[col + 1].r += err.r * (5.f / 16.f);
1369 nexterr[col + 1].g += err.g * (5.f / 16.f);
1370 nexterr[col + 1].b += err.b * (5.f / 16.f);
1371
1372 nexterr[col].a += err.a * (3.f / 16.f);
1373 nexterr[col].r += err.r * (3.f / 16.f);
1374 nexterr[col].g += err.g * (3.f / 16.f);
1375 nexterr[col].b += err.b * (3.f / 16.f);
1376
1377 } else {
1378 thiserr[col].a += err.a * (7.f / 16.f);
1379 thiserr[col].r += err.r * (7.f / 16.f);
1380 thiserr[col].g += err.g * (7.f / 16.f);
1381 thiserr[col].b += err.b * (7.f / 16.f);
1382
1383 nexterr[col].a = err.a * (1.f / 16.f);
1384 nexterr[col].r = err.r * (1.f / 16.f);
1385 nexterr[col].g = err.g * (1.f / 16.f);
1386 nexterr[col].b = err.b * (1.f / 16.f);
1387
1388 nexterr[col + 1].a += err.a * (5.f / 16.f);
1389 nexterr[col + 1].r += err.r * (5.f / 16.f);
1390 nexterr[col + 1].g += err.g * (5.f / 16.f);
1391 nexterr[col + 1].b += err.b * (5.f / 16.f);
1392
1393 nexterr[col + 2].a += err.a * (3.f / 16.f);
1394 nexterr[col + 2].r += err.r * (3.f / 16.f);
1395 nexterr[col + 2].g += err.g * (3.f / 16.f);
1396 nexterr[col + 2].b += err.b * (3.f / 16.f);
1397 }
1398
1399 // remapping is done in zig-zag
1400 if (fs_direction) {
1401 ++col;
1402 if (col >= cols)
1403 break;
1404 } else {
1405 if (col <= 0)
1406 break;
1407 --col;
1408 }
1409 } while (1);
1410
1411 {
1412 f_pixel *const temperr = thiserr;
1413 thiserr = nexterr;
1414 nexterr = temperr;
1415 }
1416
1417 fs_direction = !fs_direction;
1418 }
1419 }
1420
1421 input_image->free (MIN (thiserr, nexterr)); // MIN because pointers were swapped
1422 nearest_free (n);
1423 }
1424
1425 /* fixed colors are always included in the palette, so it would be wasteful to duplicate them in palette from histogram */
1426 static void
remove_fixed_colors_from_histogram(histogram * hist,const liq_image * input_image,const float target_mse)1427 remove_fixed_colors_from_histogram (histogram * hist,
1428 const liq_image * input_image, const float target_mse)
1429 {
1430 const float max_difference = MAX (target_mse / 2.0, 2.0 / 256.0 / 256.0);
1431 if (input_image->fixed_colors_count) {
1432 for (int j = 0; j < hist->size; j++) {
1433 for (unsigned int i = 0; i < input_image->fixed_colors_count; i++) {
1434 if (colordifference (hist->achv[j].acolor,
1435 input_image->fixed_colors[i]) < max_difference) {
1436 hist->achv[j] = hist->achv[--hist->size]; // remove color from histogram by overwriting with the last entry
1437 j--;
1438 break; // continue searching histogram
1439 }
1440 }
1441 }
1442 }
1443 }
1444
1445 /* histogram contains information how many times each color is present in the image, weighted by importance_map */
1446 static histogram *
get_histogram(liq_image * input_image,const liq_attr * options)1447 get_histogram (liq_image * input_image, const liq_attr * options)
1448 {
1449 unsigned int ignorebits =
1450 MAX (options->min_posterization_output, options->min_posterization_input);
1451 const unsigned int cols = input_image->width, rows = input_image->height;
1452
1453 if (!input_image->noise && options->use_contrast_maps) {
1454 contrast_maps (input_image);
1455 }
1456
1457 /*
1458 ** Step 2: attempt to make a histogram of the colors, unclustered.
1459 ** If at first we don't succeed, increase ignorebits to increase color
1460 ** coherence and try again.
1461 */
1462
1463 {
1464 unsigned int maxcolors = options->max_histogram_entries;
1465
1466 struct acolorhash_table *acht;
1467 const bool all_rows_at_once = liq_image_can_use_rows (input_image);
1468 histogram *hist;
1469
1470 do {
1471 acht =
1472 pam_allocacolorhash (maxcolors, rows * cols, ignorebits,
1473 options->malloc, options->free);
1474 if (!acht)
1475 return NULL;
1476
1477 // histogram uses noise contrast map for importance. Color accuracy in noisy areas is not very important.
1478 // noise map does not include edges to avoid ruining anti-aliasing
1479 for (unsigned int row = 0; row < rows; row++) {
1480 bool added_ok;
1481 if (all_rows_at_once) {
1482 added_ok =
1483 pam_computeacolorhash (acht,
1484 (const rgba_pixel * const *) input_image->rows, cols, rows,
1485 input_image->noise);
1486 if (added_ok)
1487 break;
1488 } else {
1489 const rgba_pixel *rows_p[1] =
1490 { liq_image_get_row_rgba (input_image, row) };
1491 added_ok =
1492 pam_computeacolorhash (acht, rows_p, cols, 1,
1493 input_image->noise ? &input_image->noise[row * cols] : NULL);
1494 }
1495 if (!added_ok) {
1496 ignorebits++;
1497 liq_verbose_printf (options,
1498 " too many colors! Scaling colors to improve clustering... %d",
1499 ignorebits);
1500 pam_freeacolorhash (acht);
1501 acht = NULL;
1502 break;
1503 }
1504 }
1505 } while (!acht);
1506
1507 if (input_image->noise) {
1508 input_image->free (input_image->noise);
1509 input_image->noise = NULL;
1510 }
1511
1512 if (input_image->free_pixels && input_image->f_pixels) {
1513 liq_image_free_rgba_source (input_image); // bow can free the RGBA source if copy has been made in f_pixels
1514 }
1515
1516 hist =
1517 pam_acolorhashtoacolorhist (acht, input_image->gamma, options->malloc,
1518 options->free);
1519 pam_freeacolorhash (acht);
1520 if (hist) {
1521 liq_verbose_printf (options, " made histogram...%d colors found",
1522 hist->size);
1523 remove_fixed_colors_from_histogram (hist, input_image,
1524 options->target_mse);
1525 }
1526
1527 return hist;
1528 }
1529 }
1530
1531 static void
modify_alpha(liq_image * input_image,rgba_pixel * const row_pixels)1532 modify_alpha (liq_image * input_image, rgba_pixel * const row_pixels)
1533 {
1534 /* IE6 makes colors with even slightest transparency completely transparent,
1535 thus to improve situation in IE, make colors that are less than ~10% transparent
1536 completely opaque */
1537
1538 const float min_opaque_val = input_image->min_opaque_val;
1539 const float almost_opaque_val = min_opaque_val * 169.f / 256.f;
1540 const unsigned int almost_opaque_val_int =
1541 (min_opaque_val * 169.f / 256.f) * 255.f;
1542
1543 for (unsigned int col = 0; col < input_image->width; col++) {
1544 const rgba_pixel px = row_pixels[col];
1545
1546 /* ie bug: to avoid visible step caused by forced opaqueness, linearily raise opaqueness of almost-opaque colors */
1547 if (px.a >= almost_opaque_val_int) {
1548 float al = px.a / 255.f;
1549 al = almost_opaque_val + (al - almost_opaque_val) * (1.f -
1550 almost_opaque_val) / (min_opaque_val - almost_opaque_val);
1551 al *= 256.f;
1552 row_pixels[col].a = al >= 255.f ? 255 : al;
1553 }
1554 }
1555 }
1556
1557 /**
1558 Builds two maps:
1559 noise - approximation of areas with high-frequency noise, except straight edges. 1=flat, 0=noisy.
1560 edges - noise map including all edges
1561 */
1562 static void
contrast_maps(liq_image * image)1563 contrast_maps (liq_image * image)
1564 {
1565 const int cols = image->width, rows = image->height;
1566 unsigned char *restrict noise, *restrict edges, *restrict tmp;
1567 const f_pixel *curr_row, *prev_row, *next_row;
1568 int i, j;
1569
1570 if (cols < 4 || rows < 4 || (3 * cols * rows) > LIQ_HIGH_MEMORY_LIMIT) {
1571 return;
1572 }
1573
1574 noise = image->malloc (cols * rows);
1575 edges = image->malloc (cols * rows);
1576 tmp = image->malloc (cols * rows);
1577
1578 if (!noise || !edges || !tmp) {
1579 return;
1580 }
1581
1582 curr_row = prev_row = next_row = liq_image_get_row_f (image, 0);
1583
1584 for (j = 0; j < rows; j++) {
1585 f_pixel prev, curr, next;
1586
1587 prev_row = curr_row;
1588 curr_row = next_row;
1589 next_row = liq_image_get_row_f (image, MIN (rows - 1, j + 1));
1590
1591 curr = curr_row[0];
1592 next = curr;
1593 for (i = 0; i < cols; i++) {
1594 prev = curr;
1595 curr = next;
1596 next = curr_row[MIN (cols - 1, i + 1)];
1597
1598 // contrast is difference between pixels neighbouring horizontally and vertically
1599 {
1600 const float a = fabsf (prev.a + next.a - curr.a * 2.f),
1601 r = fabsf (prev.r + next.r - curr.r * 2.f),
1602 g = fabsf (prev.g + next.g - curr.g * 2.f),
1603 b = fabsf (prev.b + next.b - curr.b * 2.f);
1604
1605 const f_pixel prevl = prev_row[i];
1606 const f_pixel nextl = next_row[i];
1607
1608 const float a1 = fabsf (prevl.a + nextl.a - curr.a * 2.f),
1609 r1 = fabsf (prevl.r + nextl.r - curr.r * 2.f),
1610 g1 = fabsf (prevl.g + nextl.g - curr.g * 2.f),
1611 b1 = fabsf (prevl.b + nextl.b - curr.b * 2.f);
1612
1613 const float horiz = MAX (MAX (a, r), MAX (g, b));
1614 const float vert = MAX (MAX (a1, r1), MAX (g1, b1));
1615 const float edge = MAX (horiz, vert);
1616 float z = edge - fabsf (horiz - vert) * .5f;
1617 z = 1.f - MAX (z, MIN (horiz, vert));
1618 z *= z; // noise is amplified
1619 z *= z;
1620
1621 z *= 256.f;
1622 noise[j * cols + i] = z < 256 ? z : 255;
1623 z = (1.f - edge) * 256.f;
1624 edges[j * cols + i] = z < 256 ? z : 255;
1625 }
1626 }
1627 }
1628
1629 // noise areas are shrunk and then expanded to remove thin edges from the map
1630 liq_max3 (noise, tmp, cols, rows);
1631 liq_max3 (tmp, noise, cols, rows);
1632
1633 liq_blur (noise, tmp, noise, cols, rows, 3);
1634
1635 liq_max3 (noise, tmp, cols, rows);
1636
1637 liq_min3 (tmp, noise, cols, rows);
1638 liq_min3 (noise, tmp, cols, rows);
1639 liq_min3 (tmp, noise, cols, rows);
1640
1641 liq_min3 (edges, tmp, cols, rows);
1642 liq_max3 (tmp, edges, cols, rows);
1643 for (int i = 0; i < cols * rows; i++)
1644 edges[i] = MIN (noise[i], edges[i]);
1645
1646 image->free (tmp);
1647
1648 image->noise = noise;
1649 image->edges = edges;
1650 }
1651
1652 /**
1653 * Builds map of neighbor pixels mapped to the same palette entry
1654 *
1655 * For efficiency/simplicity it mainly looks for same consecutive pixels horizontally
1656 * and peeks 1 pixel above/below. Full 2d algorithm doesn't improve it significantly.
1657 * Correct flood fill doesn't have visually good properties.
1658 */
1659 static void
update_dither_map(unsigned char * const * const row_pointers,liq_image * input_image)1660 update_dither_map (unsigned char *const *const row_pointers,
1661 liq_image * input_image)
1662 {
1663 const unsigned int width = input_image->width;
1664 const unsigned int height = input_image->height;
1665 unsigned char *const edges = input_image->edges;
1666
1667 for (unsigned int row = 0; row < height; row++) {
1668 unsigned char lastpixel = row_pointers[row][0];
1669 unsigned int lastcol = 0;
1670
1671 for (unsigned int col = 1; col < width; col++) {
1672 const unsigned char px = row_pointers[row][col];
1673
1674 if (px != lastpixel || col == width - 1) {
1675 float neighbor_count = 2.5f + col - lastcol;
1676
1677 unsigned int i = lastcol;
1678 while (i < col) {
1679 if (row > 0) {
1680 unsigned char pixelabove = row_pointers[row - 1][i];
1681 if (pixelabove == lastpixel)
1682 neighbor_count += 1.f;
1683 }
1684 if (row < height - 1) {
1685 unsigned char pixelbelow = row_pointers[row + 1][i];
1686 if (pixelbelow == lastpixel)
1687 neighbor_count += 1.f;
1688 }
1689 i++;
1690 }
1691
1692 while (lastcol <= col) {
1693 float e = edges[row * width + lastcol] / 255.f;
1694 e *= 1.f - 2.5f / neighbor_count;
1695 edges[row * width + lastcol++] = e * 255.f;
1696 }
1697 lastpixel = px;
1698 }
1699 }
1700 }
1701 input_image->dither_map = input_image->edges;
1702 input_image->edges = NULL;
1703 }
1704
1705 static colormap *
add_fixed_colors_to_palette(colormap * palette,const int max_colors,const f_pixel fixed_colors[],const int fixed_colors_count,void * (* malloc)(size_t),void (* free)(void *))1706 add_fixed_colors_to_palette (colormap * palette, const int max_colors,
1707 const f_pixel fixed_colors[], const int fixed_colors_count,
1708 void *(*malloc) (size_t), void (*free) (void *))
1709 {
1710 colormap *newpal;
1711 unsigned int i, palette_max;
1712 int j;
1713
1714 if (!fixed_colors_count)
1715 return palette;
1716
1717 newpal =
1718 pam_colormap (MIN (max_colors,
1719 (palette ? palette->colors : 0) + fixed_colors_count), malloc, free);
1720
1721 i = 0;
1722 if (palette && fixed_colors_count < max_colors) {
1723 palette_max = MIN (palette->colors, max_colors - fixed_colors_count);
1724 for (; i < palette_max; i++) {
1725 newpal->palette[i] = palette->palette[i];
1726 }
1727 }
1728 for (j = 0; j < MIN (max_colors, fixed_colors_count); j++) {
1729 newpal->palette[i++] = (colormap_item) {
1730 .acolor = fixed_colors[j],.fixed = true,};
1731 }
1732 if (palette)
1733 pam_freecolormap (palette);
1734 return newpal;
1735 }
1736
1737 static void
adjust_histogram_callback(hist_item * item,float diff)1738 adjust_histogram_callback (hist_item * item, float diff)
1739 {
1740 item->adjusted_weight =
1741 (item->perceptual_weight + item->adjusted_weight) * (sqrtf (1.f + diff));
1742 }
1743
1744 /**
1745 Repeats mediancut with different histogram weights to find palette with minimum error.
1746
1747 feedback_loop_trials controls how long the search will take. < 0 skips the iteration.
1748 */
1749 static colormap *
find_best_palette(histogram * hist,const liq_attr * options,const double max_mse,const f_pixel fixed_colors[],const unsigned int fixed_colors_count,double * palette_error_p)1750 find_best_palette (histogram * hist, const liq_attr * options,
1751 const double max_mse, const f_pixel fixed_colors[],
1752 const unsigned int fixed_colors_count, double *palette_error_p)
1753 {
1754 unsigned int max_colors = options->max_colors;
1755
1756 // if output is posterized it doesn't make sense to aim for perfrect colors, so increase target_mse
1757 // at this point actual gamma is not set, so very conservative posterization estimate is used
1758 const double target_mse = MIN (max_mse, MAX (options->target_mse,
1759 pow ((1 << options->min_posterization_output) / 1024.0, 2)));
1760 int feedback_loop_trials = options->feedback_loop_trials;
1761 colormap *acolormap = NULL;
1762 double least_error = MAX_DIFF;
1763 double target_mse_overshoot = feedback_loop_trials > 0 ? 1.05 : 1.0;
1764 const double percent =
1765 (double) (feedback_loop_trials > 0 ? feedback_loop_trials : 1) / 100.0;
1766
1767 do {
1768 colormap *newmap;
1769 double total_error;
1770
1771 if (hist->size && fixed_colors_count < max_colors) {
1772 newmap =
1773 mediancut (hist, options->min_opaque_val,
1774 max_colors - fixed_colors_count, target_mse * target_mse_overshoot,
1775 MAX (MAX (90.0 / 65536.0, target_mse), least_error) * 1.2,
1776 options->malloc, options->free);
1777 } else {
1778 feedback_loop_trials = 0;
1779 newmap = NULL;
1780 }
1781 newmap =
1782 add_fixed_colors_to_palette (newmap, max_colors, fixed_colors,
1783 fixed_colors_count, options->malloc, options->free);
1784 if (!newmap) {
1785 return NULL;
1786 }
1787
1788 if (feedback_loop_trials <= 0) {
1789 return newmap;
1790 }
1791 // after palette has been created, total error (MSE) is calculated to keep the best palette
1792 // at the same time Voronoi iteration is done to improve the palette
1793 // and histogram weights are adjusted based on remapping error to give more weight to poorly matched colors
1794
1795 {
1796 const bool first_run_of_target_mse = !acolormap && target_mse > 0;
1797 total_error =
1798 viter_do_iteration (hist, newmap, options->min_opaque_val,
1799 first_run_of_target_mse ? NULL : adjust_histogram_callback, !acolormap
1800 || options->fast_palette);
1801 }
1802
1803 // goal is to increase quality or to reduce number of colors used if quality is good enough
1804 if (!acolormap || total_error < least_error || (total_error <= target_mse
1805 && newmap->colors < max_colors)) {
1806 if (acolormap)
1807 pam_freecolormap (acolormap);
1808 acolormap = newmap;
1809
1810 if (total_error < target_mse && total_error > 0) {
1811 // voronoi iteration improves quality above what mediancut aims for
1812 // this compensates for it, making mediancut aim for worse
1813 target_mse_overshoot =
1814 MIN (target_mse_overshoot * 1.25, target_mse / total_error);
1815 }
1816
1817 least_error = total_error;
1818
1819 // if number of colors could be reduced, try to keep it that way
1820 // but allow extra color as a bit of wiggle room in case quality can be improved too
1821 max_colors = MIN (newmap->colors + 1, max_colors);
1822
1823 feedback_loop_trials -= 1; // asymptotic improvement could make it go on forever
1824 } else {
1825 for (unsigned int j = 0; j < hist->size; j++) {
1826 hist->achv[j].adjusted_weight =
1827 (hist->achv[j].perceptual_weight +
1828 hist->achv[j].adjusted_weight) / 2.0;
1829 }
1830
1831 target_mse_overshoot = 1.0;
1832 feedback_loop_trials -= 6;
1833 // if error is really bad, it's unlikely to improve, so end sooner
1834 if (total_error > least_error * 4)
1835 feedback_loop_trials -= 3;
1836 pam_freecolormap (newmap);
1837 }
1838
1839 liq_verbose_printf (options, " selecting colors...%d%%", 100 - MAX (0,
1840 (int) (feedback_loop_trials / percent)));
1841 }
1842 while (feedback_loop_trials > 0);
1843
1844 *palette_error_p = least_error;
1845 return acolormap;
1846 }
1847
1848 static liq_result *
pngquant_quantize(histogram * hist,const liq_attr * options,const liq_image * img)1849 pngquant_quantize (histogram * hist, const liq_attr * options,
1850 const liq_image * img)
1851 {
1852 colormap *acolormap;
1853 double palette_error = -1;
1854
1855 // no point having perfect match with imperfect colors (ignorebits > 0)
1856 const bool fast_palette = options->fast_palette || hist->ignorebits > 0;
1857 const bool few_input_colors =
1858 hist->size + img->fixed_colors_count <= options->max_colors;
1859 liq_result *result;
1860
1861 // If image has few colors to begin with (and no quality degradation is required)
1862 // then it's possible to skip quantization entirely
1863 if (few_input_colors && options->target_mse == 0) {
1864 acolormap = pam_colormap (hist->size, options->malloc, options->free);
1865 for (unsigned int i = 0; i < hist->size; i++) {
1866 acolormap->palette[i].acolor = hist->achv[i].acolor;
1867 acolormap->palette[i].popularity = hist->achv[i].perceptual_weight;
1868 }
1869 acolormap =
1870 add_fixed_colors_to_palette (acolormap, options->max_colors,
1871 img->fixed_colors, img->fixed_colors_count, options->malloc,
1872 options->free);
1873 palette_error = 0;
1874 } else {
1875 const double max_mse = options->max_mse * (few_input_colors ? 0.33 : 1.0); // when degrading image that's already paletted, require much higher improvement, since pal2pal often looks bad and there's little gain
1876 const double iteration_limit = options->voronoi_iteration_limit;
1877 unsigned int iterations = options->voronoi_iterations;
1878
1879 acolormap =
1880 find_best_palette (hist, options, max_mse, img->fixed_colors,
1881 img->fixed_colors_count, &palette_error);
1882 if (!acolormap) {
1883 return NULL;
1884 }
1885 // Voronoi iteration approaches local minimum for the palette
1886 if (!iterations && palette_error < 0 && max_mse < MAX_DIFF)
1887 iterations = 1; // otherwise total error is never calculated and MSE limit won't work
1888
1889 if (iterations) {
1890 double previous_palette_error = MAX_DIFF;
1891 unsigned int i;
1892
1893 // likely_colormap_index (used and set in viter_do_iteration) can't point to index outside colormap
1894 if (acolormap->colors < 256)
1895 for (unsigned int j = 0; j < hist->size; j++) {
1896 if (hist->achv[j].tmp.likely_colormap_index >= acolormap->colors) {
1897 hist->achv[j].tmp.likely_colormap_index = 0; // actual value doesn't matter, as the guess is out of date anyway
1898 }
1899 }
1900
1901 verbose_print (options, " moving colormap towards local minimum");
1902
1903 for (i = 0; i < iterations; i++) {
1904 palette_error =
1905 viter_do_iteration (hist, acolormap, options->min_opaque_val, NULL,
1906 i == 0 || options->fast_palette);
1907
1908 if (fabs (previous_palette_error - palette_error) < iteration_limit) {
1909 break;
1910 }
1911
1912 if (palette_error > max_mse * 1.5) { // probably hopeless
1913 if (palette_error > max_mse * 3.0)
1914 break; // definitely hopeless
1915 i++;
1916 }
1917
1918 previous_palette_error = palette_error;
1919 }
1920 }
1921
1922 if (palette_error > max_mse) {
1923 liq_verbose_printf (options,
1924 " image degradation MSE=%.3f (Q=%d) exceeded limit of %.3f (%d)",
1925 palette_error * 65536.0 / 6.0, mse_to_quality (palette_error),
1926 max_mse * 65536.0 / 6.0, mse_to_quality (max_mse));
1927 pam_freecolormap (acolormap);
1928 return NULL;
1929 }
1930 }
1931
1932 sort_palette (acolormap, options);
1933
1934 result = options->malloc (sizeof (liq_result));
1935 if (!result)
1936 return NULL;
1937 *result = (liq_result) {
1938 .magic_header = liq_result_magic,.malloc = options->malloc,.free =
1939 options->free,.palette = acolormap,.palette_error =
1940 palette_error,.fast_palette = fast_palette,.use_dither_map =
1941 options->use_dither_map,.gamma =
1942 img->gamma,.min_posterization_output =
1943 options->min_posterization_output,};
1944 return result;
1945 }
1946
1947 LIQ_EXPORT liq_error
liq_write_remapped_image(liq_result * result,liq_image * input_image,void * buffer,size_t buffer_size)1948 liq_write_remapped_image (liq_result * result, liq_image * input_image,
1949 void *buffer, size_t buffer_size)
1950 {
1951 size_t required_size;
1952 unsigned char **rows;
1953 unsigned char *buffer_bytes;
1954 unsigned i;
1955
1956 if (!CHECK_STRUCT_TYPE (result, liq_result)) {
1957 return LIQ_INVALID_POINTER;
1958 }
1959 if (!CHECK_STRUCT_TYPE (input_image, liq_image)) {
1960 return LIQ_INVALID_POINTER;
1961 }
1962 if (!CHECK_USER_POINTER (buffer)) {
1963 return LIQ_INVALID_POINTER;
1964 }
1965
1966 required_size = input_image->width * input_image->height;
1967 if (buffer_size < required_size) {
1968 return LIQ_BUFFER_TOO_SMALL;
1969 }
1970
1971 rows = g_alloca (sizeof (unsigned char *) * input_image->height);
1972 buffer_bytes = buffer;
1973 for (i = 0; i < input_image->height; i++) {
1974 rows[i] = &buffer_bytes[input_image->width * i];
1975 }
1976 return liq_write_remapped_image_rows (result, input_image, rows);
1977 }
1978
1979 LIQ_EXPORT liq_error
liq_write_remapped_image_rows(liq_result * quant,liq_image * input_image,unsigned char ** row_pointers)1980 liq_write_remapped_image_rows (liq_result * quant, liq_image * input_image,
1981 unsigned char **row_pointers)
1982 {
1983 unsigned int i;
1984 liq_remapping_result *result;
1985 float remapping_error;
1986
1987 if (!CHECK_STRUCT_TYPE (quant, liq_result))
1988 return LIQ_INVALID_POINTER;
1989 if (!CHECK_STRUCT_TYPE (input_image, liq_image))
1990 return LIQ_INVALID_POINTER;
1991 for (i = 0; i < input_image->height; i++) {
1992 if (!CHECK_USER_POINTER (row_pointers + i)
1993 || !CHECK_USER_POINTER (row_pointers[i]))
1994 return LIQ_INVALID_POINTER;
1995 }
1996
1997 if (quant->remapping) {
1998 liq_remapping_result_destroy (quant->remapping);
1999 }
2000
2001 result = quant->remapping = liq_remapping_result_create (quant);
2002 if (!result)
2003 return LIQ_OUT_OF_MEMORY;
2004
2005 if (!input_image->edges && !input_image->dither_map && quant->use_dither_map) {
2006 contrast_maps (input_image);
2007 }
2008
2009 /*
2010 ** Step 4: map the colors in the image to their closest match in the
2011 ** new colormap, and write 'em out.
2012 */
2013
2014 remapping_error = result->palette_error;
2015 if (result->dither_level == 0) {
2016 set_rounded_palette (&result->int_palette, result->palette, result->gamma,
2017 quant->min_posterization_output);
2018 remapping_error =
2019 remap_to_palette (input_image, row_pointers, result->palette,
2020 quant->fast_palette);
2021 } else {
2022 const bool generate_dither_map = result->use_dither_map
2023 && (input_image->edges && !input_image->dither_map);
2024 if (generate_dither_map) {
2025 // If dithering (with dither map) is required, this image is used to find areas that require dithering
2026 remapping_error =
2027 remap_to_palette (input_image, row_pointers, result->palette,
2028 quant->fast_palette);
2029 update_dither_map (row_pointers, input_image);
2030 }
2031 // remapping above was the last chance to do voronoi iteration, hence the final palette is set after remapping
2032 set_rounded_palette (&result->int_palette, result->palette, result->gamma,
2033 quant->min_posterization_output);
2034
2035 remap_to_palette_floyd (input_image, row_pointers, result->palette,
2036 MAX (remapping_error * 2.4, 16.f / 256.f), result->use_dither_map,
2037 generate_dither_map, result->dither_level);
2038 }
2039
2040 // remapping error from dithered image is absurd, so always non-dithered value is used
2041 // palette_error includes some perceptual weighting from histogram which is closer correlated with dssim
2042 // so that should be used when possible.
2043 if (result->palette_error < 0) {
2044 result->palette_error = remapping_error;
2045 }
2046
2047 return LIQ_OK;
2048 }
2049
2050 LIQ_EXPORT int
liq_version(void)2051 liq_version (void)
2052 {
2053 return LIQ_VERSION;
2054 }
2055