Line | Count | Source |
1 | | #include <stdbool.h> |
2 | | #include <stdlib.h> |
3 | | #include <string.h> |
4 | | #include <math.h> |
5 | | |
6 | | #include "cgif.h" |
7 | | |
8 | 22.7k | #define MULU16(a, b) (((uint32_t)a) * ((uint32_t)b)) // helper macro to correctly multiply two U16's without default signed int promotion |
9 | 10.3M | #define MAX(a,b) (a >= b ? a : b) |
10 | | #define MIN(a,b) (a <= b ? a : b) |
11 | 870 | #define MAX_TABLE_SIZE 16777216 // 256*256*256 |
12 | 1.72M | #define MAX_COLLISIONS 30 // maximum number of collisions before hash-table resize |
13 | | |
14 | | struct st_cgif_rgb { |
15 | | CGIF* pGIF; |
16 | | CGIFrgb_Config config; |
17 | | uint8_t* pBefImageData; |
18 | | cgif_chan_fmt befFmtChan; |
19 | | cgif_result curResult; |
20 | | }; |
21 | | |
22 | | typedef struct { |
23 | | uint8_t r,g,b,a; |
24 | | } Pixel; |
25 | | |
26 | | typedef struct treeNode { |
27 | | struct treeNode* child0; // pointer to child-node (elements smaller or equal than mean) |
28 | | struct treeNode* child1; // pointer to child-node (elements larger than mean) |
29 | | double mean[3]; // average of the colors |
30 | | uint32_t idxMin, idxMax; // minimum and maximum index referring to global palette |
31 | | uint8_t cutDim; // dimension along which the cut (node split) is done |
32 | | uint8_t colIdx; // color index (only meaningful for leave node) |
33 | | bool isLeave; // is leave node or not |
34 | | } treeNode; |
35 | | |
36 | | typedef struct colHashTable { |
37 | | uint32_t* frequ; // frequency of colors (histogram) |
38 | | uint8_t* hashTable; // stores RGB vales at position determined by hash |
39 | | uint8_t* indexUsed; // which part of the hash table was already used |
40 | | uint8_t* pPalette; // color palette with all the colors (all in one block) |
41 | | uint32_t* colIdx; // index of the color (mapping from hash to index in pPalette) |
42 | | uint32_t cnt; // count the number of colors |
43 | | uint32_t tableSize; // initial size of the hash table |
44 | | } colHashTable; |
45 | | |
46 | 355k | static uint64_t argmax64(double* arry, uint64_t n){ |
47 | 355k | uint64_t imax = 0; |
48 | 355k | double vmax = 0; |
49 | | |
50 | 1.42M | for(uint64_t i = 0; i < n; ++i) { |
51 | 1.06M | if(arry[i] > vmax){ |
52 | 435k | imax = i; |
53 | 435k | vmax = arry[i]; |
54 | 435k | } |
55 | 1.06M | } |
56 | 355k | return imax; |
57 | 355k | } |
58 | | |
59 | | /* get the next prime number above the next power of two */ |
60 | 3.37k | static int getNextPrimePower2(int N){ |
61 | 3.37k | if(N <= 512) {return 521;} |
62 | 3.37k | else if(N <= 1024) {return 1031;} |
63 | 3.37k | else if (N <= 2048) {return 2053;} |
64 | 3.37k | else if (N <= 4096) {return 4099;} |
65 | 3.37k | else if (N <= 8192) {return 8209;} |
66 | 3.37k | else if (N <= 16384) {return 16411;} |
67 | 3.37k | else if (N <= 32768) {return 32771;} |
68 | 3.37k | else if (N <= 65536) {return 65537;} |
69 | 3.37k | else if (N <= 131072) {return 131101;} |
70 | 3.37k | else if (N <= 262144) {return 262147;} |
71 | 3.37k | else if (N <= 524288) {return 524309;} |
72 | 827 | else if (N <= 1048576) {return 1048583;} |
73 | 522 | else if (N <= 2097152) {return 2097169;} |
74 | 301 | else if (N <= 4194304) {return 4194319;} |
75 | 126 | else if (N <= 8388608) {return 8388617;} |
76 | 43 | else {return MAX_TABLE_SIZE;} // largest table size that is meaningful (no prime number) |
77 | 3.37k | } |
78 | | |
79 | 4.60M | static Pixel getPixelVal(const uint8_t* pData, cgif_chan_fmt fmtChan) { |
80 | 4.60M | Pixel result; |
81 | | |
82 | 4.60M | result.r = *(pData++); |
83 | 4.60M | result.g = *(pData++); |
84 | 4.60M | result.b = *(pData++); |
85 | | // check whether there is a alpha channel, if so convert it to a 1 bit alpha channel. |
86 | 4.60M | switch(fmtChan) { |
87 | 3.06M | case CGIF_CHAN_FMT_RGB: |
88 | 3.06M | result.a = 0xFF; |
89 | 3.06M | break; |
90 | 1.54M | case CGIF_CHAN_FMT_RGBA: |
91 | 1.54M | result.a = (*(pData) <= 127) ? 0 : 0xFF; |
92 | 1.54M | break; |
93 | 4.60M | } |
94 | 4.60M | return result; |
95 | 4.60M | } |
96 | | |
97 | | /* get a hash from rgb color values (use open addressing, if entry does not exist, next free spot is returned) */ |
98 | 1.75M | static int32_t col_hash(const uint8_t* rgb, const uint8_t* hashTable, const uint8_t* indexUsed, const uint32_t tableSize, cgif_chan_fmt fmtChan) { |
99 | 1.75M | uint32_t h; |
100 | 1.75M | const Pixel pix = getPixelVal(rgb, fmtChan); |
101 | 1.75M | if(pix.a == 0) { // has alpha channel? |
102 | 302k | return -1; |
103 | 302k | } |
104 | 1.45M | h = (pix.r * 256 * 256 + pix.g * 256 + pix.b) % tableSize; |
105 | 1.89M | while(indexUsed[h] != 0 && memcmp(rgb, &hashTable[3 * h], 3) != 0) { // until free spot is found |
106 | 444k | ++h; |
107 | 444k | h = h % tableSize; // start from beginning if there is no free spot at the end |
108 | 444k | } |
109 | 1.45M | return h; |
110 | 1.75M | } |
111 | | |
112 | | /* same as col_hash but also count the number of collisions */ |
113 | 2.85M | static int32_t col_hash_collision_count(const uint8_t* rgb, const uint8_t* hashTable, const uint8_t* indexUsed, const uint32_t tableSize, cgif_chan_fmt fmtChan, uint32_t* cntCollision) { |
114 | 2.85M | uint32_t h; |
115 | 2.85M | const Pixel pix = getPixelVal(rgb, fmtChan); |
116 | 2.85M | *cntCollision = 0; // count the number of collisions |
117 | 2.85M | if(pix.a == 0) { // has alpha channel? |
118 | 1.12M | return -1; |
119 | 1.12M | } |
120 | 1.72M | h = (pix.r * 256 * 256 + pix.g * 256 + pix.b) % tableSize; |
121 | 1.89M | while(indexUsed[h] != 0 && memcmp(rgb, &hashTable[3 * h], 3) != 0) { // until free spot is found |
122 | 163k | ++(*cntCollision); |
123 | 163k | ++h; |
124 | 163k | h = h % tableSize; // start from beginning if there is no free spot at the end |
125 | 163k | } |
126 | 1.72M | return h; |
127 | 2.85M | } |
128 | | |
129 | | /* free the color hash table*/ |
130 | 2.54k | static void free_col_hash_table(colHashTable* colhash){ |
131 | 2.54k | free(colhash->frequ); |
132 | 2.54k | free(colhash->hashTable); |
133 | 2.54k | free(colhash->indexUsed); |
134 | 2.54k | free(colhash->pPalette); |
135 | 2.54k | free(colhash->colIdx); |
136 | 2.54k | free(colhash); |
137 | 2.54k | } |
138 | | |
139 | | /* initialize hash table storing colors and their frequency */ |
140 | 2.54k | static colHashTable* init_col_hash_table(uint32_t tableSize){ |
141 | 2.54k | colHashTable* colhash = malloc(sizeof(colHashTable)); |
142 | 2.54k | if(colhash == NULL) { |
143 | 0 | return NULL; |
144 | 0 | } |
145 | 2.54k | memset(colhash, 0, sizeof(colHashTable)); |
146 | 2.54k | colhash->tableSize = getNextPrimePower2(tableSize); // increase table size to next prime number |
147 | 2.54k | colhash->frequ = malloc(sizeof(uint32_t) * colhash->tableSize); |
148 | 2.54k | colhash->hashTable = malloc(3 * colhash->tableSize); |
149 | 2.54k | colhash->indexUsed = malloc(colhash->tableSize); |
150 | 2.54k | colhash->pPalette = malloc(3 * colhash->tableSize); |
151 | 2.54k | colhash->colIdx = malloc(sizeof(uint32_t)*colhash->tableSize); |
152 | 2.54k | if(!colhash->frequ || !colhash->hashTable || !colhash->indexUsed || !colhash->pPalette || !colhash->colIdx) { |
153 | 0 | free_col_hash_table(colhash); |
154 | 0 | return NULL; |
155 | 0 | } |
156 | 2.54k | colhash->cnt = 0; // no colors initially |
157 | 2.54k | memset(colhash->pPalette, 0, 3 * colhash->tableSize); // unused part of color table is uninitialized otheriwse |
158 | 2.54k | memset(colhash->indexUsed, 0, colhash->tableSize); // initially no entry in hash-table is used |
159 | 2.54k | return colhash; |
160 | 2.54k | } |
161 | | |
162 | | /* increase the size of the color hash table */ |
163 | 827 | static int resize_col_hash_table(colHashTable* colhash){ |
164 | 827 | uint32_t tableSizeNew; |
165 | 827 | tableSizeNew = getNextPrimePower2(colhash->tableSize); // increase table size to the next prime number above the next power of two |
166 | 827 | uint8_t* pPaletteNew = realloc(colhash->pPalette, 3 * tableSizeNew); |
167 | 827 | uint32_t* colIdxNew = realloc(colhash->colIdx, sizeof(uint32_t) * tableSizeNew); |
168 | 827 | uint8_t* hashTable_new = malloc(3 * tableSizeNew); |
169 | 827 | uint8_t* indexUsed_new = malloc(tableSizeNew); |
170 | 827 | uint32_t* frequ_new = malloc(sizeof(uint32_t) * tableSizeNew); |
171 | 827 | if(!pPaletteNew || !colIdxNew || !hashTable_new || !indexUsed_new || !frequ_new) { |
172 | | // On allocation failure, apply any successful reallocs to colhash and free |
173 | | // any newly allocated auxiliary buffers before returning an error. |
174 | 0 | if(pPaletteNew) colhash->pPalette = pPaletteNew; |
175 | 0 | if(colIdxNew) colhash->colIdx = colIdxNew; |
176 | 0 | free(hashTable_new); |
177 | 0 | free(indexUsed_new); |
178 | 0 | free(frequ_new); |
179 | 0 | return -1; |
180 | 0 | } |
181 | 827 | colhash->pPalette = pPaletteNew; |
182 | 827 | colhash->colIdx = colIdxNew; |
183 | 827 | memset(indexUsed_new, 0, tableSizeNew); |
184 | 827 | colhash->cnt = 0; |
185 | 1.46G | for(uint32_t j = 0; j < colhash->tableSize; ++j) { // TBD (no improvement when tested): easier to loop over pPalette and also leave pPalette in place?, if indexUsed is also unnecessary then |
186 | 1.46G | if(colhash->indexUsed[j] == 1){ |
187 | 467k | uint32_t h = col_hash(colhash->hashTable + 3 * j, hashTable_new, indexUsed_new, tableSizeNew, 3); // recompute hash with new table size |
188 | 467k | memcpy(&hashTable_new[3 * h], colhash->hashTable + 3 * j, 3); // put value from old hash table to right position of the new one |
189 | 467k | memcpy(colhash->pPalette + 3 * colhash->cnt, colhash->hashTable + 3 * j, 3); |
190 | 467k | indexUsed_new[h] = 1; |
191 | 467k | frequ_new[h] = colhash->frequ[j]; |
192 | 467k | colhash->colIdx[h] = colhash->cnt; |
193 | 467k | ++(colhash->cnt); |
194 | 467k | } |
195 | 1.46G | } |
196 | 827 | colhash->tableSize = tableSizeNew; |
197 | 827 | free(colhash->hashTable); // free part of old hash table that is not used anymore |
198 | 827 | free(colhash->indexUsed); // free part of old hash table that is not used anymore |
199 | 827 | free(colhash->frequ); // free part of old hash table that is not used anymore |
200 | 827 | colhash->hashTable = hashTable_new; // pass pointer to new hash table |
201 | 827 | colhash->indexUsed = indexUsed_new; // pass pointer to new hash table |
202 | 827 | colhash->frequ = frequ_new; // pass pointer to new hash table |
203 | 827 | return 0; |
204 | 827 | } |
205 | | |
206 | | /* take frequ indexed by hash(rgb) and return corresponding dense array */ |
207 | 699 | static uint32_t* hash_to_dense(colHashTable* colhash, cgif_chan_fmt fmtChan) { |
208 | 699 | uint32_t* frequDense = malloc(sizeof(uint32_t) * colhash->cnt); |
209 | 699 | uint32_t h; |
210 | 699 | (void)fmtChan; |
211 | 699 | if(frequDense == NULL) { |
212 | 0 | return NULL; |
213 | 0 | } |
214 | 910k | for(uint32_t i = 0; i < colhash->cnt; ++i) { |
215 | 909k | h = col_hash(colhash->pPalette + 3 * i, colhash->hashTable, colhash->indexUsed, colhash->tableSize, 3); |
216 | 909k | frequDense[i] = colhash->frequ[h]; |
217 | 909k | } |
218 | 699 | return frequDense; |
219 | 699 | } |
220 | | |
221 | | /* get mean of color-cloud along all 3 dimensions (at least one color must be present, otherwise div 0 issue)*/ |
222 | 355k | static void get_mean(const uint8_t* pPalette, const uint32_t* frequ, uint32_t idxMin, uint32_t idxMax, double* mean){ |
223 | | // pPalette: RGB color palette |
224 | | // frequ: frequency of the colors (indexing as pPalette, no hashing) |
225 | | // idxMin, idxMax: palette range for which the mean is computed |
226 | | // mean: mean value along all three dimensions |
227 | 355k | double m[3] = {0,0,0}; |
228 | 355k | double sum[3] = {0,0,0}; |
229 | 355k | uint32_t i; |
230 | 355k | uint8_t dim; |
231 | | |
232 | 8.59M | for(i = idxMin; i <= idxMax; ++i) { |
233 | 32.9M | for(dim = 0; dim < 3; ++dim) { |
234 | 24.7M | sum[dim] += frequ[i]; |
235 | 24.7M | m[dim] += (double)frequ[i] * pPalette[3 * i + dim]; |
236 | 24.7M | } |
237 | 8.23M | } |
238 | 1.42M | for(dim = 0; dim < 3; ++dim) { |
239 | 1.06M | mean[dim] = m[dim] / sum[dim]; |
240 | 1.06M | } |
241 | 355k | } |
242 | | |
243 | | /* get variance of color-cloud along all 3 dimensions*/ |
244 | 355k | static void get_variance(const uint8_t* pPalette, const uint32_t* frequ, uint32_t idxMin, uint32_t idxMax, double* var, double* mean){ |
245 | | // pPalette: RGB color palette |
246 | | // frequ: frequency of the colors (indexing as pPalette, no hashing) |
247 | | // idxMin, idxMax: palette range for which the variance is computed |
248 | | // var/mean: variance/mean value along all three dimensions (array with 3 entries) |
249 | 355k | uint32_t i; |
250 | 355k | uint8_t dim; |
251 | 355k | double v[3] = {0,0,0}; |
252 | 355k | double sum[3] = {0,0,0}; |
253 | | |
254 | 355k | get_mean(pPalette, frequ, idxMin, idxMax, mean); |
255 | 8.59M | for(i = idxMin; i <= idxMax; ++i) { |
256 | 32.9M | for(dim = 0; dim < 3; ++dim) { |
257 | 24.7M | sum[dim] += frequ[i]; |
258 | 24.7M | v[dim] += frequ[i] * (pPalette[3 * i + dim] - mean[dim]) * (pPalette[3 * i + dim] - mean[dim]); |
259 | 24.7M | } |
260 | 8.23M | } |
261 | 1.42M | for(dim = 0; dim < 3; ++dim) { |
262 | 1.06M | var[dim] = v[dim] / sum[dim]; |
263 | 1.06M | } |
264 | 355k | } |
265 | | |
266 | 355k | static treeNode* new_tree_node(uint8_t* pPalette, uint32_t* frequ, uint16_t* numLeaveNodes, uint32_t idxMin, uint32_t idxMax, uint8_t colIdx) { |
267 | 355k | double var[3]; |
268 | | |
269 | 355k | treeNode* node = malloc(sizeof(treeNode)); |
270 | 355k | if(node == NULL) { |
271 | 0 | return NULL; |
272 | 0 | } |
273 | 355k | node->idxMin = idxMin; // minimum color in pPalette belonging to the node |
274 | 355k | node->idxMax = idxMax; // maximum color in pPalette belonging to the node |
275 | 355k | get_variance(pPalette, frequ, idxMin, idxMax, var, node->mean); |
276 | 355k | node->cutDim = argmax64(var, 3); // dimension along which the cut (node split) is done |
277 | 355k | node->colIdx = colIdx; // index referring to (averaged) color in new color table |
278 | 355k | node->isLeave = 1; // every new node starts as a leave node |
279 | 355k | (*numLeaveNodes)++; // increase counter when leave node is added |
280 | 355k | return node; |
281 | 355k | } |
282 | | |
283 | | /* create the decision tree. (Similar to qsort with limited depth: pPalette, frequ get sorted) */ |
284 | 699 | static int crawl_decision_tree(treeNode* root, uint16_t* numLeaveNodes, uint8_t* pPalette, uint32_t* frequ, uint16_t colMax) { |
285 | 699 | uint32_t i, k, saveNum; |
286 | 699 | uint16_t nodeIdx = 0; |
287 | 699 | uint8_t saveBlk[3]; |
288 | 699 | treeNode* parent; |
289 | 699 | treeNode* nodeList[512]; // array of pointers to nodes for breadth-first tree traversal |
290 | 699 | nodeList[0] = root; |
291 | | |
292 | 247k | while(*numLeaveNodes <= (colMax - 1)){ |
293 | 246k | parent = nodeList[nodeIdx++]; // go to next node in the list |
294 | 246k | if (parent->idxMax - parent->idxMin >= 1) { // condition for node split |
295 | 177k | i = parent->idxMin; // start of block minimum |
296 | 177k | k = parent->idxMax; // start at block maximum |
297 | 2.10M | while(i < k) { // split parent node in two blocks (like one step in qsort) |
298 | 5.73M | for(; pPalette[3 * i + parent->cutDim] <= parent->mean[parent->cutDim]; ++i); // && i<parent->idxMax not needed (other condition is false when i==parent>idxMax since there must be at most 1 element above mean) |
299 | 5.43M | for(; pPalette[3 * k + parent->cutDim] > parent->mean[parent->cutDim]; --k); // && k>parent->idxMin not needed (other condition is false when k==parent>idxMin since there must be at most 1 element below mean) |
300 | 1.92M | if(k > i) { |
301 | 1.74M | memcpy(saveBlk, &(pPalette[3 * i]), 3); |
302 | 1.74M | memcpy(&(pPalette[3 * i]), &(pPalette[3 * k]), 3); // swap RGB-blocks in pPalette |
303 | 1.74M | memcpy(&(pPalette[3 * k]), saveBlk, 3); // swap RGB-blocks in pPalette |
304 | 1.74M | saveNum = frequ[k]; |
305 | 1.74M | frequ[k] = frequ[i]; // swap also the frequency |
306 | 1.74M | frequ[i] = saveNum; // sawp also the frequency |
307 | 1.74M | } |
308 | 1.92M | } |
309 | 177k | parent->isLeave = 0; // parent is no leave node anymore when children added |
310 | 177k | (*numLeaveNodes)--; // decrease counter since parent is removed as a leave node |
311 | 177k | parent->child0 = new_tree_node(pPalette, frequ, numLeaveNodes, parent->idxMin, i - 1, parent->colIdx); // i-1 is last index of 1st block, one child takes color index from parent |
312 | 177k | parent->child1 = new_tree_node(pPalette, frequ, numLeaveNodes, i, parent->idxMax, *numLeaveNodes); |
313 | 177k | if(parent->child0 == NULL || parent->child1 == NULL) { |
314 | 0 | return -1; |
315 | 0 | } |
316 | 177k | nodeList[2*(*numLeaveNodes) - 3] = parent->child0; // add new child nodes to the list (total number of nodes is always 2*(*numLeaveNodes)-1) |
317 | 177k | nodeList[2*(*numLeaveNodes) - 2] = parent->child1; // add new child nodes to the list (total number of nodes is always 2*(*numLeaveNodes)-1) |
318 | 177k | } |
319 | 246k | } |
320 | 699 | return 0; |
321 | 699 | } |
322 | | |
323 | | /* fill 256 color table using the decision tree */ |
324 | 355k | static void get_palette_from_decision_tree(const treeNode* root, uint8_t* pPalette256){ |
325 | 355k | if(root->isLeave == 0) { |
326 | 177k | get_palette_from_decision_tree(root->child0, pPalette256); |
327 | 177k | get_palette_from_decision_tree(root->child1, pPalette256); |
328 | 178k | } else { |
329 | 178k | pPalette256[3 * root->colIdx] = (uint8_t)round(root->mean[0]); |
330 | 178k | pPalette256[3 * root->colIdx + 1] = (uint8_t)round(root->mean[1]); |
331 | 178k | pPalette256[3 * root->colIdx + 2] = (uint8_t)round(root->mean[2]); |
332 | 178k | } |
333 | 355k | } |
334 | | |
335 | | /* get color index by using the decision tree */ |
336 | 20.7M | static uint8_t get_leave_node_index(const treeNode* root, const float* rgb) { |
337 | 20.7M | if(root->isLeave == 0) { // if there is a split |
338 | 18.4M | if(rgb[root->cutDim] <= root->mean[root->cutDim]) { |
339 | 12.3M | return get_leave_node_index(root->child0, rgb); |
340 | 12.3M | } else { |
341 | 6.12M | return get_leave_node_index(root->child1, rgb); |
342 | 6.12M | } |
343 | 18.4M | } else { |
344 | 2.27M | return root->colIdx; // return color index of leave node |
345 | 2.27M | } |
346 | 20.7M | } |
347 | | |
348 | | /* free memory allocated for the tree */ |
349 | 355k | static void free_decision_tree(treeNode* root){ |
350 | 355k | if(root == NULL) { |
351 | 0 | return; |
352 | 0 | } |
353 | 355k | if(root->isLeave == 0) { // if the node has children |
354 | 177k | free_decision_tree(root->child0); |
355 | 177k | free_decision_tree(root->child1); |
356 | 177k | } |
357 | 355k | free(root); // free root once free is called for children |
358 | 355k | } |
359 | | |
360 | | /* color quantization with mean cut method (TBD? switch to median cut) |
361 | | (works with dense palette, no hash table) */ |
362 | 699 | static treeNode* create_decision_tree(uint8_t* pPalette, uint32_t* pFrequDense, uint8_t* pPalette256, uint32_t cnt, uint16_t colMax, uint8_t depthMax){ |
363 | 699 | uint16_t numLeaveNodes = 0; |
364 | 699 | treeNode* root = new_tree_node(pPalette, pFrequDense, &numLeaveNodes, 0, cnt - 1, 0); |
365 | 699 | if(root == NULL) { |
366 | 0 | return NULL; |
367 | 0 | } |
368 | 699 | if(crawl_decision_tree(root, &numLeaveNodes, pPalette, pFrequDense, colMax) != 0) { |
369 | 0 | free_decision_tree(root); |
370 | 0 | return NULL; |
371 | 0 | } |
372 | 699 | get_palette_from_decision_tree(root, pPalette256); // fill the reduced color table |
373 | 699 | return root; |
374 | 699 | } |
375 | | |
376 | | /* get image with max 256 color indices using Floyd-Steinberg dithering */ |
377 | 699 | static void get_quantized_dithered_image(uint8_t* pImageData, float* pImageDataRGBfloat, uint8_t* pPalette256, treeNode* root, uint32_t numPixel, uint32_t width, uint8_t dithering, uint8_t transIndex, cgif_chan_fmt fmtChan, uint8_t* pBef, cgif_chan_fmt befFmtChan, int hasAlpha) { |
378 | | // pImageData: image with (max 256) color indices (length: numPixel) |
379 | | // pImageDataRGBfloat: image with RGB colors (length: 3*numPixel) must be signed to avoid overflow due to error passing, float only needed because of 0.9 factor |
380 | | // pPalette256: quantized color palette (indexed by node->colIdx), only used if dithering is on |
381 | | // root: root node of the decision tree for color quantization |
382 | | // numPixel, width: size of the image |
383 | | // dithering: 0 (no dithering), 1: Floyd-Steinberg dithering, else: Sierra dithering |
384 | 699 | uint32_t i; |
385 | 699 | uint8_t k; |
386 | 699 | int err; // color errors |
387 | | /* |
388 | | we noticed certain artifacts with Floyd-Steinberg dithering if the error is passed too far. |
389 | | use a damping factor to reduce these effects. |
390 | | */ |
391 | 699 | const double factor = 0.90; // Has to be a double to force double-precision arithmetic - otherwise we might get rounding specific differences between platforms (eg. macOS Clang) |
392 | 699 | if(!dithering) { |
393 | 1.04M | for(i = 0; i < numPixel; ++i) { |
394 | 1.04M | if(hasAlpha) { |
395 | 15.5k | if(pImageDataRGBfloat[fmtChan * i + 3] == 0) { |
396 | 1.50k | pImageData[i] = transIndex; |
397 | 1.50k | continue; |
398 | 1.50k | } |
399 | 1.03M | } else { |
400 | | // do the transparency trick |
401 | 1.03M | float* p = pImageDataRGBfloat; |
402 | 1.03M | if(pBef && p[i * fmtChan] == pBef[i * befFmtChan] && p[i * fmtChan + 1] == pBef[i * befFmtChan + 1] && p[i * fmtChan + 2] == pBef[i * befFmtChan + 2]) { |
403 | 133k | pImageData[i] = transIndex; |
404 | 133k | continue; |
405 | 133k | } |
406 | 1.03M | } |
407 | 912k | pImageData[i] = get_leave_node_index(root, &pImageDataRGBfloat[fmtChan * i]); // use decision tree to get indices for new colors |
408 | 912k | } |
409 | 408 | } else { |
410 | 1.39M | for(i = 0; i < numPixel; ++i) { |
411 | 1.39M | if(fmtChan == CGIF_CHAN_FMT_RGBA) { |
412 | 905k | if(pImageDataRGBfloat[fmtChan * i + 3] == 0) { |
413 | 37.0k | pImageData[i] = transIndex; |
414 | 37.0k | continue; |
415 | 37.0k | } |
416 | 905k | } |
417 | | // TBD add the transparency trick |
418 | | |
419 | | // restrict color + error to 0-255 interval |
420 | 5.44M | for(k = 0; k<3; ++k) { |
421 | 4.08M | pImageDataRGBfloat[fmtChan * i + k] = MAX(0,MIN(pImageDataRGBfloat[fmtChan * i + k], 255)); // cut to 0-255 before |
422 | 4.08M | } |
423 | | |
424 | 1.36M | pImageData[i] = get_leave_node_index(root, &pImageDataRGBfloat[fmtChan * i]); // use decision tree to get indices for new colors |
425 | 5.44M | for(k = 0; k<3; ++k) { |
426 | 4.08M | err = pImageDataRGBfloat[fmtChan * i + k] - pPalette256[3 * pImageData[i] + k]; // compute color error |
427 | | |
428 | | //diffuse error with Floyd-Steinberg dithering. |
429 | 4.08M | if(dithering == 1) { |
430 | 4.08M | if(i % width < width-1){ |
431 | 3.14M | pImageDataRGBfloat[fmtChan * (i+1) + k] += factor * (7*err >> 4); |
432 | 3.14M | } |
433 | 4.08M | if(i < numPixel - width){ |
434 | 3.60M | pImageDataRGBfloat[fmtChan * (i+width) + k] += factor * (5*err >> 4); |
435 | 3.60M | if(i % width > 0){ |
436 | 2.66M | pImageDataRGBfloat[fmtChan * (i+width-1) + k] += factor * (3*err >> 4); |
437 | 2.66M | } |
438 | 3.60M | if(i % width < width-1){ |
439 | 2.66M | pImageDataRGBfloat[fmtChan * (i+width+1) + k] += factor * (1*err >> 4); |
440 | 2.66M | } |
441 | 3.60M | } |
442 | 4.08M | } else { |
443 | | // Sierra dithering |
444 | 0 | if(i % width < width-1){ |
445 | 0 | pImageDataRGBfloat[fmtChan * (i+1) + k] += factor * (5*err >> 5); |
446 | 0 | if(i % width < width-2){ |
447 | 0 | pImageDataRGBfloat[fmtChan * (i+2) + k] += factor * (3*err >> 5); |
448 | 0 | } |
449 | 0 | } |
450 | 0 | if(i < numPixel - width){ |
451 | 0 | pImageDataRGBfloat[fmtChan * (i+width) + k] += factor * (5*err >> 5); |
452 | 0 | if(i % width > 0){ |
453 | 0 | pImageDataRGBfloat[fmtChan * (i+width-1) + k] += factor * (4*err >> 5); |
454 | 0 | if(i % width > 1){ |
455 | 0 | pImageDataRGBfloat[fmtChan * (i+width-2) + k] += factor * (2*err >> 5); |
456 | 0 | } |
457 | 0 | } |
458 | 0 | if(i % width < width-1){ |
459 | 0 | pImageDataRGBfloat[fmtChan * (i+width+1) + k] += factor * (4*err >> 5); |
460 | 0 | if(i % width < width-2){ |
461 | 0 | pImageDataRGBfloat[fmtChan * (i+width+2) + k] += factor * (2*err >> 5); |
462 | 0 | } |
463 | 0 | } |
464 | 0 | if(i < numPixel - 2*width){ |
465 | 0 | pImageDataRGBfloat[fmtChan * (i+2*width) + k] += factor * (3*err >> 5); |
466 | 0 | if(i % width > 0){ |
467 | 0 | pImageDataRGBfloat[fmtChan * (i+2*width-1) + k] += factor * (2*err >> 5); |
468 | 0 | } |
469 | 0 | if(i % width < width-1){ |
470 | 0 | pImageDataRGBfloat[fmtChan * (i+2*width+1) + k] += factor * (2*err >> 5); |
471 | 0 | } |
472 | 0 | } |
473 | 0 | } |
474 | 0 | } |
475 | 4.08M | } |
476 | 1.36M | } |
477 | 408 | } |
478 | 699 | } |
479 | | |
480 | | /* get color histogram of and rgb image with up to 256*256*256 colors */ |
481 | | // pImageDataRGB: image in RGB format |
482 | | // numPixel: number of pixels of input image |
483 | | // fmtChan: select if image data are RGB or RGBa |
484 | | // pHasAlpha: is alpha channel present |
485 | 2.54k | static colHashTable* get_color_histogram(const uint8_t* pImageDataRGB, uint32_t numPixel, cgif_chan_fmt fmtChan, int* pHasAlpha) { |
486 | 2.54k | uint32_t cntCollision; // count the number of collision |
487 | 2.54k | uint32_t tableSize = 262147; // initial size of the hash table |
488 | 2.54k | colHashTable* colhash = init_col_hash_table(tableSize); // initialize the hash table storing all the colors |
489 | 2.54k | if(colhash == NULL) { |
490 | 0 | return NULL; |
491 | 0 | } |
492 | 2.54k | *pHasAlpha = 0; // assume no alpha channel until it is found |
493 | 2.54k | const uint8_t sizePixel = fmtChan; // number of bytes for one pixel (e.g. 3 for RGB, 4 for RGBa) |
494 | 2.85M | for(uint32_t i = 0; i < numPixel; ++i) { |
495 | 2.85M | uint32_t h = col_hash_collision_count(&pImageDataRGB[sizePixel * i], colhash->hashTable, colhash->indexUsed, colhash->tableSize, fmtChan, &cntCollision); |
496 | 2.85M | if(h == -1) { // -1 means that the user has set a user-defined transparency (alpha channel) |
497 | 1.12M | *pHasAlpha = 1; |
498 | 1.12M | continue; // do not take this pixel into account (e.g. alpha channel present) |
499 | 1.12M | } |
500 | 1.72M | if(colhash->indexUsed[h] == 0) { |
501 | 964k | memcpy(colhash->hashTable + 3 * h, &pImageDataRGB[sizePixel * i], 3); // add new color to hash table |
502 | 964k | memcpy(colhash->pPalette + 3 * colhash->cnt, &pImageDataRGB[sizePixel * i], 3); // add new color to palette |
503 | 964k | colhash->indexUsed[h] = 1; // mark hash table entry as used |
504 | 964k | colhash->colIdx[h] = colhash->cnt; // assign index to color |
505 | 964k | colhash->frequ[h] = 1; // the new color occured 1x (1st time) |
506 | 964k | ++(colhash->cnt); // one new color added |
507 | 964k | } else { // if color exists already |
508 | 763k | colhash->frequ[h] += 1; // increment color histrogram |
509 | 763k | } |
510 | | // resize the hash table (if more than half-full) |
511 | 1.72M | if((colhash->cnt > (colhash->tableSize >> 1) || cntCollision > MAX_COLLISIONS) && colhash->tableSize < MAX_TABLE_SIZE) { |
512 | 827 | if(resize_col_hash_table(colhash) != 0) { |
513 | 0 | free_col_hash_table(colhash); |
514 | 0 | return NULL; |
515 | 0 | } |
516 | 827 | } |
517 | 1.72M | } |
518 | 2.54k | return colhash; |
519 | 2.54k | } |
520 | | |
521 | | /* quantize the image using the color histogram */ |
522 | 2.54k | static int quantize_and_dither(colHashTable* colhash, const uint8_t* pImageDataRGB, uint32_t numPixel, uint32_t width, cgif_chan_fmt fmtChan, uint8_t* pImageData, uint8_t* pPalette256, uint8_t depthMax, uint8_t dithering, int hasAlpha, uint8_t* pBef, cgif_chan_fmt befFmtChan) { |
523 | | // pImageDataRGB: image in RGB format |
524 | | // numPixel: number of pixels of input image |
525 | | // width: width of the image (needed for dithering) |
526 | | // fmtChan: select if image data are RGB or RGBa |
527 | | // pImageData: pointer to image as indices (output) |
528 | | // pPalette256: new color palette with 256 colors max. |
529 | | // depthMax: maximum depth of decision tree for colors quantization (sets number of colors) |
530 | | // dithering: 0 (no dithering), 1: Floyd-Steinberg dithering, else: Sierra dithering |
531 | | // hasAlpha: alpha channel present 1, 0 otheriwse |
532 | | // pBef, befFmtChan |
533 | 2.54k | const uint8_t sizePixel = fmtChan; // number of bytes for one pixel (e.g. 3 for RGB, 4 for RGBa) |
534 | 2.54k | const uint16_t colMax = (1uL << depthMax) - 1; // maximum number of colors (-1 to leave space for transparency), disadvantage (TBD): quantization for static image with 256 colors and no alpha channel unnecessary |
535 | 2.54k | if(colhash->cnt > colMax) { // color-quantization is needed |
536 | 699 | uint32_t* pFrequDense = hash_to_dense(colhash, fmtChan); |
537 | 699 | if(pFrequDense == NULL) { |
538 | 0 | return -1; |
539 | 0 | } |
540 | 699 | treeNode* root = create_decision_tree(colhash->pPalette, pFrequDense, pPalette256, colhash->cnt, colMax, depthMax); // create decision tree (dynamic, splits along rgb-dimension with highest variance) |
541 | 699 | free(pFrequDense); |
542 | 699 | if(root == NULL) { |
543 | 0 | return -1; |
544 | 0 | } |
545 | 699 | float* pImageDataRGBfloat = malloc(fmtChan * numPixel * sizeof(float)); // TBD fmtChan + only when hasAlpha |
546 | 699 | if(pImageDataRGBfloat == NULL) { |
547 | 0 | free_decision_tree(root); |
548 | 0 | return -1; |
549 | 0 | } |
550 | 8.26M | for(uint32_t i = 0; i < fmtChan * numPixel; ++i){ |
551 | 8.26M | pImageDataRGBfloat[i] = pImageDataRGB[i]; |
552 | 8.26M | } |
553 | 699 | uint8_t transIndex = colMax; |
554 | 699 | get_quantized_dithered_image(pImageData, pImageDataRGBfloat, pPalette256, root, numPixel, width, dithering, transIndex, fmtChan, pBef, befFmtChan, hasAlpha); // do color quantization and dithering |
555 | 699 | free(pImageDataRGBfloat); // RGB image is not needed anymore |
556 | 699 | free_decision_tree(root); // tree for color quantization is not needed anymore |
557 | 699 | colhash->cnt = colMax; |
558 | 1.84k | } else { // no color-quantization is needed if the number of colors is small enough |
559 | 1.84k | uint8_t transIndex = colhash->cnt; |
560 | 411k | for(uint32_t i = 0; i < numPixel; ++i) { |
561 | 409k | if(!hasAlpha && pBef) { |
562 | 52.4k | if(memcmp(&pImageDataRGB[sizePixel * i], &pBef[befFmtChan * i], 3) == 0) { |
563 | 33.4k | pImageData[i] = transIndex; |
564 | 33.4k | continue; |
565 | 33.4k | } |
566 | 52.4k | } |
567 | 376k | uint32_t h = col_hash(&pImageDataRGB[sizePixel * i], colhash->hashTable, colhash->indexUsed, colhash->tableSize, fmtChan); |
568 | 376k | pImageData[i] = (h == -1) ? transIndex : colhash->colIdx[h]; |
569 | 376k | } |
570 | 1.84k | memcpy(pPalette256, colhash->pPalette, 3 * 256); // keep the color palette (no quantization) |
571 | 1.84k | } |
572 | 2.54k | return colhash->cnt; // return number of colors found |
573 | 2.54k | } |
574 | | |
575 | 1.16k | CGIFrgb* cgif_rgb_newgif(const CGIFrgb_Config* pConfig) { |
576 | 1.16k | CGIF_Config idxConfig = {0}; |
577 | 1.16k | CGIFrgb* pGIFrgb; |
578 | | |
579 | 1.16k | pGIFrgb = malloc(sizeof(CGIFrgb)); |
580 | 1.16k | if(pGIFrgb == NULL) { |
581 | 0 | return NULL; |
582 | 0 | } |
583 | 1.16k | memset(pGIFrgb, 0, sizeof(CGIFrgb)); |
584 | 1.16k | idxConfig.pWriteFn = pConfig->pWriteFn; |
585 | 1.16k | idxConfig.pContext = pConfig->pContext; |
586 | 1.16k | idxConfig.path = pConfig->path; |
587 | 1.16k | idxConfig.numLoops = pConfig->numLoops; |
588 | 1.16k | idxConfig.width = pConfig->width; |
589 | 1.16k | idxConfig.height = pConfig->height; |
590 | 1.16k | idxConfig.attrFlags = CGIF_ATTR_IS_ANIMATED | CGIF_ATTR_NO_GLOBAL_TABLE; |
591 | 1.16k | pGIFrgb->pGIF = cgif_newgif(&idxConfig); |
592 | 1.16k | if(pGIFrgb->pGIF == NULL) { |
593 | 14 | free(pGIFrgb); |
594 | 14 | return NULL; |
595 | 14 | } |
596 | 1.15k | pGIFrgb->config = *pConfig; |
597 | 1.15k | pGIFrgb->curResult = CGIF_PENDING; |
598 | 1.15k | return pGIFrgb; |
599 | 1.16k | } |
600 | | |
601 | 17.6k | cgif_result cgif_rgb_addframe(CGIFrgb* pGIF, const CGIFrgb_FrameConfig* pConfig) { |
602 | 17.6k | uint8_t aPalette[256 * 3]; |
603 | 17.6k | memset(aPalette, 0, 256 * 3); // quantize_and_dither does not necessarily fill/use all palette entries (-> initialize aPalette to avoid underfined behaviour) |
604 | 17.6k | CGIF_FrameConfig fConfig = {0}; |
605 | 17.6k | uint8_t* pNewBef; |
606 | 17.6k | const uint16_t imageWidth = pGIF->config.width; |
607 | 17.6k | const uint16_t imageHeight = pGIF->config.height; |
608 | 17.6k | const uint32_t numPixel = MULU16(imageWidth, imageHeight); |
609 | 17.6k | int hasAlpha; |
610 | | // check for previous errors |
611 | 17.6k | if(pGIF->curResult != CGIF_OK && pGIF->curResult != CGIF_PENDING) { |
612 | 14.0k | return pGIF->curResult; |
613 | 14.0k | } |
614 | | // check if fmtChan param is valid (only RGB, RGBA allowed) |
615 | 3.61k | if(pConfig->fmtChan != CGIF_CHAN_FMT_RGB && pConfig->fmtChan != CGIF_CHAN_FMT_RGBA) { |
616 | 1.07k | pGIF->curResult = CGIF_ERROR; |
617 | 1.07k | return CGIF_ERROR; |
618 | 1.07k | } |
619 | 2.54k | pNewBef = malloc(pConfig->fmtChan * MULU16(imageWidth, imageHeight)); |
620 | 2.54k | if(pNewBef == NULL) { |
621 | 0 | pGIF->curResult = CGIF_EALLOC; |
622 | 0 | return pGIF->curResult; |
623 | 0 | } |
624 | 2.54k | memcpy(pNewBef, pConfig->pImageData, pConfig->fmtChan * MULU16(imageWidth, imageHeight)); |
625 | 2.54k | fConfig.pLocalPalette = aPalette; |
626 | 2.54k | fConfig.pImageData = malloc(pGIF->config.width * (uint32_t)pGIF->config.height); |
627 | 2.54k | if(fConfig.pImageData == NULL) { |
628 | 0 | free(pNewBef); |
629 | 0 | pGIF->curResult = CGIF_EALLOC; |
630 | 0 | return pGIF->curResult; |
631 | 0 | } |
632 | 2.54k | fConfig.delay = pConfig->delay; |
633 | 2.54k | fConfig.attrFlags = CGIF_FRAME_ATTR_USE_LOCAL_TABLE; |
634 | 2.54k | if(pConfig->attrFlags & CGIF_RGB_FRAME_ATTR_INTERLACED) { |
635 | 1.40k | fConfig.attrFlags |= CGIF_FRAME_ATTR_INTERLACED; |
636 | 1.40k | } |
637 | | |
638 | 2.54k | colHashTable* colhash = get_color_histogram(pConfig->pImageData, numPixel, pConfig->fmtChan, &hasAlpha); |
639 | 2.54k | if(colhash == NULL) { |
640 | 0 | free(pNewBef); |
641 | 0 | free(fConfig.pImageData); |
642 | 0 | pGIF->curResult = CGIF_EALLOC; |
643 | 0 | return pGIF->curResult; |
644 | 0 | } |
645 | 2.54k | const uint8_t bDither = !(pConfig->attrFlags & CGIF_RGB_FRAME_ATTR_NO_DITHERING); |
646 | 2.54k | const int sizeLCT = quantize_and_dither(colhash, pConfig->pImageData, numPixel, pGIF->config.width, pConfig->fmtChan, fConfig.pImageData, aPalette, 8, bDither, hasAlpha, pGIF->pBefImageData, pGIF->befFmtChan); |
647 | 2.54k | free_col_hash_table(colhash); |
648 | 2.54k | if(sizeLCT < 0) { |
649 | 0 | free(pNewBef); |
650 | 0 | free(fConfig.pImageData); |
651 | 0 | pGIF->curResult = CGIF_EALLOC; |
652 | 0 | return pGIF->curResult; |
653 | 0 | } |
654 | | |
655 | 2.54k | fConfig.numLocalPaletteEntries = sizeLCT; |
656 | 2.54k | if(hasAlpha) { |
657 | 439 | fConfig.attrFlags |= CGIF_FRAME_ATTR_HAS_ALPHA; |
658 | 439 | fConfig.transIndex = sizeLCT; |
659 | 2.10k | } else { |
660 | 2.10k | fConfig.attrFlags |= CGIF_FRAME_ATTR_HAS_SET_TRANS; |
661 | 2.10k | fConfig.transIndex = sizeLCT; |
662 | 2.10k | } |
663 | 2.54k | cgif_result r = cgif_addframe(pGIF->pGIF, &fConfig); |
664 | 2.54k | free(pGIF->pBefImageData); |
665 | 2.54k | pGIF->pBefImageData = pNewBef; |
666 | 2.54k | pGIF->befFmtChan = pConfig->fmtChan; |
667 | | |
668 | | // cleanup |
669 | 2.54k | free(fConfig.pImageData); |
670 | 2.54k | pGIF->curResult = r; |
671 | 2.54k | return r; |
672 | 2.54k | } |
673 | | |
674 | 1.15k | cgif_result cgif_rgb_close(CGIFrgb* pGIF) { |
675 | 1.15k | cgif_result r = cgif_close(pGIF->pGIF); |
676 | 1.15k | free(pGIF->pBefImageData); |
677 | 1.15k | free(pGIF); |
678 | 1.15k | return r; |
679 | 1.15k | } |