libimagequant.c 78 KB

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