-
Notifications
You must be signed in to change notification settings - Fork 232
/
quantize.c
1477 lines (1302 loc) · 63.4 KB
/
quantize.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* quantize.c - Histograms and quantization for gifsicle.
Copyright (C) 1997-2024 Eddie Kohler, ekohler@gmail.com
This file is part of gifsicle.
Gifsicle is free software. It is distributed under the GNU Public License,
version 2; you can copy, distribute, or alter it at will, as long
as this notice is kept intact and this source code is made available. There
is no warranty, express or implied. */
#include <config.h>
#include "gifsicle.h"
#include "kcolor.h"
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <ctype.h>
#include <math.h>
/* COLORMAP FUNCTIONS return a palette (a vector of Gif_Colors). The
pixel fields are undefined; the haspixel fields are all 0. */
typedef struct {
int first;
int size;
uint32_t pixel;
} adaptive_slot;
Gif_Colormap* colormap_median_cut(kchist* kch, Gt_OutputData* od)
{
int adapt_size = od->colormap_size;
adaptive_slot *slots = Gif_NewArray(adaptive_slot, adapt_size);
Gif_Colormap *gfcm = Gif_NewFullColormap(adapt_size, 256);
Gif_Color *adapt = gfcm->col;
int nadapt;
int i, j, k;
/* This code was written with reference to ppmquant by Jef Poskanzer,
part of the pbmplus package. */
if (adapt_size < 2 || adapt_size > 256)
fatal_error("adaptive palette size must be between 2 and 256");
if (adapt_size >= kch->n && !od->colormap_fixed)
warning(1, "trivial adaptive palette (only %d %s in source)",
kch->n, kch->n == 1 ? "color" : "colors");
if (adapt_size >= kch->n)
adapt_size = kch->n;
/* 0. remove any transparent color from consideration; reduce adaptive
palette size to accommodate transparency if it looks like that'll be
necessary */
if (adapt_size > 2 && adapt_size < kch->n && kch->n <= 265
&& od->colormap_needs_transparency)
adapt_size--;
/* 1. set up the first slot, containing all pixels. */
slots[0].first = 0;
slots[0].size = kch->n;
slots[0].pixel = 0;
for (i = 0; i < kch->n; i++)
slots[0].pixel += kch->h[i].count;
/* 2. split slots until we have enough. */
for (nadapt = 1; nadapt < adapt_size; nadapt++) {
adaptive_slot *split = 0;
kcolor minc, maxc;
kchistitem *slice;
/* 2.1. pick the slot to split. */
{
uint32_t split_pixel = 0;
for (i = 0; i < nadapt; i++)
if (slots[i].size >= 2 && slots[i].pixel > split_pixel) {
split = &slots[i];
split_pixel = slots[i].pixel;
}
if (!split)
break;
}
slice = &kch->h[split->first];
/* 2.2. find its extent. */
{
kchistitem *trav = slice;
minc = maxc = trav->ka.k;
for (i = 1, trav++; i < split->size; i++, trav++)
for (k = 0; k != 3; ++k) {
minc.a[k] = min(minc.a[k], trav->ka.a[k]);
maxc.a[k] = max(maxc.a[k], trav->ka.a[k]);
}
}
/* 2.3. decide how to split it. use the luminance method. also sort
the colors. */
{
double red_diff = 0.299 * (maxc.a[0] - minc.a[0]);
double green_diff = 0.587 * (maxc.a[1] - minc.a[1]);
double blue_diff = 0.114 * (maxc.a[2] - minc.a[2]);
if (red_diff >= green_diff && red_diff >= blue_diff)
qsort(slice, split->size, sizeof(kchistitem), kchistitem_compare_red);
else if (green_diff >= blue_diff)
qsort(slice, split->size, sizeof(kchistitem), kchistitem_compare_green);
else
qsort(slice, split->size, sizeof(kchistitem), kchistitem_compare_blue);
}
/* 2.4. decide where to split the slot and split it there. */
{
uint32_t half_pixels = split->pixel / 2;
uint32_t pixel_accum = slice[0].count;
uint32_t diff1, diff2;
for (i = 1; i < split->size - 1 && pixel_accum < half_pixels; i++)
pixel_accum += slice[i].count;
/* We know the area before the split has more pixels than the
area after, possibly by a large margin (bad news). If it
would shrink the margin, change the split. */
diff1 = 2*pixel_accum - split->pixel;
diff2 = split->pixel - 2*(pixel_accum - slice[i-1].count);
if (diff2 < diff1 && i > 1) {
i--;
pixel_accum -= slice[i].count;
}
slots[nadapt].first = split->first + i;
slots[nadapt].size = split->size - i;
slots[nadapt].pixel = split->pixel - pixel_accum;
split->size = i;
split->pixel = pixel_accum;
}
}
/* 3. make the new palette by choosing one color from each slot. */
for (i = 0; i < nadapt; i++) {
double px[3];
kchistitem* slice = &kch->h[ slots[i].first ];
kcolor kc;
px[0] = px[1] = px[2] = 0;
for (j = 0; j != slots[i].size; ++j)
for (k = 0; k != 3; ++k)
px[k] += slice[j].ka.a[k] * (double) slice[j].count;
kc.a[0] = (int) (px[0] / slots[i].pixel);
kc.a[1] = (int) (px[1] / slots[i].pixel);
kc.a[2] = (int) (px[2] / slots[i].pixel);
adapt[i] = kc_togfcg(kc);
}
Gif_DeleteArray(slots);
gfcm->ncol = nadapt;
return gfcm;
}
void kcdiversity_init(kcdiversity* div, kchist* kch, int dodither) {
int i;
div->kch = kch;
qsort(kch->h, kch->n, sizeof(kchistitem), kchistitem_compare_popularity);
div->closest = Gif_NewArray(int, kch->n);
div->min_dist = Gif_NewArray(uint32_t, kch->n);
for (i = 0; i != kch->n; ++i)
div->min_dist[i] = (uint32_t) -1;
if (dodither) {
div->min_dither_dist = Gif_NewArray(uint32_t, kch->n);
for (i = 0; i != kch->n; ++i)
div->min_dither_dist[i] = (uint32_t) -1;
} else
div->min_dither_dist = NULL;
div->chosen = Gif_NewArray(int, kch->n);
div->nchosen = 0;
}
void kcdiversity_cleanup(kcdiversity* div) {
Gif_DeleteArray(div->closest);
Gif_DeleteArray(div->min_dist);
Gif_DeleteArray(div->min_dither_dist);
Gif_DeleteArray(div->chosen);
}
int kcdiversity_find_popular(kcdiversity* div) {
int i, n = div->kch->n;
for (i = 0; i != n && div->min_dist[i] == 0; ++i)
/* spin */;
return i;
}
int kcdiversity_find_diverse(kcdiversity* div, double ditherweight) {
int i, n = div->kch->n, chosen = kcdiversity_find_popular(div);
if (chosen == n)
/* skip */;
else if (!ditherweight || !div->min_dither_dist) {
for (i = chosen + 1; i != n; ++i)
if (div->min_dist[i] > div->min_dist[chosen])
chosen = i;
} else {
double max_dist = div->min_dist[chosen] + ditherweight * div->min_dither_dist[chosen];
for (i = chosen + 1; i != n; ++i)
if (div->min_dist[i] != 0) {
double dist = div->min_dist[i] + ditherweight * div->min_dither_dist[i];
if (dist > max_dist) {
chosen = i;
max_dist = dist;
}
}
}
return chosen;
}
int kcdiversity_choose(kcdiversity* div, int chosen, int dodither) {
int i, j, k, n = div->kch->n;
kchistitem* hist = div->kch->h;
div->min_dist[chosen] = 0;
if (div->min_dither_dist)
div->min_dither_dist[chosen] = 0;
div->closest[chosen] = chosen;
/* adjust the min_dist array */
for (i = 0; i != n; ++i)
if (div->min_dist[i]) {
uint32_t dist = kc_distance(hist[i].ka.k, hist[chosen].ka.k);
if (dist < div->min_dist[i]) {
div->min_dist[i] = dist;
div->closest[i] = chosen;
}
}
/* also account for dither distances */
if (dodither && div->min_dither_dist)
for (i = 0; i != div->nchosen; ++i) {
kcolor x = hist[chosen].ka.k, *y = &hist[div->chosen[i]].ka.k;
/* penalize combinations with large luminance difference */
double dL = abs(kc_luminance(x) - kc_luminance(*y));
dL = (dL > 8192 ? dL * 4 / 32767. : 1);
/* create combination */
for (k = 0; k != 3; ++k)
x.a[k] = (x.a[k] + y->a[k]) >> 1;
/* track closeness of combination to other colors */
for (j = 0; j != n; ++j)
if (div->min_dist[j]) {
double dist = kc_distance(hist[j].ka.k, x) * dL;
if (dist < div->min_dither_dist[j])
div->min_dither_dist[j] = (uint32_t) dist;
}
}
div->chosen[div->nchosen] = chosen;
++div->nchosen;
return chosen;
}
static void colormap_diversity_do_blend(kcdiversity* div) {
int i, j, k, n = div->kch->n;
kchistitem* hist = div->kch->h;
int* chosenmap = Gif_NewArray(int, n);
scale_color* di = Gif_NewArray(scale_color, div->nchosen);
for (i = 0; i != div->nchosen; ++i)
for (k = 0; k != 4; ++k)
di[i].a[k] = 0;
for (i = 0; i != div->nchosen; ++i)
chosenmap[div->chosen[i]] = i;
for (i = 0; i != n; ++i) {
double count = hist[i].count;
if (div->closest[i] == i)
count *= 3;
j = chosenmap[div->closest[i]];
for (k = 0; k != 3; ++k)
di[j].a[k] += hist[i].ka.a[k] * count;
di[j].a[3] += count;
}
for (i = 0; i != div->nchosen; ++i) {
int match = div->chosen[i];
if (di[i].a[3] >= 5 * hist[match].count)
for (k = 0; k != 3; ++k)
hist[match].ka.a[k] = (int) (di[i].a[k] / di[i].a[3]);
}
Gif_DeleteArray(chosenmap);
Gif_DeleteArray(di);
}
static Gif_Colormap *
colormap_diversity(kchist* kch, Gt_OutputData* od, int blend)
{
int adapt_size = od->colormap_size;
kcdiversity div;
Gif_Colormap* gfcm = Gif_NewFullColormap(adapt_size, 256);
int nadapt = 0;
int chosen;
/* This code uses XV's modified diversity algorithm, and was written
with reference to XV's implementation of that algorithm by John Bradley
<bradley@cis.upenn.edu> and Tom Lane <Tom.Lane@g.gp.cs.cmu.edu>. */
if (adapt_size < 2 || adapt_size > 256)
fatal_error("adaptive palette size must be between 2 and 256");
if (adapt_size > kch->n && !od->colormap_fixed)
warning(1, "trivial adaptive palette (only %d colors in source)", kch->n);
if (adapt_size > kch->n)
adapt_size = kch->n;
/* 0. remove any transparent color from consideration; reduce adaptive
palette size to accommodate transparency if it looks like that'll be
necessary */
/* It will be necessary to accommodate transparency if (1) there is
transparency in the image; (2) the adaptive palette isn't trivial; and
(3) there are a small number of colors in the image (arbitrary constant:
<= 265), so it's likely that most images will use most of the slots, so
it's likely there won't be unused slots. */
if (adapt_size > 2 && adapt_size < kch->n && kch->n <= 265
&& od->colormap_needs_transparency)
adapt_size--;
/* blending has bad effects when there are very few colors */
if (adapt_size < 4)
blend = 0;
/* 1. initialize min_dist and sort the colors in order of popularity. */
kcdiversity_init(&div, kch, od->dither_type != dither_none);
/* 2. choose colors one at a time */
for (nadapt = 0; nadapt < adapt_size; nadapt++) {
/* 2.1. choose the color to be added */
if (nadapt == 0 || (nadapt >= 10 && nadapt % 2 == 0))
/* 2.1a. want most popular unchosen color */
chosen = kcdiversity_find_popular(&div);
else if (od->dither_type == dither_none)
/* 2.1b. choose based on diversity from unchosen colors */
chosen = kcdiversity_find_diverse(&div, 0);
else {
/* 2.1c. choose based on diversity from unchosen colors, but allow
dithered combinations to stand in for colors, particularly early
on in the color finding process */
/* Weight assigned to dithered combinations drops as we proceed. */
#if HAVE_POW
double ditherweight = 0.05 + pow(0.25, 1 + (nadapt - 1) / 3.);
#else
double ditherweight = nadapt < 4 ? 0.25 : 0.125;
#endif
chosen = kcdiversity_find_diverse(&div, ditherweight);
}
kcdiversity_choose(&div, chosen,
od->dither_type != dither_none
&& nadapt > 0 && nadapt < 64);
}
/* 3. make the new palette by choosing one color from each slot. */
if (blend)
colormap_diversity_do_blend(&div);
for (nadapt = 0; nadapt != div.nchosen; ++nadapt)
gfcm->col[nadapt] = kc_togfcg(kch->h[div.chosen[nadapt]].ka.k);
gfcm->ncol = nadapt;
kcdiversity_cleanup(&div);
return gfcm;
}
Gif_Colormap* colormap_blend_diversity(kchist* kch, Gt_OutputData* od) {
return colormap_diversity(kch, od, 1);
}
Gif_Colormap* colormap_flat_diversity(kchist* kch, Gt_OutputData* od) {
return colormap_diversity(kch, od, 0);
}
void
colormap_image_posterize(Gif_Image *gfi, uint8_t *new_data,
Gif_Colormap *old_cm, kd3_tree* kd3,
uint32_t *histogram)
{
int ncol = old_cm->ncol;
Gif_Color *col = old_cm->col;
int map[256];
int i, j;
int transparent = gfi->transparent;
/* find closest colors in new colormap */
assert(old_cm->capacity >= 256);
for (i = 0; i < ncol; ++i) {
map[i] = col[i].pixel = kd3_closest8g(kd3, col[i].gfc_red, col[i].gfc_green, col[i].gfc_blue);
col[i].haspixel = 1;
}
for (i = ncol; i < 256; ++i) {
map[i] = col[i].pixel = 0;
col[i].haspixel = 1;
}
/* map image */
for (j = 0; j < gfi->height; j++) {
uint8_t *data = gfi->img[j];
for (i = 0; i < gfi->width; i++, data++, new_data++)
if (*data != transparent) {
*new_data = map[*data];
histogram[*new_data]++;
}
}
}
#define DITHER_SCALE 1024
#define DITHER_SHIFT 10
#define DITHER_SCALE_M1 (DITHER_SCALE-1)
#define DITHER_ITEM2ERR (1<<(DITHER_SHIFT-7))
#define N_RANDOM_VALUES 512
void
colormap_image_floyd_steinberg(Gif_Image *gfi, uint8_t *all_new_data,
Gif_Colormap *old_cm, kd3_tree* kd3,
uint32_t *histogram)
{
static int32_t *random_values = 0;
int width = gfi->width;
int dither_direction = 0;
int transparent = gfi->transparent;
int i, j, k;
kcolor *old_kc;
wkcolor *err, *err1;
/* Initialize distances; beware uninitialized colors */
assert(old_cm->capacity >= 256);
old_kc = Gif_NewArray(kcolor, old_cm->capacity);
for (i = 0; i < old_cm->ncol; ++i) {
Gif_Color* c = &old_cm->col[i];
old_kc[i] = kd3_makegfcg(kd3, c);
c->pixel = kd3_closest_transformed(kd3, old_kc[i], NULL);
c->haspixel = 1;
}
for (i = old_cm->ncol; i < 256; ++i) {
Gif_Color* c = &old_cm->col[i];
old_kc[i] = kd3_makegfcg(kd3, c);
c->pixel = 0;
c->haspixel = 1;
}
/* This code was written with reference to ppmquant by Jef Poskanzer, part
of the pbmplus package. */
/* Initialize Floyd-Steinberg error vectors to small random values, so we
don't get artifacts on the top row */
err = Gif_NewArray(wkcolor, width + 2);
err1 = Gif_NewArray(wkcolor, width + 2);
/* Use the same random values on each call in an attempt to minimize
"jumping dithering" effects on animations */
if (!random_values) {
random_values = Gif_NewArray(int32_t, N_RANDOM_VALUES);
for (i = 0; i < N_RANDOM_VALUES; i++)
random_values[i] = RANDOM() % (DITHER_SCALE_M1 * 2) - DITHER_SCALE_M1;
}
for (i = 0; i < gfi->width + 2; i++) {
j = (i + gfi->left) * 3;
for (k = 0; k < 3; ++k)
err[i].a[k] = random_values[ (j + k) % N_RANDOM_VALUES ];
}
/* err1 initialized below */
kd3_build_xradius(kd3);
/* Do the image! */
for (j = 0; j < gfi->height; j++) {
int d0, d1, d2, d3; /* used for error diffusion */
uint8_t *data, *new_data;
int x;
if (dither_direction) {
x = width - 1;
d0 = 0, d1 = 2, d2 = 1, d3 = 0;
} else {
x = 0;
d0 = 2, d1 = 0, d2 = 1, d3 = 2;
}
data = &gfi->img[j][x];
new_data = all_new_data + j * (unsigned) width + x;
for (i = 0; i < width + 2; i++)
err1[i].a[0] = err1[i].a[1] = err1[i].a[2] = 0;
/* Do a single row */
while (x >= 0 && x < width) {
int e;
kcolor use;
/* the transparent color never gets adjusted */
if (*data == transparent)
goto next;
/* find desired new color */
use = old_kc[*data];
/* use Floyd-Steinberg errors to adjust */
for (k = 0; k < 3; ++k) {
int v = use.a[k]
+ (err[x+1].a[k] & ~(DITHER_ITEM2ERR-1)) / DITHER_ITEM2ERR;
use.a[k] = KC_CLAMPV(v);
}
e = old_cm->col[*data].pixel;
if (kc_distance(kd3->ks[e], use) < kd3->xradius[e])
*new_data = e;
else
*new_data = kd3_closest_transformed(kd3, use, NULL);
histogram[*new_data]++;
/* calculate and propagate the error between desired and selected color.
Assume that, with a large scale (1024), we don't need to worry about
image artifacts caused by error accumulation (the fact that the
error terms might not sum to the error). */
for (k = 0; k < 3; ++k) {
e = (use.a[k] - kd3->ks[*new_data].a[k]) * DITHER_ITEM2ERR;
if (e) {
err [x+d0].a[k] += ((e * 7) & ~15) / 16;
err1[x+d1].a[k] += ((e * 3) & ~15) / 16;
err1[x+d2].a[k] += ((e * 5) & ~15) / 16;
err1[x+d3].a[k] += ( e & ~15) / 16;
}
}
next:
if (dither_direction)
x--, data--, new_data--;
else
x++, data++, new_data++;
}
/* Did a single row */
/* change dithering directions */
{
wkcolor *temp = err1;
err1 = err;
err = temp;
dither_direction = !dither_direction;
}
}
/* delete temporary storage */
Gif_DeleteArray(err);
Gif_DeleteArray(err1);
Gif_DeleteArray(old_kc);
}
/* This function is a variant of the colormap_image_floyd_steinberg function
since the Atkinson dither is a variant of the Floyd-Steinberg dither. */
void
colormap_image_atkinson(Gif_Image *gfi, uint8_t *all_new_data,
Gif_Colormap *old_cm, kd3_tree* kd3,
uint32_t *histogram)
{
static int32_t *random_values = 0;
int transparent = gfi->transparent;
int i, j, k;
kcolor *old_kc;
wkcolor *err[3];
/* Initialize distances; beware uninitialized colors */
assert(old_cm->capacity >= 256);
old_kc = Gif_NewArray(kcolor, old_cm->capacity);
for (i = 0; i < old_cm->ncol; ++i) {
Gif_Color* c = &old_cm->col[i];
old_kc[i] = kd3_makegfcg(kd3, c);
c->pixel = kd3_closest_transformed(kd3, old_kc[i], NULL);
c->haspixel = 1;
}
for (i = old_cm->ncol; i < 256; ++i) {
Gif_Color* c = &old_cm->col[i];
old_kc[i] = kd3_makegfcg(kd3, c);
c->pixel = 0;
c->haspixel = 1;
}
/* Initialize Atkinson error vectors */
for (i = 0; i < 3; i++)
err[i] = Gif_NewArray(wkcolor, gfi->width + 2);
/* Use the same random values on each call in an attempt to minimize
"jumping dithering" effects on animations */
if (!random_values) {
random_values = Gif_NewArray(int32_t, N_RANDOM_VALUES);
for (i = 0; i < N_RANDOM_VALUES; i++)
random_values[i] = RANDOM() % (DITHER_SCALE_M1 * 2) - DITHER_SCALE_M1;
}
for (i = 0; i < gfi->width + 2; i++) {
j = (i + gfi->left) * 3;
for (k = 0; k < 3; ++k)
err[0][i].a[k] = random_values[ (j + k) % N_RANDOM_VALUES ];
}
kd3_build_xradius(kd3);
/* Do the image! */
for (j = 0; j < gfi->height; j++) {
uint8_t *data = &gfi->img[j][0];
uint8_t *new_data = all_new_data + j * (unsigned) gfi->width;
/* Initialize error rows for this pass */
for (i = 0; i < gfi->width + 2; i++)
for (k = 0; k < 3; k++)
err[1][i].a[k] = err[2][i].a[k] = 0;
for (int x = 0; x < gfi->width; x++, data++, new_data++) {
int e;
kcolor use;
/* Transparent color never gets adjusted, skip */
if (*data == transparent) {
continue;
}
/* Calculate desired new color including current error */
use = old_kc[*data];
for (k = 0; k < 3; ++k)
use.a[k] = KC_CLAMPV(use.a[k] + err[0][x].a[k] / DITHER_SCALE);
/* Find the closest color in the colormap */
e = old_cm->col[*data].pixel;
if (kc_distance(kd3->ks[e], use) < kd3->xradius[e])
*new_data = e;
else
*new_data = kd3_closest_transformed(kd3, use, NULL);
histogram[*new_data]++;
/* Calculate and propagate the error using the Atkinson dithering
algorithm */
for (k = 0; k < 3; ++k) {
int e = (use.a[k] - kd3->ks[*new_data].a[k]) * DITHER_SCALE;
if (x + 1 < gfi->width) err[0][x + 1].a[k] += e / 8;
if (x + 2 < gfi->width) err[0][x + 2].a[k] += e / 8;
if (j + 1 < gfi->height) {
err[1][x].a[k] += e / 8;
err[1][x + 1].a[k] += e / 8;
if (x + 1 < gfi->width) err[1][x + 1].a[k] += e / 8;
}
if (j + 2 < gfi->height)
err[2][x].a[k] += e / 8;
}
}
/* Rotate error buffers */
wkcolor *temp = err[0];
err[0] = err[1];
err[1] = err[2];
err[2] = temp;
}
/* Delete temporary storage */
for (i = 0; i < 3; i++) {
Gif_DeleteArray(err[i]);
}
Gif_DeleteArray(old_kc);
}
typedef struct odselect_planitem {
uint8_t plan;
uint16_t frac;
} odselect_planitem;
static int* ordered_dither_lum;
static void plan_from_cplan(uint8_t* plan, int nplan,
const odselect_planitem* cp, int ncp, int whole) {
int i, cfrac_subt = 0, planpos = 0, end_planpos;
for (i = 0; i != ncp; ++i) {
cfrac_subt += cp[i].frac;
end_planpos = cfrac_subt * nplan / whole;
while (planpos != end_planpos)
plan[planpos++] = cp[i].plan;
}
assert(planpos == nplan);
}
static int ordered_dither_plan_compare(const void* xa, const void* xb) {
const uint8_t* a = (const uint8_t*) xa;
const uint8_t* b = (const uint8_t*) xb;
if (ordered_dither_lum[*a] != ordered_dither_lum[*b])
return ordered_dither_lum[*a] - ordered_dither_lum[*b];
else
return *a - *b;
}
static int kc_line_closest(kcolor p0, kcolor p1, kcolor ref,
double* t, unsigned* dist) {
wkcolor p01, p0ref;
kcolor online;
unsigned den;
int d;
for (d = 0; d != 3; ++d) {
p01.a[d] = p1.a[d] - p0.a[d];
p0ref.a[d] = ref.a[d] - p0.a[d];
}
den = (unsigned)
(p01.a[0]*p01.a[0] + p01.a[1]*p01.a[1] + p01.a[2]*p01.a[2]);
if (den == 0)
return 0;
/* NB: We've run out of bits of precision. We can calculate the
denominator in unsigned arithmetic, but the numerator might
be negative, or it might be so large that it is unsigned.
Calculate the numerator as a double. */
*t = ((double) p01.a[0]*p0ref.a[0] + p01.a[1]*p0ref.a[1]
+ p01.a[2]*p0ref.a[2]) / den;
if (*t < 0 || *t > 1)
return 0;
for (d = 0; d != 3; ++d) {
int v = (int) (p01.a[d] * *t) + p0.a[d];
online.a[d] = KC_CLAMPV(v);
}
*dist = kc_distance(online, ref);
return 1;
}
static int kc_plane_closest(kcolor p0, kcolor p1, kcolor p2, kcolor ref,
double* t, unsigned* dist) {
wkcolor p0ref, p01, p02;
double n[3], pvec[3], det, qvec[3], u, v;
int d;
/* Calculate the non-unit normal of the plane determined by the input
colors (p0-p2) */
for (d = 0; d != 3; ++d) {
p0ref.a[d] = ref.a[d] - p0.a[d];
p01.a[d] = p1.a[d] - p0.a[d];
p02.a[d] = p2.a[d] - p0.a[d];
}
n[0] = p01.a[1]*p02.a[2] - p01.a[2]*p02.a[1];
n[1] = p01.a[2]*p02.a[0] - p01.a[0]*p02.a[2];
n[2] = p01.a[0]*p02.a[1] - p01.a[1]*p02.a[0];
/* Moeller-Trumbore ray tracing algorithm: trace a ray from `ref` along
normal `n`; convert to barycentric coordinates to see if the ray
intersects with the triangle. */
pvec[0] = n[1]*p02.a[2] - n[2]*p02.a[1];
pvec[1] = n[2]*p02.a[0] - n[0]*p02.a[2];
pvec[2] = n[0]*p02.a[1] - n[1]*p02.a[0];
det = pvec[0]*p01.a[0] + pvec[1]*p01.a[1] + pvec[2]*p01.a[2];
if (fabs(det) <= 0.0001220703125) /* optimizer will take care of that */
return 0;
det = 1 / det;
u = (p0ref.a[0]*pvec[0] + p0ref.a[1]*pvec[1] + p0ref.a[2]*pvec[2]) * det;
if (u < 0 || u > 1)
return 0;
qvec[0] = p0ref.a[1]*p01.a[2] - p0ref.a[2]*p01.a[1];
qvec[1] = p0ref.a[2]*p01.a[0] - p0ref.a[0]*p01.a[2];
qvec[2] = p0ref.a[0]*p01.a[1] - p0ref.a[1]*p01.a[0];
v = (n[0]*qvec[0] + n[1]*qvec[1] + n[2]*qvec[2]) * det;
if (v < 0 || v > 1 || u + v > 1)
return 0;
/* Now we know at there is a point in the triangle that is closer to
`ref` than any point along its edges. Return the barycentric
coordinates for that point and the distance to that point. */
t[0] = u;
t[1] = v;
v = (p02.a[0]*qvec[0] + p02.a[1]*qvec[1] + p02.a[2]*qvec[2]) * det;
*dist = (unsigned) (v * v * (n[0]*n[0] + n[1]*n[1] + n[2]*n[2]) + 0.5);
return 1;
}
static void limit_ordered_dither_plan(uint8_t* plan, int nplan, int nc,
kcolor want, kd3_tree* kd3) {
unsigned mindist, dist;
int ncp = 0, nbestcp = 0, i, j, k;
double t[2];
odselect_planitem cp[256], bestcp[16];
nc = nc <= 16 ? nc : 16;
/* sort colors */
cp[0].plan = plan[0];
cp[0].frac = 1;
for (ncp = i = 1; i != nplan; ++i)
if (plan[i - 1] == plan[i])
++cp[ncp - 1].frac;
else {
cp[ncp].plan = plan[i];
cp[ncp].frac = 1;
++ncp;
}
/* calculate plan */
mindist = (unsigned) -1;
for (i = 0; i != ncp; ++i) {
/* check for closest single color */
dist = kc_distance(kd3->ks[cp[i].plan], want);
if (dist < mindist) {
bestcp[0].plan = cp[i].plan;
bestcp[0].frac = KC_WHOLE;
nbestcp = 1;
mindist = dist;
}
for (j = i + 1; nc >= 2 && j < ncp; ++j) {
/* check for closest blend of two colors */
if (kc_line_closest(kd3->ks[cp[i].plan],
kd3->ks[cp[j].plan],
want, &t[0], &dist)
&& dist < mindist) {
bestcp[0].plan = cp[i].plan;
bestcp[1].plan = cp[j].plan;
bestcp[1].frac = (int) (KC_WHOLE * t[0]);
bestcp[0].frac = KC_WHOLE - bestcp[1].frac;
nbestcp = 2;
mindist = dist;
}
for (k = j + 1; nc >= 3 && k < ncp; ++k)
/* check for closest blend of three colors */
if (kc_plane_closest(kd3->ks[cp[i].plan],
kd3->ks[cp[j].plan],
kd3->ks[cp[k].plan],
want, &t[0], &dist)
&& dist < mindist) {
bestcp[0].plan = cp[i].plan;
bestcp[1].plan = cp[j].plan;
bestcp[1].frac = (int) (KC_WHOLE * t[0]);
bestcp[2].plan = cp[k].plan;
bestcp[2].frac = (int) (KC_WHOLE * t[1]);
bestcp[0].frac = KC_WHOLE - bestcp[1].frac - bestcp[2].frac;
nbestcp = 3;
mindist = dist;
}
}
}
plan_from_cplan(plan, nplan, bestcp, nbestcp, KC_WHOLE);
}
static void set_ordered_dither_plan(uint8_t* plan, int nplan, int nc,
Gif_Color* gfc, kd3_tree* kd3) {
kcolor want, cur;
wkcolor err = wkc_zero();
int i, d;
want = kd3_makegfcg(kd3, gfc);
for (i = 0; i != nplan; ++i) {
for (d = 0; d != 3; ++d) {
int v = want.a[d] + err.a[d];
cur.a[d] = KC_CLAMPV(v);
}
plan[i] = kd3_closest_transformed(kd3, cur, NULL);
for (d = 0; d != 3; ++d)
err.a[d] += want.a[d] - kd3->ks[plan[i]].a[d];
}
qsort(plan, nplan, 1, ordered_dither_plan_compare);
if (nc < nplan && plan[0] != plan[nplan-1]) {
int ncp = 1;
for (i = 1; i != nplan; ++i)
ncp += plan[i-1] != plan[i];
if (ncp > nc)
limit_ordered_dither_plan(plan, nplan, nc, want, kd3);
}
gfc->haspixel = 1;
}
static void pow2_ordered_dither(Gif_Image* gfi, uint8_t* all_new_data,
Gif_Colormap* old_cm, kd3_tree* kd3,
uint32_t* histogram, const uint8_t* matrix,
uint8_t* plan) {
int mws, nplans, i, x, y;
for (mws = 0; (1 << mws) != matrix[0]; ++mws)
/* nada */;
for (nplans = 0; (1 << nplans) != matrix[2]; ++nplans)
/* nada */;
for (y = 0; y != gfi->height; ++y) {
uint8_t *data, *new_data, *thisplan;
data = gfi->img[y];
new_data = all_new_data + y * (unsigned) gfi->width;
for (x = 0; x != gfi->width; ++x)
/* the transparent color never gets adjusted */
if (data[x] != gfi->transparent) {
thisplan = &plan[data[x] << nplans];
if (!old_cm->col[data[x]].haspixel)
set_ordered_dither_plan(thisplan, 1 << nplans, matrix[3],
&old_cm->col[data[x]], kd3);
i = matrix[4 + ((x + gfi->left) & (matrix[0] - 1))
+ (((y + gfi->top) & (matrix[1] - 1)) << mws)];
new_data[x] = thisplan[i];
histogram[new_data[x]]++;
}
}
}
static void colormap_image_ordered(Gif_Image* gfi, uint8_t* all_new_data,
Gif_Colormap* old_cm, kd3_tree* kd3,
uint32_t* histogram,
const uint8_t* matrix) {
int mw = matrix[0], mh = matrix[1], nplan = matrix[2];
uint8_t* plan = Gif_NewArray(uint8_t, nplan * old_cm->ncol);
int i, x, y;
/* Written with reference to Joel Ylilouma's versions. */
/* Initialize colors */
assert(old_cm->capacity >= 256);
for (i = 0; i != 256; ++i)
old_cm->col[i].haspixel = 0;
/* Initialize luminances, create luminance sorter */
ordered_dither_lum = Gif_NewArray(int, kd3->nitems);
for (i = 0; i != kd3->nitems; ++i)
ordered_dither_lum[i] = kc_luminance(kd3->ks[i]);
/* Do the image! */
if ((mw & (mw - 1)) == 0 && (mh & (mh - 1)) == 0
&& (nplan & (nplan - 1)) == 0)
pow2_ordered_dither(gfi, all_new_data, old_cm, kd3, histogram,
matrix, plan);
else
for (y = 0; y != gfi->height; ++y) {
uint8_t *data, *new_data, *thisplan;
data = gfi->img[y];
new_data = all_new_data + y * (unsigned) gfi->width;
for (x = 0; x != gfi->width; ++x)
/* the transparent color never gets adjusted */
if (data[x] != gfi->transparent) {
thisplan = &plan[nplan * data[x]];
if (!old_cm->col[data[x]].haspixel)
set_ordered_dither_plan(thisplan, nplan, matrix[3],
&old_cm->col[data[x]], kd3);
i = matrix[4 + (x + gfi->left) % mw
+ ((y + gfi->top) % mh) * mw];
new_data[x] = thisplan[i];
histogram[new_data[x]]++;
}
}
/* delete temporary storage */
Gif_DeleteArray(ordered_dither_lum);
Gif_DeleteArray(plan);
}
static void dither(Gif_Image* gfi, uint8_t* new_data, Gif_Colormap* old_cm,
kd3_tree* kd3, uint32_t* histogram, Gt_OutputData* od) {
if (od->dither_type == dither_default
|| od->dither_type == dither_floyd_steinberg)
colormap_image_floyd_steinberg(gfi, new_data, old_cm, kd3, histogram);
else if (od->dither_type == dither_ordered
|| od->dither_type == dither_ordered_new)
colormap_image_ordered(gfi, new_data, old_cm, kd3, histogram,
od->dither_data);
else if (od->dither_type == dither_atkinson)
colormap_image_atkinson(gfi, new_data, old_cm, kd3, histogram);
else
colormap_image_posterize(gfi, new_data, old_cm, kd3, histogram);
}
/* return value 1 means run the dither again */
static int
try_assign_transparency(Gif_Image *gfi, Gif_Colormap *old_cm, uint8_t *new_data,
Gif_Colormap *new_cm, int *new_ncol,
kd3_tree* kd3, uint32_t *histogram)
{
uint32_t min_used;
int i, j;
int transparent = gfi->transparent;
int new_transparent = -1;
Gif_Color transp_value;
if (transparent < 0)
return 0;
if (old_cm)
transp_value = old_cm->col[transparent];
else
GIF_SETCOLOR(&transp_value, 0, 0, 0);
/* look for an unused pixel in the existing colormap; prefer the same color
we had */
for (i = 0; i < *new_ncol; i++)
if (histogram[i] == 0 && GIF_COLOREQ(&transp_value, &new_cm->col[i])) {
new_transparent = i;
goto found;
}
for (i = 0; i < *new_ncol; i++)
if (histogram[i] == 0) {
new_transparent = i;
goto found;
}
/* try to expand the colormap */
if (*new_ncol < 256) {
assert(*new_ncol < new_cm->capacity);
new_transparent = *new_ncol;
new_cm->col[new_transparent] = transp_value;
(*new_ncol)++;
goto found;