sixel_quant.c

filter: Statementstmt 93.9% 485 / 516 Branchbran 86.0% 198 / 230 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 91.5% 683 / 746 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« sixel_write.c ↑ Summary
1 /*
2 * Imager::File::SIXEL - colour quantization used by the SIXEL encoder.
3 *
4 * Copyright (C) 2026 davenonymous.
5 *
6 * This library is free software; you can redistribute it and/or modify
7 * it under the same terms as Perl itself.
8 *
9 * Palette construction:
10 *
11 * exact - images with few colours keep them, rounded to SIXEL
12 * percentages; colours that round alike share an entry.
13 * adaptive - a 5/6/5 bit histogram is split into boxes, always
14 * splitting the box whose best axis aligned cut removes
15 * the most squared error (a greedy variant of Wu's
16 * quantizer). Each box contributes its mean colour.
17 * webmap - the fixed 6x6x6 web-safe cube.
18 *
19 * Pixel mapping uses a lazily filled 6/6/6 bit lookup table over cells
20 * of 4 x 4 x 4 colours. When dithering, a cell maps all its colours to
21 * the entry nearest to its centre; the dither absorbs the difference.
22 * Without dithering every colour is mapped to its exactly nearest
23 * entry: a cell holds either the entry nearest to all its colours or a
24 * list of the entries that can be nearest to one of them, with the
25 * answer for each colour cached once found.
26 */
27 #include "sixel_quant.h"
28  
29 #include <limits.h>
30 #include <math.h>
31 #include <stdlib.h>
32 #include <string.h>
33  
34 #define PIXEL_PAINTED(p) ((p)[3] != 0)
35  
36 int
37 23756 sixel_percent_from_sample(int sample) {
38 23756 return (sample * 100 + 127) / 255;
39 }
40  
41 int
42 15941 sixel_sample_from_percent(int percent) {
43 15941 return (percent * 255 + 50) / 100;
44 }
45  
46 static unsigned char
47 15941 snapped_sample(int sample) {
48 15941 return (unsigned char)sixel_sample_from_percent(sixel_percent_from_sample(sample));
49 }
50  
51 void
52 23 sixel_palette_snap(sixel_palette *palette) {
53 int i, c;
54  
55 2094 ▶ for (i = 0; i < palette->size; ++i) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < palette->size; ++i) { 2071 23 2094
56 8284 ▶ for (c = 0; c < 3; ++c)
Branch: 1 branch
BranchTrueFalseTotal
for (c = 0; c < 3; ++c) 6213 2071 8284
57 6213 palette->rgb[i][c] = snapped_sample(palette->rgb[i][c]);
58 }
59 23 }
60  
61 void
62 4 sixel_palette_webmap(sixel_palette *palette) {
63 int r, g, b;
64 4 int n = 0;
65  
66 28 ▶ for (r = 0; r < 6; ++r) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < 6; ++r) { 24 4 28
67 168 ▶ for (g = 0; g < 6; ++g) {
Branch: 1 branch
BranchTrueFalseTotal
for (g = 0; g < 6; ++g) { 144 24 168
68 1008 ▶ for (b = 0; b < 6; ++b) {
Branch: 1 branch
BranchTrueFalseTotal
for (b = 0; b < 6; ++b) { 864 144 1008
69 864 palette->rgb[n][0] = (unsigned char)(r * 51);
70 864 palette->rgb[n][1] = (unsigned char)(g * 51);
71 864 palette->rgb[n][2] = (unsigned char)(b * 51);
72 864 ++n;
73 }
74 }
75 }
76 4 palette->size = n;
77 4 }
78  
79 /* ------------------------------------------------------------------ */
80 /* exact palettes */
81  
82 #define EXACT_HASH_BITS 10
83 #define EXACT_HASH_SIZE (1 << EXACT_HASH_BITS)
84 #define EXACT_KEY_USED 0x01000000u
85  
86 typedef struct {
87 uint32_t key[EXACT_HASH_SIZE];
88 uint16_t index[EXACT_HASH_SIZE];
89 } exact_table;
90  
91 static uint32_t
92 4332 exact_slot(uint32_t key) {
93 4332 return (key * 2654435761u) >> (32 - EXACT_HASH_BITS);
94 }
95  
96 int
97 38 sixel_palette_exact(const unsigned char *rgba, size_t pixel_count, int max_colors,
98 sixel_palette *palette, uint16_t *map) {
99 exact_table table;
100 unsigned char snapped[256];
101 38 uint32_t last_pixel = 0;
102 38 uint16_t last_index = 0;
103 size_t i;
104 int sample;
105  
106 38 memset(table.key, 0, sizeof(table.key));
107 9766 ▶ for (sample = 0; sample < 256; ++sample)
Branch: 1 branch
BranchTrueFalseTotal
for (sample = 0; sample < 256; ++sample) 9728 38 9766
108 9728 snapped[sample] = snapped_sample(sample);
109 38 palette->size = 0;
110  
111 4867 ▶ for (i = 0; i < pixel_count; ++i, rgba += 4) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < pixel_count; ++i, rgba += 4) { 4841 26 4867
112 uint32_t pixel, key, slot;
113  
114 4841 ▶ if (!PIXEL_PAINTED(rgba)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!PIXEL_PAINTED(rgba)) { 108 4733 4841
115 108 map[i] = SIXEL_TRANSPARENT;
116 108 continue;
117 }
118 4733 pixel = EXACT_KEY_USED | ((uint32_t)rgba[0] << 16) | ((uint32_t)rgba[1] << 8) | rgba[2];
119 4733 ▶ if (pixel == last_pixel) {
Branch: 1 branch
BranchTrueFalseTotal
if (pixel == last_pixel) { 401 4332 4733
120 401 map[i] = last_index;
121 401 continue;
122 }
123  
124 /* colours are counted as SIXEL writes them */
125 4332 key = EXACT_KEY_USED | ((uint32_t)snapped[rgba[0]] << 16) | ((uint32_t)snapped[rgba[1]] << 8)
126 4332 | snapped[rgba[2]];
127 4332 slot = exact_slot(key);
128 4638 ▶ while (table.key[slot] != 0 && table.key[slot] != key)
Branch: 2 branches
BranchTrueFalseTotal
while (table.key[slot] != 0 && table.key[slot] != key) 2898 1740 4638
while (table.key[slot] != 0 && table.key[slot] != key) 306 2592 2898
129 306 slot = (slot + 1) & (EXACT_HASH_SIZE - 1);
130  
131 4332 ▶ if (table.key[slot] == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (table.key[slot] == 0) { 1740 2592 4332
132 1740 ▶ if (palette->size >= max_colors)
Branch: 1 branch
BranchTrueFalseTotal
if (palette->size >= max_colors) 12 1728 1740
133 12 return 0;
134 1728 table.key[slot] = key;
135 1728 table.index[slot] = (uint16_t)palette->size;
136 1728 palette->rgb[palette->size][0] = snapped[rgba[0]];
137 1728 palette->rgb[palette->size][1] = snapped[rgba[1]];
138 1728 palette->rgb[palette->size][2] = snapped[rgba[2]];
139 1728 ++palette->size;
140 }
141 4320 last_pixel = pixel;
142 4320 last_index = table.index[slot];
143 4320 map[i] = last_index;
144 }
145  
146 26 return 1;
147 }
148  
149 /* ------------------------------------------------------------------ */
150 /* nearest colour search */
151  
152 /* A palette ordered by green, so a search can start at the query's
153 * green value and stop once the green difference alone exceeds the
154 * best distance found. Coordinates are doubled so that the centres of
155 * lookup table cells are integers.
156 */
157 typedef struct {
158 const sixel_palette *palette;
159 int by_green[SIXEL_MAX_PALETTE];
160 int green2[SIXEL_MAX_PALETTE];
161 } green_order;
162  
163 static void
164 44 green_order_init(green_order *order, const sixel_palette *palette) {
165 int i;
166  
167 44 order->palette = palette;
168 /* insertion sort by green, ties by index; palettes are small */
169 5656 ▶ for (i = 0; i < palette->size; ++i) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < palette->size; ++i) { 5612 44 5656
170 5612 int green2 = 2 * palette->rgb[i][1];
171 5612 int j = i;
172 307491 ▶ while (j > 0 && order->green2[j - 1] > green2) {
Branch: 2 branches
BranchTrueFalseTotal
while (j > 0 && order->green2[j - 1] > green2) { 307410 81 307491
while (j > 0 && order->green2[j - 1] > green2) { 301879 5531 307410
173 301879 order->green2[j] = order->green2[j - 1];
174 301879 order->by_green[j] = order->by_green[j - 1];
175 301879 --j;
176 }
177 5612 order->green2[j] = green2;
178 5612 order->by_green[j] = i;
179 }
180 44 }
181  
182 /* Returns the first position in the green order whose green is not
183 * below g2.
184 */
185 static int
186 33512 green_position(const green_order *order, int g2) {
187 33512 int lo = 0;
188 33512 int hi = order->palette->size;
189  
190 265880 ▶ while (lo < hi) {
Branch: 1 branch
BranchTrueFalseTotal
while (lo < hi) { 232368 33512 265880
191 232368 int mid = (lo + hi) / 2;
192 232368 ▶ if (order->green2[mid] < g2)
Branch: 1 branch
BranchTrueFalseTotal
if (order->green2[mid] < g2) 114677 117691 232368
193 114677 lo = mid + 1;
194 else
195 117691 hi = mid;
196 }
197 33512 return lo;
198 }
199  
200 static inline void
201 906323 consider_entry(const green_order *order, int position, int r2, int g2, int b2,
202 int *best, int *best_index) {
203 906323 int index = order->by_green[position];
204 906323 const unsigned char *entry = order->palette->rgb[index];
205 906323 int dr = 2 * entry[0] - r2;
206 906323 int dg = 2 * entry[1] - g2;
207 906323 int db = 2 * entry[2] - b2;
208 906323 int d = dr * dr + dg * dg + db * db;
209  
210 906323 ▶ if (d < *best || (d == *best && index < *best_index)) {
Branch: 3 branches
BranchTrueFalseTotal
if (d < *best || (d == *best && index < *best_index)) { 778984 127339 906323
if (d < *best || (d == *best && index < *best_index)) { 382 778602 778984
if (d < *best || (d == *best && index < *best_index)) { 169 213 382
211 127508 *best = d;
212 127508 *best_index = index;
213 }
214 906323 }
215  
216 /* Returns the index of the palette entry nearest to the doubled
217 * coordinates (r2, g2, b2), preferring the lowest index on ties.
218 */
219 static int
220 33512 nearest_entry(const green_order *order, int r2, int g2, int b2) {
221 33512 int size = order->palette->size;
222 33512 int best = INT_MAX;
223 33512 int best_index = 0;
224 33512 int up = green_position(order, g2);
225 33512 int down = up - 1;
226  
227 620046 ▶ while (up < size || down >= 0) {
Branch: 2 branches
BranchTrueFalseTotal
while (up < size || down >= 0) { 483490 136556 620046
while (up < size || down >= 0) { 103044 33512 136556
228 586534 ▶ if (up < size) {
Branch: 1 branch
BranchTrueFalseTotal
if (up < size) { 483490 103044 586534
229 483490 int dg = order->green2[up] - g2;
230 483490 ▶ if (dg * dg > best)
Branch: 1 branch
BranchTrueFalseTotal
if (dg * dg > best) 28167 455323 483490
231 28167 up = size;
232 else
233 455323 consider_entry(order, up++, r2, g2, b2, &best, &best_index);
234 }
235 586534 ▶ if (down >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (down >= 0) { 479604 106930 586534
236 479604 int dg = g2 - order->green2[down];
237 479604 ▶ if (dg * dg > best)
Branch: 1 branch
BranchTrueFalseTotal
if (dg * dg > best) 28604 451000 479604
238 28604 down = -1;
239 else
240 451000 consider_entry(order, down--, r2, g2, b2, &best, &best_index);
241 }
242 }
243 33512 return best_index;
244 }
245  
246 /* Blocks of 16 x 16 x 16 colours, whose diameter in doubled
247 * coordinates is 2 * sqrt(3 * 15 * 15).
248 */
249 #define BLOCK_SHIFT 4
250 #define BLOCK_COUNT (1 << (3 * (8 - BLOCK_SHIFT)))
251 #define BLOCK_KEY(r, g, b) \
252 ((((unsigned)(r) >> BLOCK_SHIFT) << 8) | (((unsigned)(g) >> BLOCK_SHIFT) << 4) | ((unsigned)(b) >> BLOCK_SHIFT))
253 #define BLOCK_DIAMETER2 52.0
254  
255 /* A growable array of palette indices. */
256 typedef struct {
257 unsigned char *items;
258 size_t used;
259 size_t capacity;
260 } index_pool;
261  
262 /* Makes room for count more items of size bytes in a growable array. */
263 static int
264 42305 reserve_items(void **items, size_t *capacity, size_t used, size_t count, size_t size) {
265 42305 ▶ size_t wanted = *capacity ? *capacity : 1024;
Branch: 1 branch
BranchTrueFalseTotal
size_t wanted = *capacity ? *capacity : 1024; 42248 57 42305
266 void *grown;
267  
268 42305 ▶ if (used + count <= *capacity)
Branch: 1 branch
BranchTrueFalseTotal
if (used + count <= *capacity) 42177 128 42305
269 42177 return 1;
270 199 ▶ while (wanted < used + count)
Branch: 1 branch
BranchTrueFalseTotal
while (wanted < used + count) 71 128 199
271 71 wanted *= 2;
272 128 grown = realloc(*items, wanted * size);
273 128 ▶ if (!grown)
Branch: 1 branch
BranchTrueFalseTotal
if (!grown) 0 128 128
274 0 return 0;
275 128 *items = grown;
276 128 *capacity = wanted;
277 128 return 1;
278 }
279  
280 /* Appends to pool the entries among candidates (all entries if
281 * candidates is NULL) within distance limit2 (squared, doubled
282 * coordinates) of (r2, g2, b2). Returns the number appended, or -1 if
283 * the pool cannot grow.
284 */
285 static int
286 40590 collect_candidates(const green_order *order, const unsigned char *candidates, int count,
287 int r2, int g2, int b2, int limit2, index_pool *pool) {
288 40590 const sixel_palette *palette = order->palette;
289 40590 int collected = 0;
290 int i;
291  
292 40590 ▶ if (!candidates)
Branch: 1 branch
BranchTrueFalseTotal
if (!candidates) 33512 7078 40590
293 33512 count = palette->size;
294 40590 ▶ if (!reserve_items((void **)&pool->items, &pool->capacity, pool->used, (size_t)count, 1))
Branch: 1 branch
BranchTrueFalseTotal
if (!reserve_items((void **)&pool->items, &pool->capacity, pool->used, (size_t)count, 1)) 0 40590 40590
295 0 return -1;
296  
297 6652365 ▶ for (i = 0; i < count; ++i) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < count; ++i) { 6611775 40590 6652365
298 6611775 ▶ int index = candidates ? candidates[i] : i;
Branch: 1 branch
BranchTrueFalseTotal
int index = candidates ? candidates[i] : i; 29445 6582330 6611775
299 6611775 const unsigned char *entry = palette->rgb[index];
300 6611775 int dr = 2 * entry[0] - r2;
301 6611775 int dg = 2 * entry[1] - g2;
302 6611775 int db = 2 * entry[2] - b2;
303  
304 6611775 ▶ if (dr * dr + dg * dg + db * db <= limit2)
Branch: 1 branch
BranchTrueFalseTotal
if (dr * dr + dg * dg + db * db <= limit2) 153301 6458474 6611775
305 153301 pool->items[pool->used + collected++] = (unsigned char)index;
306 }
307 40590 return collected;
308 }
309  
310 /* The nearest of the candidate entries to (r2, g2, b2) in doubled
311 * coordinates, preferring the lowest index on ties.
312 */
313 static int
314 106527 nearest_candidate(const sixel_palette *palette, const unsigned char *candidates, int count,
315 int r2, int g2, int b2) {
316 106527 int best = INT_MAX;
317 106527 int best_index = 0;
318 int i;
319  
320 582381 ▶ for (i = 0; i < count; ++i) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < count; ++i) { 475854 106527 582381
321 475854 int index = candidates[i];
322 475854 const unsigned char *entry = palette->rgb[index];
323 475854 int dr = 2 * entry[0] - r2;
324 475854 int dg = 2 * entry[1] - g2;
325 475854 int db = 2 * entry[2] - b2;
326 475854 int d = dr * dr + dg * dg + db * db;
327 475854 ▶ if (d < best || (d == best && index < best_index)) {
Branch: 3 branches
BranchTrueFalseTotal
if (d < best || (d == best && index < best_index)) { 263136 212718 475854
if (d < best || (d == best && index < best_index)) { 1178 261958 263136
if (d < best || (d == best && index < best_index)) { 0 1178 1178
328 212718 best = d;
329 212718 best_index = index;
330 }
331 }
332 106527 return best_index;
333 }
334  
335 /* The squared reach, in doubled coordinates, within which an entry may
336 * be nearest to some colour of a region: the distance from the region's
337 * centre to its nearest entry plus the region's diameter.
338 */
339 static int
340 40590 candidate_reach(const sixel_palette *palette, int nearest, int r2, int g2, int b2, double diameter) {
341 40590 const unsigned char *entry = palette->rgb[nearest];
342 40590 int dr = 2 * entry[0] - r2;
343 40590 int dg = 2 * entry[1] - g2;
344 40590 int db = 2 * entry[2] - b2;
345 40590 double reach = sqrt((double)(dr * dr + dg * dg + db * db)) + diameter;
346  
347 40590 return (int)ceil(reach * reach);
348 }
349  
350 /* For each block of 16 x 16 x 16 colours, the palette entries that may
351 * be nearest to one of its colours, found on first use.
352 */
353 typedef struct {
354 green_order order;
355 /* one past the start of a block's candidates in blocks, or 0 while
356 * unknown, and their number */
357 size_t block_first[BLOCK_COUNT];
358 uint16_t block_size[BLOCK_COUNT];
359 index_pool blocks;
360 } block_index;
361  
362 static void
363 44 block_index_init(block_index *index, const sixel_palette *palette) {
364 44 green_order_init(&index->order, palette);
365 44 memset(index->block_first, 0, sizeof(index->block_first));
366 44 index->blocks.items = NULL;
367 44 index->blocks.used = 0;
368 44 index->blocks.capacity = 0;
369 44 }
370  
371 static void
372 44 block_index_release(block_index *index) {
373 44 free(index->blocks.items);
374 44 index->blocks.items = NULL;
375 44 }
376  
377 /* Returns the entries that may be nearest to some colour of the block
378 * containing (r, g, b), computing them on first use, and their number
379 * in *count; NULL if memory ran out.
380 */
381 static const unsigned char *
382 106527 block_candidates(block_index *index, int r, int g, int b, int *count) {
383 106527 unsigned key = BLOCK_KEY(r, g, b);
384 106527 int block = 1 << BLOCK_SHIFT;
385  
386 106527 ▶ if (!index->block_first[key]) {
Branch: 1 branch
BranchTrueFalseTotal
if (!index->block_first[key]) { 33512 73015 106527
387 33512 int r2 = 2 * (r & ~(block - 1)) + block - 1;
388 33512 int g2 = 2 * (g & ~(block - 1)) + block - 1;
389 33512 int b2 = 2 * (b & ~(block - 1)) + block - 1;
390 33512 int nearest = nearest_entry(&index->order, r2, g2, b2);
391 33512 int limit2 = candidate_reach(index->order.palette, nearest, r2, g2, b2, BLOCK_DIAMETER2);
392 33512 int collected = collect_candidates(&index->order, NULL, 0, r2, g2, b2, limit2, &index->blocks);
393  
394 33512 ▶ if (collected < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (collected < 0) 0 33512 33512
395 0 return NULL;
396 33512 index->block_first[key] = index->blocks.used + 1;
397 33512 index->block_size[key] = (uint16_t)collected;
398 33512 index->blocks.used += (size_t)collected;
399 }
400 106527 *count = index->block_size[key];
401 106527 return index->blocks.items + index->block_first[key] - 1;
402 }
403  
404 /* Returns the entry nearest to (r2, g2, b2) in doubled coordinates,
405 * preferring the lowest index on ties.
406 */
407 static int
408 66480 nearest_color(block_index *index, int r2, int g2, int b2) {
409 66480 int count = 0;
410 66480 const unsigned char *candidates = block_candidates(index, r2 / 2, g2 / 2, b2 / 2, &count);
411  
412 return candidates
413 66480 ? nearest_candidate(index->order.palette, candidates, count, r2, g2, b2)
414 132960 ▶ : nearest_entry(&index->order, r2, g2, b2);
Branch: 1 branch
BranchTrueFalseTotal
: nearest_entry(&index->order, r2, g2, b2); 66480 0 66480
415 }
416  
417  
418 /* ------------------------------------------------------------------ */
419 /* adaptive palettes */
420  
421 #define HIST_SHIFT_R 3
422 #define HIST_SHIFT_G 2
423 #define HIST_SHIFT_B 3
424 #define HIST_KEY(r, g, b) \
425 ((((unsigned)(r) >> HIST_SHIFT_R) << 11) | (((unsigned)(g) >> HIST_SHIFT_G) << 5) | ((unsigned)(b) >> HIST_SHIFT_B))
426 #define HIST_SIZE (1 << 16)
427 #define HIST_MAX_LEVELS 64
428 #define REFINE_ITERATIONS 2
429  
430 static const int hist_levels[3] = { 32, 64, 32 };
431  
432 typedef struct {
433 uint64_t sum[3];
434 uint64_t count;
435 unsigned char coord[3];
436 } hist_bin;
437  
438 typedef struct {
439 size_t start;
440 size_t end;
441 double count;
442 double sum[3];
443 double gain;
444 int axis;
445 int cut;
446 } color_box;
447  
448 typedef struct {
449 double count;
450 double sum[3];
451 } box_moments;
452  
453 static double
454 123177 moments_energy(const box_moments *m) {
455 123177 return (m->sum[0] * m->sum[0] + m->sum[1] * m->sum[1] + m->sum[2] * m->sum[2]) / m->count;
456 }
457  
458 /* Sums the bins of box and records the axis aligned cut that removes
459 * the most squared error, or a gain of 0 when the box cannot be split.
460 */
461 static void
462 3148 box_analyze(color_box *box, const hist_bin *bins) {
463 box_moments buckets[HIST_MAX_LEVELS];
464 box_moments total;
465 double total_energy;
466 size_t i;
467 int axis;
468  
469 3148 memset(&total, 0, sizeof(total));
470 280776 ▶ for (i = box->start; i < box->end; ++i) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = box->start; i < box->end; ++i) { 277628 3148 280776
471 277628 total.count += (double)bins[i].count;
472 277628 total.sum[0] += (double)bins[i].sum[0];
473 277628 total.sum[1] += (double)bins[i].sum[1];
474 277628 total.sum[2] += (double)bins[i].sum[2];
475 }
476 3148 box->count = total.count;
477 3148 memcpy(box->sum, total.sum, sizeof(box->sum));
478 3148 box->gain = 0;
479 3148 box->axis = -1;
480 3148 box->cut = 0;
481  
482 3148 ▶ if (box->end - box->start < 2)
Branch: 1 branch
BranchTrueFalseTotal
if (box->end - box->start < 2) 17 3131 3148
483 17 return;
484  
485 3131 total_energy = moments_energy(&total);
486 12524 ▶ for (axis = 0; axis < 3; ++axis) {
Branch: 1 branch
BranchTrueFalseTotal
for (axis = 0; axis < 3; ++axis) { 9393 3131 12524
487 box_moments left;
488 9393 int levels = hist_levels[axis];
489 int t;
490  
491 9393 memset(buckets, 0, sizeof(buckets[0]) * levels);
492 842226 ▶ for (i = box->start; i < box->end; ++i) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = box->start; i < box->end; ++i) { 832833 9393 842226
493 832833 box_moments *bucket = buckets + bins[i].coord[axis];
494 832833 bucket->count += (double)bins[i].count;
495 832833 bucket->sum[0] += (double)bins[i].sum[0];
496 832833 bucket->sum[1] += (double)bins[i].sum[1];
497 832833 bucket->sum[2] += (double)bins[i].sum[2];
498 }
499  
500 9393 memset(&left, 0, sizeof(left));
501 235659 ▶ for (t = 0; t < levels - 1; ++t) {
Branch: 1 branch
BranchTrueFalseTotal
for (t = 0; t < levels - 1; ++t) { 234209 1450 235659
502 box_moments right;
503 double gain;
504 int c;
505  
506 234209 left.count += buckets[t].count;
507 936836 ▶ for (c = 0; c < 3; ++c)
Branch: 1 branch
BranchTrueFalseTotal
for (c = 0; c < 3; ++c) 702627 234209 936836
508 702627 left.sum[c] += buckets[t].sum[c];
509 234209 ▶ if (left.count == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (left.count == 0) 166243 67966 234209
510 166243 continue;
511 67966 right.count = total.count - left.count;
512 67966 ▶ if (right.count <= 0)
Branch: 1 branch
BranchTrueFalseTotal
if (right.count <= 0) 7943 60023 67966
513 7943 break;
514 240092 ▶ for (c = 0; c < 3; ++c)
Branch: 1 branch
BranchTrueFalseTotal
for (c = 0; c < 3; ++c) 180069 60023 240092
515 180069 right.sum[c] = total.sum[c] - left.sum[c];
516  
517 60023 gain = moments_energy(&left) + moments_energy(&right) - total_energy;
518 60023 ▶ if (gain > box->gain) {
Branch: 1 branch
BranchTrueFalseTotal
if (gain > box->gain) { 15221 44802 60023
519 15221 box->gain = gain;
520 15221 box->axis = axis;
521 15221 box->cut = t;
522 }
523 }
524 }
525 }
526  
527 /* Moves the bins of box whose coordinate on the cut axis is at most
528 * the cut to the front and returns the index of the first other bin.
529 */
530 static size_t
531 1568 box_partition(const color_box *box, hist_bin *bins) {
532 1568 size_t lo = box->start;
533 1568 size_t hi = box->end;
534  
535 245956 ▶ while (lo < hi) {
Branch: 1 branch
BranchTrueFalseTotal
while (lo < hi) { 244388 1568 245956
536 244388 ▶ if (bins[lo].coord[box->axis] <= box->cut) {
Branch: 1 branch
BranchTrueFalseTotal
if (bins[lo].coord[box->axis] <= box->cut) { 121790 122598 244388
537 121790 ++lo;
538 }
539 else {
540 122598 hist_bin swap = bins[lo];
541 122598 bins[lo] = bins[--hi];
542 122598 bins[hi] = swap;
543 }
544 }
545 1568 return lo;
546 }
547  
548 /* Collects the occupied histogram bins of the painted pixels. */
549 static hist_bin *
550 12 histogram_collect(const unsigned char *rgba, size_t pixel_count, size_t *bin_count) {
551 12 size_t capacity = pixel_count < HIST_SIZE ? pixel_count : HIST_SIZE;
552 uint32_t *slot_of_key;
553 hist_bin *bins;
554 12 size_t used = 0;
555 size_t i;
556  
557 12 slot_of_key = calloc(HIST_SIZE, sizeof(*slot_of_key));
558 12 bins = malloc(capacity * sizeof(*bins));
559 12 ▶ if (!slot_of_key || !bins) {
Branch: 2 branches
BranchTrueFalseTotal
if (!slot_of_key || !bins) { 12 0 12
if (!slot_of_key || !bins) { 0 12 12
560 0 free(slot_of_key);
561 0 free(bins);
562 0 return NULL;
563 }
564  
565 39876 ▶ for (i = 0; i < pixel_count; ++i, rgba += 4) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < pixel_count; ++i, rgba += 4) { 39864 12 39876
566 unsigned key;
567 hist_bin *bin;
568  
569 39864 ▶ if (!PIXEL_PAINTED(rgba))
Branch: 1 branch
BranchTrueFalseTotal
if (!PIXEL_PAINTED(rgba)) 0 39864 39864
570 0 continue;
571 39864 key = HIST_KEY(rgba[0], rgba[1], rgba[2]);
572 39864 ▶ if (slot_of_key[key] == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (slot_of_key[key] == 0) { 33240 6624 39864
573 33240 bin = bins + used++;
574 33240 memset(bin, 0, sizeof(*bin));
575 33240 bin->coord[0] = (unsigned char)(rgba[0] >> HIST_SHIFT_R);
576 33240 bin->coord[1] = (unsigned char)(rgba[1] >> HIST_SHIFT_G);
577 33240 bin->coord[2] = (unsigned char)(rgba[2] >> HIST_SHIFT_B);
578 33240 slot_of_key[key] = (uint32_t)used;
579 }
580 else {
581 6624 bin = bins + slot_of_key[key] - 1;
582 }
583 39864 bin->count++;
584 39864 bin->sum[0] += rgba[0];
585 39864 bin->sum[1] += rgba[1];
586 39864 bin->sum[2] += rgba[2];
587 }
588  
589 12 free(slot_of_key);
590 12 *bin_count = used;
591 12 return bins;
592 }
593  
594 static unsigned char
595 14220 mean_sample(double sum, double count) {
596 14220 double mean = sum / count + 0.5;
597 14220 ▶ return (unsigned char)(mean > 255 ? 255 : mean);
Branch: 1 branch
BranchTrueFalseTotal
return (unsigned char)(mean > 255 ? 255 : mean); 27 14193 14220
598 }
599  
600 /* Moves every palette entry to the mean of the histogram bins nearest
601 * to it (Lloyd's algorithm). Entries without bins keep their colour.
602 */
603 static int
604 12 palette_refine(const hist_bin *bins, size_t bin_count, sixel_palette *palette) {
605 double sums[SIXEL_MAX_PALETTE][4];
606 12 block_index *index = malloc(sizeof(*index));
607 int iteration;
608  
609 12 ▶ if (!index)
Branch: 1 branch
BranchTrueFalseTotal
if (!index) 0 12 12
610 0 return 0;
611  
612 36 ▶ for (iteration = 0; iteration < REFINE_ITERATIONS; ++iteration) {
Branch: 1 branch
BranchTrueFalseTotal
for (iteration = 0; iteration < REFINE_ITERATIONS; ++iteration) { 24 12 36
613 size_t i;
614 int k;
615  
616 24 memset(sums, 0, sizeof(sums));
617 24 block_index_init(index, palette);
618 66504 ▶ for (i = 0; i < bin_count; ++i) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < bin_count; ++i) { 66480 24 66504
619 66480 const hist_bin *bin = bins + i;
620 66480 double count = (double)bin->count;
621 66480 int nearest = nearest_color(index,
622 66480 (int)(2.0 * (double)bin->sum[0] / count + 0.5),
623 66480 (int)(2.0 * (double)bin->sum[1] / count + 0.5),
624 66480 (int)(2.0 * (double)bin->sum[2] / count + 0.5));
625 66480 sums[nearest][0] += (double)bin->sum[0];
626 66480 sums[nearest][1] += (double)bin->sum[1];
627 66480 sums[nearest][2] += (double)bin->sum[2];
628 66480 sums[nearest][3] += count;
629 }
630 3184 ▶ for (k = 0; k < palette->size; ++k) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < palette->size; ++k) { 3160 24 3184
631 3160 ▶ if (sums[k][3] == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (sums[k][3] == 0) 0 3160 3160
632 0 continue;
633 3160 palette->rgb[k][0] = mean_sample(sums[k][0], sums[k][3]);
634 3160 palette->rgb[k][1] = mean_sample(sums[k][1], sums[k][3]);
635 3160 palette->rgb[k][2] = mean_sample(sums[k][2], sums[k][3]);
636 }
637 24 block_index_release(index);
638 }
639 12 free(index);
640 12 return 1;
641 }
642  
643 int
644 12 sixel_palette_adaptive(const unsigned char *rgba, size_t pixel_count, int max_colors,
645 sixel_palette *palette) {
646 color_box boxes[SIXEL_MAX_PALETTE];
647 size_t bin_count;
648 hist_bin *bins;
649 int box_count;
650 int ok;
651 int i;
652  
653 12 bins = histogram_collect(rgba, pixel_count, &bin_count);
654 12 ▶ if (!bins)
Branch: 1 branch
BranchTrueFalseTotal
if (!bins) 0 12 12
655 0 return 0;
656  
657 12 palette->size = 0;
658 12 ▶ if (bin_count == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (bin_count == 0) { 0 12 12
659 0 free(bins);
660 0 return 1;
661 }
662  
663 12 boxes[0].start = 0;
664 12 boxes[0].end = bin_count;
665 12 box_analyze(boxes, bins);
666 12 box_count = 1;
667  
668 1580 ▶ while (box_count < max_colors) {
Branch: 1 branch
BranchTrueFalseTotal
while (box_count < max_colors) { 1568 12 1580
669 1568 color_box *widest = NULL;
670 size_t middle;
671  
672 197602 ▶ for (i = 0; i < box_count; ++i) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < box_count; ++i) { 196034 1568 197602
673 196034 ▶ if (boxes[i].gain > 0 && (!widest || boxes[i].gain > widest->gain))
Branch: 3 branches
BranchTrueFalseTotal
if (boxes[i].gain > 0 && (!widest || boxes[i].gain > widest->gain)) 195042 992 196034
if (boxes[i].gain > 0 && (!widest || boxes[i].gain > widest->gain)) 193474 1568 195042
if (boxes[i].gain > 0 && (!widest || boxes[i].gain > widest->gain)) 5680 187794 193474
674 7248 widest = boxes + i;
675 }
676 1568 ▶ if (!widest)
Branch: 1 branch
BranchTrueFalseTotal
if (!widest) 0 1568 1568
677 0 break;
678  
679 1568 middle = box_partition(widest, bins);
680 1568 boxes[box_count].start = middle;
681 1568 boxes[box_count].end = widest->end;
682 1568 widest->end = middle;
683 1568 box_analyze(widest, bins);
684 1568 box_analyze(boxes + box_count, bins);
685 1568 ++box_count;
686 }
687  
688 1592 ▶ for (i = 0; i < box_count; ++i) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < box_count; ++i) { 1580 12 1592
689 1580 palette->rgb[i][0] = mean_sample(boxes[i].sum[0], boxes[i].count);
690 1580 palette->rgb[i][1] = mean_sample(boxes[i].sum[1], boxes[i].count);
691 1580 palette->rgb[i][2] = mean_sample(boxes[i].sum[2], boxes[i].count);
692 }
693 12 palette->size = box_count;
694 12 ok = palette_refine(bins, bin_count, palette);
695 12 sixel_palette_snap(palette);
696  
697 12 free(bins);
698 12 return ok;
699 }
700  
701 /* ------------------------------------------------------------------ */
702 /* lookup table */
703  
704 #define LUT_SHIFT 2
705 #define LUT_SIZE (1 << 18)
706 #define LUT_KEY(r, g, b) \
707 ((((unsigned)(r) >> LUT_SHIFT) << 12) | (((unsigned)(g) >> LUT_SHIFT) << 6) | ((unsigned)(b) >> LUT_SHIFT))
708 #define CELL_COLORS (1 << (3 * LUT_SHIFT))
709 #define CELL_SLOT(r, g, b) \
710 (((((unsigned)(r) & 3) << LUT_SHIFT | ((unsigned)(g) & 3)) << LUT_SHIFT) | ((unsigned)(b) & 3))
711 /* lookup table values: palette indices, then candidate list numbers */
712 #define LUT_FIRST_LIST 0x0100
713 #define LUT_SEARCH 0xFFFE
714 #define LUT_EMPTY 0xFFFF
715 #define LUT_MAX_LISTS (LUT_SEARCH - LUT_FIRST_LIST)
716 #define CHOICE_UNKNOWN 0xFFFF
717 /* Twice the largest distance, in doubled coordinates, between the
718 * centre of a cell and any colour in it: 2 * sqrt(3 * 3 * 3), rounded up.
719 */
720 #define LUT_CELL_DIAMETER2 10.4
721 /* The palette entries that may be nearest to some colour of a cell,
722 * stored in the finder's candidate pool, and the nearest entry of each
723 * of the cell's colours once known.
724 */
725 typedef struct {
726 size_t first;
727 int count;
728 uint16_t choice[CELL_COLORS];
729 } candidate_list;
730  
731 typedef struct {
732 block_index index;
733 /* whether to resolve colours exactly or by the cell centre */
734 int exact;
735 uint16_t *lut;
736 candidate_list *lists;
737 size_t list_count;
738 size_t list_capacity;
739 index_pool pool;
740 } nearest_finder;
741  
742 static int
743 20 nearest_init(nearest_finder *finder, const sixel_palette *palette, int exact) {
744 20 memset(finder, 0, sizeof(*finder));
745 20 finder->exact = exact;
746 20 finder->lut = malloc(LUT_SIZE * sizeof(*finder->lut));
747 20 ▶ if (!finder->lut)
Branch: 1 branch
BranchTrueFalseTotal
if (!finder->lut) 0 20 20
748 0 return 0;
749 20 memset(finder->lut, 0xFF, LUT_SIZE * sizeof(*finder->lut));
750 20 block_index_init(&finder->index, palette);
751 20 return 1;
752 }
753  
754 static void
755 20 nearest_release(nearest_finder *finder) {
756 20 free(finder->lut);
757 20 free(finder->lists);
758 20 free(finder->pool.items);
759 20 block_index_release(&finder->index);
760 20 }
761  
762 /* Decides the lookup table cell containing (r, g, b), searching the
763 * candidates of its block. Without exact resolution the cell stores
764 * the entry nearest to its centre. With it, the cell stores the only
765 * entry that may be nearest to one of its colours, or a list of them.
766 */
767 static uint16_t
768 40047 lut_fill(nearest_finder *finder, unsigned key, int r, int g, int b) {
769 40047 const sixel_palette *palette = finder->index.order.palette;
770 40047 int cell = 1 << LUT_SHIFT;
771 40047 int r2 = 2 * (r & ~(cell - 1)) + cell - 1;
772 40047 int g2 = 2 * (g & ~(cell - 1)) + cell - 1;
773 40047 int b2 = 2 * (b & ~(cell - 1)) + cell - 1;
774 40047 int block_count = 0;
775 40047 const unsigned char *block = block_candidates(&finder->index, r, g, b, &block_count);
776 40047 int nearest = block
777 40047 ? nearest_candidate(palette, block, block_count, r2, g2, b2)
778 40047 ▶ : nearest_entry(&finder->index.order, r2, g2, b2);
Branch: 1 branch
BranchTrueFalseTotal
: nearest_entry(&finder->index.order, r2, g2, b2); 40047 0 40047
779 candidate_list *list;
780 int count;
781 40047 uint16_t value = LUT_SEARCH;
782  
783 40047 ▶ if (!finder->exact) {
Branch: 1 branch
BranchTrueFalseTotal
if (!finder->exact) { 32969 7078 40047
784 32969 finder->lut[key] = (uint16_t)nearest;
785 32969 return (uint16_t)nearest;
786 }
787  
788 7078 count = collect_candidates(&finder->index.order, block, block_count, r2, g2, b2,
789 candidate_reach(palette, nearest, r2, g2, b2, LUT_CELL_DIAMETER2),
790 &finder->pool);
791 7078 ▶ if (count == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (count == 1) { 5363 1715 7078
792 5363 value = (uint16_t)nearest;
793 }
794 1715 ▶ else if (count > 1 && finder->list_count < LUT_MAX_LISTS
Branch: 2 branches
BranchTrueFalseTotal
else if (count > 1 && finder->list_count < LUT_MAX_LISTS 1715 0 1715
else if (count > 1 && finder->list_count < LUT_MAX_LISTS 1715 0 1715
795 1715 ▶ && reserve_items((void **)&finder->lists, &finder->list_capacity, finder->list_count,
Branch: 1 branch
BranchTrueFalseTotal
&& reserve_items((void **)&finder->lists, &finder->list_capacity, finder->list_count, 1715 0 1715
796 1, sizeof(*finder->lists))) {
797 1715 list = finder->lists + finder->list_count;
798 1715 list->first = finder->pool.used;
799 1715 list->count = count;
800 1715 memset(list->choice, 0xFF, sizeof(list->choice));
801 1715 finder->pool.used += (size_t)count;
802 1715 value = (uint16_t)(LUT_FIRST_LIST + finder->list_count++);
803 }
804 /* otherwise memory ran out and every colour of the cell is searched */
805 7078 finder->lut[key] = value;
806 7078 return value;
807 }
808  
809 static uint16_t
810 1792 nearest_in_list(const nearest_finder *finder, candidate_list *list, int r, int g, int b) {
811 1792 const sixel_palette *palette = finder->index.order.palette;
812 1792 const unsigned char *candidates = finder->pool.items + list->first;
813 1792 uint16_t *choice = list->choice + CELL_SLOT(r, g, b);
814 1792 int best = INT_MAX;
815 1792 int best_index = 0;
816 int i;
817  
818 1792 ▶ if (*choice != CHOICE_UNKNOWN)
Branch: 1 branch
BranchTrueFalseTotal
if (*choice != CHOICE_UNKNOWN) 0 1792 1792
819 0 return *choice;
820  
821 5697 ▶ for (i = 0; i < list->count; ++i) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < list->count; ++i) { 3905 1792 5697
822 3905 int index = candidates[i];
823 3905 const unsigned char *entry = palette->rgb[index];
824 3905 int dr = entry[0] - r;
825 3905 int dg = entry[1] - g;
826 3905 int db = entry[2] - b;
827 3905 int d = dr * dr + dg * dg + db * db;
828 3905 ▶ if (d < best || (d == best && index < best_index)) {
Branch: 3 branches
BranchTrueFalseTotal
if (d < best || (d == best && index < best_index)) { 1145 2760 3905
if (d < best || (d == best && index < best_index)) { 21 1124 1145
if (d < best || (d == best && index < best_index)) { 0 21 21
829 2760 best = d;
830 2760 best_index = index;
831 }
832 }
833 1792 *choice = (uint16_t)best_index;
834 1792 return *choice;
835 }
836  
837 /* Returns the palette entry nearest to (r, g, b), preferring the
838 * lowest index on ties.
839 */
840 static inline uint16_t
841 44106 nearest_lookup(nearest_finder *finder, int r, int g, int b) {
842 44106 unsigned key = LUT_KEY(r, g, b);
843 44106 uint16_t value = finder->lut[key];
844  
845 44106 ▶ if (value == LUT_EMPTY)
Branch: 1 branch
BranchTrueFalseTotal
if (value == LUT_EMPTY) 40047 4059 44106
846 40047 value = lut_fill(finder, key, r, g, b);
847 44106 ▶ if (value < LUT_FIRST_LIST)
Branch: 1 branch
BranchTrueFalseTotal
if (value < LUT_FIRST_LIST) 42314 1792 44106
848 42314 return value;
849 1792 ▶ if (value == LUT_SEARCH)
Branch: 1 branch
BranchTrueFalseTotal
if (value == LUT_SEARCH) 0 1792 1792
850 0 return (uint16_t)nearest_entry(&finder->index.order, 2 * r, 2 * g, 2 * b);
851 1792 return nearest_in_list(finder, finder->lists + (value - LUT_FIRST_LIST), r, g, b);
852 }
853  
854 /* ------------------------------------------------------------------ */
855 /* pixel mapping */
856  
857 static const unsigned char bayer8[64] = {
858 0, 32, 8, 40, 2, 34, 10, 42,
859 48, 16, 56, 24, 50, 18, 58, 26,
860 12, 44, 4, 36, 14, 46, 6, 38,
861 60, 28, 52, 20, 62, 30, 54, 22,
862 3, 35, 11, 43, 1, 33, 9, 41,
863 51, 19, 59, 27, 49, 17, 57, 25,
864 15, 47, 7, 39, 13, 45, 5, 37,
865 63, 31, 55, 23, 61, 29, 53, 21,
866 };
867  
868 static inline int
869 110376 clamp_sample(int value) {
870 110376 ▶ return value < 0 ? 0 : value > 255 ? 255 : value;
Branch: 1 branch
BranchTrueFalseTotal
return value < 0 ? 0 : value > 255 ? 255 : value; 102866 7510 110376
871 }
872  
873 /* The mean distance from each palette entry to its nearest neighbour,
874 * used as the amplitude of ordered dithering.
875 */
876 static double
877 3 palette_spacing(const sixel_palette *palette) {
878 3 double total = 0;
879 int i, j;
880  
881 3 ▶ if (palette->size < 2)
Branch: 1 branch
BranchTrueFalseTotal
if (palette->size < 2) 0 3 3
882 0 return 0;
883  
884 691 ▶ for (i = 0; i < palette->size; ++i) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < palette->size; ++i) { 688 3 691
885 688 int nearest = INT_MAX;
886 159536 ▶ for (j = 0; j < palette->size; ++j) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < palette->size; ++j) { 158848 688 159536
887 int dr, dg, db, d;
888 158848 ▶ if (i == j)
Branch: 1 branch
BranchTrueFalseTotal
if (i == j) 688 158160 158848
889 688 continue;
890 158160 dr = palette->rgb[i][0] - palette->rgb[j][0];
891 158160 dg = palette->rgb[i][1] - palette->rgb[j][1];
892 158160 db = palette->rgb[i][2] - palette->rgb[j][2];
893 158160 d = dr * dr + dg * dg + db * db;
894 158160 ▶ if (d < nearest)
Branch: 1 branch
BranchTrueFalseTotal
if (d < nearest) 7505 150655 158160
895 7505 nearest = d;
896 }
897 688 total += sqrt((double)nearest);
898 }
899 3 return total / palette->size;
900 }
901  
902 static void
903 7 map_plain(const unsigned char *rgba, size_t width, size_t height,
904 nearest_finder *finder, uint16_t *map) {
905 7 size_t count = width * height;
906 size_t i;
907  
908 7321 ▶ for (i = 0; i < count; ++i, rgba += 4) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < count; ++i, rgba += 4) { 7314 7 7321
909 14628 ▶ map[i] = PIXEL_PAINTED(rgba)
Branch: 1 branch
BranchTrueFalseTotal
map[i] = PIXEL_PAINTED(rgba) 7314 0 7314
910 7314 ? nearest_lookup(finder, rgba[0], rgba[1], rgba[2])
911 : SIXEL_TRANSPARENT;
912 }
913 7 }
914  
915 static void
916 3 map_ordered(const unsigned char *rgba, size_t width, size_t height,
917 nearest_finder *finder, uint16_t *map) {
918 3 double spacing = palette_spacing(finder->index.order.palette);
919 int offset[64];
920 size_t x, y;
921 int i;
922  
923 195 ▶ for (i = 0; i < 64; ++i)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 64; ++i) 192 3 195
924 192 offset[i] = (int)floor(((bayer8[i] + 0.5) / 64.0 - 0.5) * spacing + 0.5);
925  
926 115 ▶ for (y = 0; y < height; ++y) {
Branch: 1 branch
BranchTrueFalseTotal
for (y = 0; y < height; ++y) { 112 3 115
927 112 const int *row_offset = offset + (y & 7) * 8;
928 8560 ▶ for (x = 0; x < width; ++x, rgba += 4, ++map) {
Branch: 1 branch
BranchTrueFalseTotal
for (x = 0; x < width; ++x, rgba += 4, ++map) { 8448 112 8560
929 int o;
930 8448 ▶ if (!PIXEL_PAINTED(rgba)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!PIXEL_PAINTED(rgba)) { 0 8448 8448
931 0 *map = SIXEL_TRANSPARENT;
932 0 continue;
933 }
934 8448 o = row_offset[x & 7];
935 8448 *map = nearest_lookup(finder,
936 8448 clamp_sample(rgba[0] + o),
937 8448 clamp_sample(rgba[1] + o),
938 8448 clamp_sample(rgba[2] + o));
939 }
940 }
941 3 }
942  
943 /* Errors are kept in sixteenths of a sample. Every pixel distributes
944 * at most 16 * 255 sixteenths, so adding ERROR_BIAS keeps the sum
945 * positive and the rounding below a plain unsigned division.
946 */
947 #define ERROR_BIAS (16 * 512)
948  
949 /* Rounds an error in sixteenths to whole sample units, halves up. */
950 static inline int
951 85032 error_units(int sixteenths) {
952 85032 return (int)((unsigned)(sixteenths + ERROR_BIAS + 8) / 16u) - ERROR_BIAS / 16;
953 }
954  
955 /* Floyd-Steinberg error diffusion with serpentine scanning. The error
956 * for the next pixel of a row is carried in locals; the errors for the
957 * following row are collected in a buffer with a guard cell at either
958 * end.
959 */
960 static int
961 10 map_diffusion(const unsigned char *rgba, size_t width, size_t height,
962 nearest_finder *finder, uint16_t *map) {
963 10 const sixel_palette *palette = finder->index.order.palette;
964 10 size_t row_cells = (width + 2) * 3;
965 10 int *current = calloc(row_cells, sizeof(int));
966 10 int *next = calloc(row_cells, sizeof(int));
967 size_t y;
968  
969 10 ▶ if (!current || !next) {
Branch: 2 branches
BranchTrueFalseTotal
if (!current || !next) { 10 0 10
if (!current || !next) { 0 10 10
970 0 free(current);
971 0 free(next);
972 0 return 0;
973 }
974  
975 380 ▶ for (y = 0; y < height; ++y) {
Branch: 1 branch
BranchTrueFalseTotal
for (y = 0; y < height; ++y) { 370 10 380
976 370 int forward = (y & 1) == 0;
977 370 ▶ ptrdiff_t step = forward ? 1 : -1;
Branch: 1 branch
BranchTrueFalseTotal
ptrdiff_t step = forward ? 1 : -1; 185 185 370
978 370 ▶ size_t x = forward ? 0 : width - 1;
Branch: 1 branch
BranchTrueFalseTotal
size_t x = forward ? 0 : width - 1; 185 185 370
979 370 const unsigned char *pixel = rgba + (y * width + x) * 4;
980 370 uint16_t *out = map + y * width + x;
981 370 int *below = next + (x + 1) * 3;
982 370 const int *above = current + (x + 1) * 3;
983 370 int carry[3] = { 0, 0, 0 };
984 size_t n;
985 int *swap;
986  
987 370 memset(next, 0, row_cells * sizeof(int));
988 28714 ▶ for (n = 0; n < width; ++n, pixel += 4 * step, out += step, below += 3 * step, above += 3 * step) {
Branch: 1 branch
BranchTrueFalseTotal
for (n = 0; n < width; ++n, pixel += 4 * step, out += step, below += 3 * step, above += 3 * step) { 28344 370 28714
989 const unsigned char *chosen;
990 int value[3];
991 uint16_t index;
992 int c;
993  
994 28344 ▶ if (!PIXEL_PAINTED(pixel)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!PIXEL_PAINTED(pixel)) { 0 28344 28344
995 0 *out = SIXEL_TRANSPARENT;
996 0 carry[0] = carry[1] = carry[2] = 0;
997 0 continue;
998 }
999 113376 ▶ for (c = 0; c < 3; ++c)
Branch: 1 branch
BranchTrueFalseTotal
for (c = 0; c < 3; ++c) 85032 28344 113376
1000 85032 value[c] = clamp_sample(pixel[c] + error_units(above[c] + carry[c]));
1001  
1002 28344 index = nearest_lookup(finder, value[0], value[1], value[2]);
1003 28344 *out = index;
1004  
1005 28344 chosen = palette->rgb[index];
1006 113376 ▶ for (c = 0; c < 3; ++c) {
Branch: 1 branch
BranchTrueFalseTotal
for (c = 0; c < 3; ++c) { 85032 28344 113376
1007 85032 int error = value[c] - chosen[c];
1008 85032 carry[c] = error * 7;
1009 85032 below[c - 3 * step] += error * 3;
1010 85032 below[c] += error * 5;
1011 85032 below[c + 3 * step] += error;
1012 }
1013 }
1014 370 swap = current;
1015 370 current = next;
1016 370 next = swap;
1017 }
1018  
1019 10 free(current);
1020 10 free(next);
1021 10 return 1;
1022 }
1023  
1024 int
1025 20 sixel_map_pixels(const unsigned char *rgba, size_t width, size_t height,
1026 const sixel_palette *palette, sixel_dither dither, uint16_t *map) {
1027 nearest_finder *finder;
1028 20 int ok = 1;
1029  
1030 20 ▶ if (palette->size == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (palette->size == 0) { 0 20 20
1031 0 size_t i, count = width * height;
1032 0 ▶ for (i = 0; i < count; ++i)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < count; ++i) 0 0 0
1033 0 map[i] = SIXEL_TRANSPARENT;
1034 0 return 1;
1035 }
1036  
1037 20 finder = malloc(sizeof(*finder));
1038 /* dithering absorbs the error of resolving by cell centres */
1039 20 ▶ if (!finder || !nearest_init(finder, palette, dither == SIXEL_DITHER_NONE)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!finder || !nearest_init(finder, palette, dither == SIXEL_DITHER_NONE)) { 20 0 20
if (!finder || !nearest_init(finder, palette, dither == SIXEL_DITHER_NONE)) { 0 20 20
1040 0 free(finder);
1041 0 return 0;
1042 }
1043  
1044 20 switch (dither) {
1045 7 case SIXEL_DITHER_NONE:
1046 7 map_plain(rgba, width, height, finder, map);
1047 7 break;
1048 3 case SIXEL_DITHER_ORDERED:
1049 3 map_ordered(rgba, width, height, finder, map);
1050 3 break;
1051 10 case SIXEL_DITHER_DIFFUSION:
1052 10 ok = map_diffusion(rgba, width, height, finder, map);
1053 10 break;
1054 }
1055  
1056 20 nearest_release(finder);
1057 20 free(finder);
1058 20 return ok;
1059 }
« sixel_write.c ↑ Summary