forked from kornelski/pngquant
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpngquant.c
1732 lines (1494 loc) · 56.1 KB
/
pngquant.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
/* pngquant.c - quantize the colors in an alphamap down to a specified number
**
** Copyright (C) 1989, 1991 by Jef Poskanzer.
** Copyright (C) 1997, 2000, 2002 by Greg Roelofs; based on an idea by
** Stefan Schneider.
** Copyright (C) 2009 by Kornel Lesinski.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation. This software is provided "as is" without express or
** implied warranty.
*/
/* GRR TO DO: set sBIT flag appropriately for maxval-scaled images */
/* GRR TO DO: "original file size" and "quantized file size" if verbose? */
/* GRR TO DO: add option to preserve background color (if any) exactly */
/* GRR TO DO: add mapfile support, but cleanly (build palette in main()) */
/* GRR TO DO: default to 256 colors if number not specified on command line */
/* GRR TO DO: support 16 bps without down-conversion */
/* GRR TO DO: replace PBMPLUS mem-management routines? */
/* GRR TO DO: if all samples are gray and image is opaque and sample depth
would be no bigger than palette and user didn't explicitly
specify a mapfile, switch to grayscale */
/* GRR TO DO: if all samples are 0 or maxval, eliminate gAMA chunk (rwpng.c) */
#define PNGQUANT_VERSION "1.1.3 of February 2009"
#define PNGQUANT_USAGE "\
usage: pngquant [options] [ncolors] [pngfile [pngfile ...]]\n\
[options] -map mapfile [pngfile [pngfile ...]]\n\
options:\n\
-force overwrite existing output files\n\
-ext new.png set custom extension for output filename\n\
-nofs disable dithering (synonyms: -nofloyd, -ordered)\n\
-verbose print status messages (synonyms: -noquiet)\n\
-iebug increase opacity to work around Internet Explorer 6 bug\n\
\n\
Quantizes one or more 32-bit RGBA PNGs to 8-bit (or smaller) RGBA-palette\n\
PNGs using Floyd-Steinberg diffusion dithering (unless disabled).\n\
The output filename is the same as the input name except that\n\
it ends in \"-fs8.png\", \"-or8.png\" or your custom extension (unless the\n\
input is stdin, in which case the quantized image will go to stdout).\n\
The default behavior if the output file exists is to skip the conversion;\n\
use -force to overwrite.\n\
NOTE: the -map option is NOT YET SUPPORTED.\n"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef unix
# include <unistd.h> /* getpid() */
#endif
#ifdef WIN32 /* defined in Makefile.w32 (or use _MSC_VER for MSVC) */
# include <fcntl.h> /* O_BINARY */
# include <io.h> /* setmode() */
# include <process.h> /* _getpid() */
# ifndef getpid
# define getpid _getpid
# endif
# ifndef srandom
# define srandom srand
# endif
# ifndef random
# define random rand
# endif
#endif
#include <math.h>
#include "png.h" /* libpng header; includes zlib.h */
#include "rwpng.h" /* typedefs, common macros, public prototypes */
typedef uch pixval; /* GRR: hardcoded for now; later add 16-bit support */
/* from pam.h */
typedef struct {
uch r, g, b, a;
} apixel;
/*
typedef struct {
ush r, g, b, a;
} apixel16;
*/
#define pam_freearray(pixels,rows) pm_freearray((char **)pixels, rows)
#define PAM_GETR(p) ((p).r)
#define PAM_GETG(p) ((p).g)
#define PAM_GETB(p) ((p).b)
#define PAM_GETA(p) ((p).a)
#define PAM_SETA(p,v) ((p).a = (v))
#define PAM_ASSIGN(p,red,grn,blu,alf) \
do { (p).r = (red); (p).g = (grn); (p).b = (blu); (p).a = (alf); } while (0)
#define PAM_EQUAL(p,q) \
((p).r == (q).r && (p).g == (q).g && (p).b == (q).b && (p).a == (q).a)
#define PAM_DEPTH(newp,p,oldmaxval,newmaxval) \
PAM_ASSIGN( (newp), \
( (int) PAM_GETR(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval), \
( (int) PAM_GETG(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval), \
( (int) PAM_GETB(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval), \
( (int) PAM_GETA(p) * (newmaxval) + (oldmaxval) / 2 ) / (oldmaxval) )
/* from pamcmap.h */
typedef struct acolorhist_item *acolorhist_vector;
struct acolorhist_item {
apixel acolor;
int value;
int contrast;
};
typedef struct acolorhist_list_item *acolorhist_list;
struct acolorhist_list_item {
struct acolorhist_item ch;
acolorhist_list next;
};
typedef acolorhist_list *acolorhash_table;
static mainprog_info rwpng_info;
#define FNMAX 1024 /* max filename length */
#define MAXCOLORS (32767*8)
#define FS_SCALE 4096 /* Floyd-Steinberg scaling factor */
#define LARGE_NORM
/* #define LARGE_LUM */ /* GRR 19970727: this isn't well-defined for RGBA */
/* #define REP_CENTER_BOX */
/* #define REP_AVERAGE_COLORS */
#define REP_AVERAGE_PIXELS
typedef struct box *box_vector;
struct box {
int ind;
int colors;
int sum;
};
#ifdef SUPPORT_MAPFILE
static int pngquant
(char *filename, char *newext, int floyd, int force, int verbose,
int using_stdin, int reqcolors, apixel **mapapixels, ulg maprows,
ulg mapcols, pixval mapmaxval, int ie_bug);
#else
static int pngquant
(char *filename, char *newext, int floyd, int force, int verbose,
int using_stdin, int reqcolors, apixel **mapapixels, int ie_bug);
#endif
static acolorhist_vector mediancut
(acolorhist_vector achv, int colors, int sum, pixval maxval, pixval min_opaque_val, int newcolors);
static int redcompare (const void *ch1, const void *ch2);
static int greencompare (const void *ch1, const void *ch2);
static int bluecompare (const void *ch1, const void *ch2);
static int alphacompare (const void *ch1, const void *ch2);
static int sumcompare (const void *b1, const void *b2);
static int colorimportance(int alpha);
static acolorhist_vector pam_acolorhashtoacolorhist
(acolorhash_table acht, int maxacolors);
static acolorhist_vector pam_computeacolorhist
(apixel **apixels, int cols, int rows, int maxacolors, int* acolorsP);
static acolorhash_table pam_computeacolorhash
(apixel** apixels, int cols, int rows, int maxacolors, int* acolorsP);
static acolorhash_table pam_allocacolorhash (void);
static int pam_addtoacolorhash
(acolorhash_table acht, apixel *acolorP, int value);
static int pam_lookupacolor (acolorhash_table acht, apixel* acolorP);
static void pam_freeacolorhist (acolorhist_vector achv);
static void pam_freeacolorhash (acolorhash_table acht);
static char *pm_allocrow (int cols, int size);
#ifdef SUPPORT_MAPFILE
static void pm_freearray (char **its, int rows);
#endif
static void averagepixels(int indx, int clrs, apixel *pixel, acolorhist_vector achv, pixval maxval, pixval min_opaque_val);
int
main( argc, argv )
int argc;
char *argv[];
{
#ifdef SUPPORT_MAPFILE
FILE *infile;
ulg maprows, mapcols;
pixval mapmaxval;
#endif
apixel **mapapixels;
int argn;
int reqcolors;
int floyd = TRUE;
int force = FALSE;
int ie_bug = FALSE;
int verbose = FALSE;
int using_stdin = FALSE;
int latest_error=0, error_count=0, file_count=0;
char *filename, *newext = NULL;
char *pq_usage = PNGQUANT_USAGE;
#ifdef __EMX__
_wildcard(&argc, &argv); /* Unix-like globbing for OS/2 and DOS */
#endif
argn = 1;
mapapixels = (apixel **)0;
while ( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' ) {
if ( 0 == strcmp( argv[argn], "--" ) ) { ++argn;break; }
if ( 0 == strncmp( argv[argn], "-fs", 3 ) ||
0 == strncmp( argv[argn], "-floyd", 3 ) )
floyd = TRUE;
else if ( 0 == strncmp( argv[argn], "-nofs", 5 ) ||
0 == strncmp( argv[argn], "-nofloyd", 5 ) ||
0 == strncmp( argv[argn], "-ordered", 3 ) )
floyd = FALSE;
else if ( 0 == strcmp( argv[argn], "-iebug" ) )
ie_bug = TRUE;
else if ( 0 == strncmp( argv[argn], "-force", 2 ) )
force = TRUE;
else if ( 0 == strncmp( argv[argn], "-noforce", 4 ) )
force = FALSE;
else if ( 0 == strncmp( argv[argn], "-verbose", 2 ) ||
0 == strncmp( argv[argn], "-noquiet", 4 ) )
verbose = TRUE;
else if ( 0 == strncmp( argv[argn], "-noverbose", 4 ) ||
0 == strncmp( argv[argn], "-quiet", 2 ) )
verbose = FALSE;
else if ( 0 == strcmp( argv[argn], "-ext" ) ) {
++argn;
if ( argn == argc ) {
fprintf( stderr, pq_usage );
fflush( stderr );
return 1;
}
newext = argv[argn];
}
#ifdef SUPPORT_MAPFILE
else if ( 0 == strcmp( argv[argn], "-map" ) ) {
++argn;
if ( argn == argc ) {
fprintf( stderr, pq_usage );
fflush( stderr );
return 1;
}
if ((infile = fopen( argv[argn], "rb" )) == NULL) {
fprintf(stderr, "cannot open mapfile %s for reading\n",
argv[argn]);
fflush( stderr );
return 2;
}
mapapixels = pam_readpam( infile, &mapcols, &maprows, &mapmaxval );
fclose(infile);
if ( mapcols == 0 || maprows == 0 ) {
fputs( "null colormap??\n", stderr );
fflush( stderr );
return 3;
}
}
/* GRR TO DO: really want to build entire mapfile palette right here and
pass that (and *only* that) to pngquant()
*/
#endif /* SUPPORT_MAPFILE */
else {
fprintf(stderr, "pngquant, version %s, by Greg Roelofs, Kornel Lesinski.\n",
PNGQUANT_VERSION);
rwpng_version_info();
fputs( "\n", stderr );
fputs( pq_usage, stderr );
fflush( stderr );
return 1;
}
++argn;
}
if ( mapapixels == (apixel**) 0 ) {
if ( argn == argc ) {
fprintf( stderr, "pngquant, version %s, by Greg Roelofs, Kornel Lesinski.\n",
PNGQUANT_VERSION );
rwpng_version_info();
fputs( "\n", stderr );
fputs( pq_usage, stderr );
fflush( stderr );
return 1;
}
if ( sscanf( argv[argn], "%d", &reqcolors ) != 1 ) {
reqcolors = 256; argn--;
}
if ( reqcolors <= 1 ) {
fputs( "number of colors must be greater than 1\n", stderr );
fflush( stderr );
return 4;
}
if ( reqcolors > 256 ) {
fputs( "number of colors cannot be more than 256\n", stderr );
fflush( stderr );
return 4;
}
++argn;
}
if (newext == NULL)
{
newext = floyd? "-ie-fs8.png" : "-ie-or8.png";
if (!ie_bug) newext += 3; /* skip "-ie" */
}
if ( argn == argc || 0==strcmp(argv[argn],"-")) {
using_stdin = TRUE;
filename = "stdin";
} else {
filename = argv[argn];
++argn;
}
/*============================= MAIN LOOP =============================*/
while (argn <= argc) {
int retval;
if (verbose) {
fprintf(stderr, "%s:\n", filename);
fflush(stderr);
}
#ifdef SUPPORT_MAPFILE
retval = pngquant(filename, newext, floyd, force, verbose, using_stdin,
reqcolors, mapapixels, maprows, mapcols, mapmaxval, ie_bug);
#else
retval = pngquant(filename, newext, floyd, force, verbose, using_stdin,
reqcolors, mapapixels, ie_bug);
#endif
if (retval) {
latest_error = retval;
++error_count;
}
++file_count;
if (verbose) {
fprintf(stderr, "\n");
fflush(stderr);
}
filename = argv[argn];
++argn;
}
/*=======================================================================*/
if (verbose) {
if (error_count)
fprintf(stderr, "There were errors quantizing %d file%s out of a"
" total of %d file%s.\n",
error_count, (error_count == 1)? "" : "s",
file_count, (file_count == 1)? "" : "s");
else
fprintf(stderr, "No errors detected while quantizing %d image%s.\n",
file_count, (file_count == 1)? "" : "s");
fflush(stderr);
}
return latest_error;
}
#ifdef SUPPORT_MAPFILE
int
pngquant(filename, newext, floyd, force, verbose, using_stdin, reqcolors,
mapapixels, maprows, mapcols, mapmaxval, ie_bug)
char *filename, *newext;
int floyd, force, verbose, using_stdin, reqcolors, ie_bug;
apixel **mapapixels;
ulg maprows, mapcols;
pixval mapmaxval;
#else
int
pngquant(filename, newext, floyd, force, verbose, using_stdin, reqcolors,
mapapixels, ie_bug)
char *filename, *newext;
int floyd, force, verbose, using_stdin, reqcolors, ie_bug;
apixel **mapapixels;
#endif
{
FILE *infile, *outfile;
apixel **apixels;
apixel *pP;
int col, limitcol;
int ind;
uch *pQ, *outrow, **row_pointers=NULL;
ulg rows, cols;
pixval maxval, newmaxval, min_opaque_val, almost_opaque_val;
acolorhist_vector achv, acolormap=NULL;
acolorhash_table acht;
long *thisrerr = NULL;
long *nextrerr = NULL;
long *thisgerr = NULL;
long *nextgerr = NULL;
long *thisberr = NULL;
long *nextberr = NULL;
long *thisaerr = NULL;
long *nextaerr = NULL;
long *temperr;
long sr=0, sg=0, sb=0, sa=0, err;
int row;
int colors;
int newcolors = 0;
int usehash;
int fs_direction = 0;
int x;
/* int channels; */
int bot_idx, top_idx;
int remap[256];
char outname[FNMAX];
/* can't do much if we don't have an input file...but don't reopen stdin */
if (using_stdin) {
#if defined(MSDOS) || defined(FLEXOS) || defined(OS2) || defined(WIN32)
#if (defined(__HIGHC__) && !defined(FLEXOS))
setmode(stdin, _BINARY);
#else
setmode(0, O_BINARY);
#endif
#endif
/* GRR: Reportedly "some buggy C libraries require BOTH the setmode()
* call AND fdopen() in binary mode," but it's not clear which
* ones or that any of them are still in use as of 2000. Until
* someone reports a specific problem, we're skipping the fdopen
* part... */
infile = stdin;
} else if ((infile = fopen(filename, "rb")) == NULL) {
fprintf(stderr, " error: cannot open %s for reading\n", filename);
fflush(stderr);
return 2;
}
/* build the output filename from the input name by inserting "-fs8" or
* "-or8" before the ".png" extension (or by appending that plus ".png" if
* there isn't any extension), then make sure it doesn't exist already */
if (using_stdin) {
#if defined(MSDOS) || defined(FLEXOS) || defined(OS2) || defined(WIN32)
#if (defined(__HIGHC__) && !defined(FLEXOS))
setmode(stdout, _BINARY);
#else
setmode(1, O_BINARY);
#endif
#endif
outfile = stdout; /* GRR: see comment above about fdopen() */
} else {
x = strlen(filename);
if (x > FNMAX-strlen(newext)-1) {
fprintf(stderr,
" warning: base filename [%s] will be truncated\n", filename);
fflush(stderr);
x = FNMAX-strlen(newext)-1;
}
strncpy(outname, filename, x);
if (strncmp(outname+x-4, ".png", 4) == 0)
strcpy(outname+x-4, newext);
else
strcpy(outname+x, newext);
if (!force) {
if ((outfile = fopen(outname, "rb")) != NULL) {
fprintf(stderr, " error: %s exists; not overwriting\n",
outname);
fflush(stderr);
fclose(outfile);
return 15;
}
}
if ((outfile = fopen(outname, "wb")) == NULL) {
fprintf(stderr, " error: cannot open %s for writing\n", outname);
fflush(stderr);
return 16;
}
}
/*
** Step 1: read in the alpha-channel image.
*/
/* GRR: returns RGBA (4 channels), 8 bps */
rwpng_read_image(infile, &rwpng_info);
if (!using_stdin)
fclose(infile);
if (rwpng_info.retval) {
fprintf(stderr, " rwpng_read_image() error\n");
fflush(stderr);
if (!using_stdin)
fclose(outfile);
return rwpng_info.retval;
}
/* NOTE: rgba_data and row_pointers are allocated but not freed in
* rwpng_read_image() */
apixels = (apixel **)rwpng_info.row_pointers;
cols = rwpng_info.width;
rows = rwpng_info.height;
/* channels = rwpng_info.channels; */
maxval = 255; /* GRR TO DO: allow either 8 or 16 bps */
/* IE6 makes colors with even slightest transparency completely transparent,
thus to improve situation in IE, make colors that are less than ~10% transparent
completely opaque */
if (ie_bug)
{
min_opaque_val = maxval * 15 / 16; /* rest of the code uses min_opaque_val rather than checking for ie_bug */
almost_opaque_val = min_opaque_val * 2 / 3;
if (verbose) {
fprintf(stderr, " Working around IE6 bug by making image less transparent...\n");
fflush(stderr);
}
}
else
{
min_opaque_val = almost_opaque_val = maxval;
}
for ( row = 0; (ulg)row < rows; ++row )
for ( col = 0, pP = apixels[row]; (ulg)col < cols; ++col, ++pP )
{
/* set all completely transparent colors to black */
if (!PAM_GETA(*pP))
{
PAM_ASSIGN(*pP,0,0,0,PAM_GETA(*pP));
}
/* ie bug: to avoid visible step caused by forced opaqueness, linearily raise opaqueness of almost-opaque colors */
else if (PAM_GETA(*pP) < maxval && PAM_GETA(*pP) > almost_opaque_val)
{
int al = almost_opaque_val + (PAM_GETA(*pP)-almost_opaque_val) * (maxval-almost_opaque_val) / (min_opaque_val-almost_opaque_val);
if (al > maxval) al = maxval;
PAM_SETA(*pP,al);
}
}
/* ie bug: despite increased opaqueness in the picture, color reduction could still produce
non-opaque colors. to prevent that, set a treshold (it'll be used when remapping too) */
if (min_opaque_val != maxval)
{
min_opaque_val = maxval*15/16;
}
if ( mapapixels == (apixel**) 0 ) {
/*
** Step 2: attempt to make a histogram of the colors, unclustered.
** If at first we don't succeed, lower maxval to increase color
** coherence and try again. This will eventually terminate, with
** maxval at worst 15, since 32^3 is approximately MAXCOLORS.
[GRR POSSIBLE BUG: what about 32^4 ?]
*/
for ( ; ; ) {
if (verbose) {
fprintf(stderr, " making histogram...");
fflush(stderr);
}
achv = pam_computeacolorhist(
apixels, cols, rows, MAXCOLORS, &colors );
if ( achv != (acolorhist_vector) 0 )
break;
newmaxval = maxval / 2;
min_opaque_val /= 2;
if (verbose) {
fprintf(stderr, "too many colors!\n");
fprintf(stderr, " scaling colors from maxval=%d to maxval=%d"
" to improve clustering...\n", maxval, newmaxval);
fflush(stderr);
}
for ( row = 0; (ulg)row < rows; ++row )
for ( col = 0, pP = apixels[row]; (ulg)col < cols; ++col, ++pP )
PAM_DEPTH( *pP, *pP, maxval, newmaxval );
maxval = newmaxval;
}
if (verbose) {
fprintf(stderr, "%d colors found\n", colors);
fflush(stderr);
}
newcolors = MIN(colors, reqcolors);
/*
** Step 3: apply median-cut to histogram, making the new acolormap.
*/
if (verbose && colors > reqcolors) {
fprintf(stderr, " choosing %d colors...\n", newcolors);
fflush(stderr);
}
acolormap = mediancut(achv, colors, rows * cols, maxval, min_opaque_val, newcolors);
pam_freeacolorhist(achv);
}
#ifdef SUPPORT_MAPFILE
else {
/*
** Reverse steps 2 & 3 : Turn mapapixels into an acolormap.
*/
if (mapmaxval != maxval) {
if (mapmaxval > maxval) {
fprintf(stderr, " rescaling colormap colors\n");
fflush(stderr);
}
for (row = 0; row < maprows; ++row)
for (col = 0, pP = mapapixels[row]; col < mapcols; ++col, ++pP)
PAM_DEPTH(*pP, *pP, mapmaxval, maxval);
mapmaxval = maxval;
}
acolormap = pam_computeacolorhist(
mapapixels, mapcols, maprows, MAXCOLORS, &newcolors );
if ( acolormap == (acolorhist_vector) 0 ) {
fprintf( stderr, " too many colors in acolormap!\n" );
fflush(stderr);
if (rwpng_info.row_pointers)
free(rwpng_info.row_pointers);
if (rwpng_info.rgba_data)
free(rwpng_info.rgba_data);
if (!using_stdin)
fclose(outfile);
return 5;
}
pam_freearray( mapapixels, maprows );
if (verbose) {
fprintf(stderr, " %d colors found in acolormap\n", newcolors);
fflush(stderr);
/* GRR TO DO: eliminate unused colors from mapfile */
}
}
#endif /* SUPPORT_MAPFILE */
/*
** Step 3.4 [GRR]: set the bit-depth appropriately, given the actual
** number of colors that will be used in the output image.
*/
if (newcolors <= 2)
rwpng_info.sample_depth = 1;
else if (newcolors <= 4)
rwpng_info.sample_depth = 2;
else if (newcolors <= 16)
rwpng_info.sample_depth = 4;
else
rwpng_info.sample_depth = 8;
if (verbose) {
fprintf(stderr, " writing %d-bit colormapped image\n",
rwpng_info.sample_depth);
fflush(stderr);
}
/*
** Step 3.5 [GRR]: remap the palette colors so that all entries with
** the maximal alpha value (i.e., fully opaque) are at the end and can
** therefore be omitted from the tRNS chunk. Note that the ordering of
** opaque entries is reversed from how Step 3 arranged them--not that
** this should matter to anyone.
*/
if (verbose) {
fprintf(stderr,
" remapping colormap to eliminate opaque tRNS-chunk entries...");
fflush(stderr);
}
for (top_idx = newcolors-1, bot_idx = x = 0; x < newcolors; ++x) {
if (PAM_GETA(acolormap[x].acolor) == maxval)
remap[x] = top_idx--;
else
remap[x] = bot_idx++;
}
if (verbose) {
fprintf(stderr, "%d entr%s left\n", bot_idx,
(bot_idx == 1)? "y" : "ies");
fflush(stderr);
}
/* sanity check: top and bottom indices should have just crossed paths */
if (bot_idx != top_idx + 1) {
fprintf(stderr,
" internal logic error: remapped bot_idx = %d, top_idx = %d\n",
bot_idx, top_idx);
fflush(stderr);
if (rwpng_info.row_pointers)
free(rwpng_info.row_pointers);
if (rwpng_info.rgba_data)
free(rwpng_info.rgba_data);
if (!using_stdin)
fclose(outfile);
return 18;
}
rwpng_info.num_palette = newcolors;
rwpng_info.num_trans = bot_idx;
/* GRR TO DO: if bot_idx == 0, check whether all RGB samples are gray
and if so, whether grayscale sample_depth would be same
=> skip following palette section and go grayscale */
/*
** Step 3.6 [GRR]: rescale the palette colors to a maxval of 255, as
** required by the PNG spec. (Technically, the actual remapping happens
** in here, too.)
*/
if (maxval < 255) {
if (verbose) {
fprintf(stderr,
" rescaling colormap colors from maxval=%d to maxval=255\n",
maxval);
fflush(stderr);
}
for (x = 0; x < newcolors; ++x) {
/* the rescaling part of this is really just PAM_DEPTH() broken out
* for the PNG palette; the trans-remapping just puts the values
* in different slots in the PNG palette */
rwpng_info.palette[remap[x]].red
= (PAM_GETR(acolormap[x].acolor)*255 + (maxval >> 1)) / maxval;
rwpng_info.palette[remap[x]].green
= (PAM_GETG(acolormap[x].acolor)*255 + (maxval >> 1)) / maxval;
rwpng_info.palette[remap[x]].blue
= (PAM_GETB(acolormap[x].acolor)*255 + (maxval >> 1)) / maxval;
rwpng_info.trans[remap[x]]
= (PAM_GETA(acolormap[x].acolor)*255 + (maxval >> 1)) / maxval;
}
/* GRR TO DO: set sBIT flag appropriately */
} else {
for (x = 0; x < newcolors; ++x) {
rwpng_info.palette[remap[x]].red
= PAM_GETR( acolormap[x].acolor );
rwpng_info.palette[remap[x]].green
= PAM_GETG( acolormap[x].acolor );
rwpng_info.palette[remap[x]].blue
= PAM_GETB( acolormap[x].acolor );
rwpng_info.trans[remap[x]]
= PAM_GETA( acolormap[x].acolor );
}
}
/*
** Step 3.7 [GRR]: allocate memory for either a single row (non-
** interlaced -> progressive write) or the entire indexed image
** (interlaced -> all at once); note that rwpng_info.row_pointers
** is still in use via apixels (INPUT data).
*/
if (rwpng_info.interlaced) {
if ((rwpng_info.indexed_data = (uch *)malloc(rows * cols)) != NULL) {
if ((row_pointers = (uch **)malloc(rows * sizeof(uch *))) != NULL) {
for (row = 0; (ulg)row < rows; ++row)
row_pointers[row] = rwpng_info.indexed_data + row*cols;
}
}
} else
rwpng_info.indexed_data = (uch *)malloc(cols);
if (rwpng_info.indexed_data == NULL ||
(rwpng_info.interlaced && row_pointers == NULL))
{
fprintf(stderr,
" insufficient memory for indexed data and/or row pointers\n");
fflush(stderr);
if (rwpng_info.row_pointers)
free(rwpng_info.row_pointers);
if (rwpng_info.rgba_data)
free(rwpng_info.rgba_data);
if (rwpng_info.indexed_data)
free(rwpng_info.indexed_data);
if (!using_stdin)
fclose(outfile);
return 17;
}
/*
** Step 4: map the colors in the image to their closest match in the
** new colormap, and write 'em out.
*/
if (verbose) {
fprintf(stderr, " mapping image to new colors...\n" );
fflush(stderr);
}
acht = pam_allocacolorhash( );
usehash = 1;
if (rwpng_write_image_init(outfile, &rwpng_info) != 0) {
fprintf( stderr, " rwpng_write_image_init() error\n" );
fflush( stderr );
if (rwpng_info.rgba_data)
free(rwpng_info.rgba_data);
if (rwpng_info.row_pointers)
free(rwpng_info.row_pointers);
if (rwpng_info.indexed_data)
free(rwpng_info.indexed_data);
if (row_pointers)
free(row_pointers);
if (!using_stdin)
fclose(outfile);
return rwpng_info.retval;
}
if ( floyd ) {
/* Initialize Floyd-Steinberg error vectors. */
thisrerr = (long*) pm_allocrow( cols + 2, sizeof(long) );
nextrerr = (long*) pm_allocrow( cols + 2, sizeof(long) );
thisgerr = (long*) pm_allocrow( cols + 2, sizeof(long) );
nextgerr = (long*) pm_allocrow( cols + 2, sizeof(long) );
thisberr = (long*) pm_allocrow( cols + 2, sizeof(long) );
nextberr = (long*) pm_allocrow( cols + 2, sizeof(long) );
thisaerr = (long*) pm_allocrow( cols + 2, sizeof(long) );
nextaerr = (long*) pm_allocrow( cols + 2, sizeof(long) );
srandom( 12345 ); /** deterministic dithering is better for comparing results */
for ( col = 0; (ulg)col < cols + 2; ++col ) {
thisrerr[col] = random( ) % ( FS_SCALE * 2 ) - FS_SCALE;
thisgerr[col] = random( ) % ( FS_SCALE * 2 ) - FS_SCALE;
thisberr[col] = random( ) % ( FS_SCALE * 2 ) - FS_SCALE;
thisaerr[col] = random( ) % ( FS_SCALE * 2 ) - FS_SCALE;
/* (random errors in [-1 .. 1]) */
}
fs_direction = 1;
}
for ( row = 0; (ulg)row < rows; ++row ) {
outrow = rwpng_info.interlaced? row_pointers[row] :
rwpng_info.indexed_data;
if ( floyd )
for ( col = 0; (ulg)col < cols + 2; ++col )
nextrerr[col] = nextgerr[col] =
nextberr[col] = nextaerr[col] = 0;
if ( ( ! floyd ) || fs_direction ) {
col = 0;
limitcol = cols;
pP = apixels[row];
pQ = outrow;
} else {
col = cols - 1;
limitcol = -1;
pP = &(apixels[row][col]);
pQ = &(outrow[col]);
}
do {
if ( floyd ) {
/* Use Floyd-Steinberg errors to adjust actual color. */
sr = PAM_GETR(*pP) + thisrerr[col + 1] / FS_SCALE;
sg = PAM_GETG(*pP) + thisgerr[col + 1] / FS_SCALE;
sb = PAM_GETB(*pP) + thisberr[col + 1] / FS_SCALE;
sa = PAM_GETA(*pP) + thisaerr[col + 1] / FS_SCALE;
if ( sr < 0 ) sr = 0;
else if ( sr > maxval ) sr = maxval;
if ( sg < 0 ) sg = 0;
else if ( sg > maxval ) sg = maxval;
if ( sb < 0 ) sb = 0;
else if ( sb > maxval ) sb = maxval;
if ( sa < 0 ) sa = 0;
/* when fighting IE bug, dithering must not make opaque areas transparent */
else if ( sa > maxval || (ie_bug && PAM_GETA(*pP) == maxval)) sa = maxval;
/* GRR 20001228: added casts to quiet warnings; 255 DEPENDENCY */
PAM_ASSIGN( *pP, (uch)sr, (uch)sg, (uch)sb, (uch)sa );
}
/* Check hash table to see if we have already matched this color. */
ind = pam_lookupacolor( acht, pP );
int a1 = PAM_GETA( *pP );
int colorimp = colorimportance(a1);
if ( ind == -1 ) {
/* No; search acolormap for closest match. */
int i, r1, g1, b1, r2, g2, b2, a2;
long dist = 1<<30, newdist;
r1 = PAM_GETR( *pP );
g1 = PAM_GETG( *pP );
b1 = PAM_GETB( *pP );
/* a1 read few lines earlier */
for ( i = 0; i < newcolors; ++i ) {
r2 = PAM_GETR( acolormap[i].acolor );
g2 = PAM_GETG( acolormap[i].acolor );
b2 = PAM_GETB( acolormap[i].acolor );
a2 = PAM_GETA( acolormap[i].acolor );
/* GRR POSSIBLE BUG */
/* 8+1 shift is /256 for colorimportance and approx /3 for 3 channels vs 1 */
newdist = (( a1 - a2 ) * ( a1 - a2 ) << 8+1) +
(( r1 - r2 ) * ( r1 - r2 ) * colorimp +
( g1 - g2 ) * ( g1 - g2 ) * colorimp +
( b1 - b2 ) * ( b1 - b2 ) * colorimp);
/* penalty for making holes in IE */
if (a1 >= min_opaque_val && a2 < maxval) newdist += maxval*maxval/64;
if ( newdist < dist ) {
ind = i;
dist = newdist;
}
}
if ( usehash ) {
if ( pam_addtoacolorhash( acht, pP, ind ) < 0 ) {
if (verbose) {
fprintf(stderr, " out of memory adding to hash"
" table, proceeding without it\n");
fflush(stderr);
}
usehash = 0;
}
}
}
if ( floyd ) {
/* Propagate Floyd-Steinberg error terms. */
if ( fs_direction ) {
err = (sr - (long)PAM_GETR(acolormap[ind].acolor))*FS_SCALE * colorimp/256;
thisrerr[col + 2] += ( err * 7 ) / 16;
nextrerr[col ] += ( err * 3 ) / 16;
nextrerr[col + 1] += ( err * 5 ) / 16;
nextrerr[col + 2] += ( err ) / 16;
err = (sg - (long)PAM_GETG(acolormap[ind].acolor))*FS_SCALE * colorimp/256;
thisgerr[col + 2] += ( err * 7 ) / 16;
nextgerr[col ] += ( err * 3 ) / 16;
nextgerr[col + 1] += ( err * 5 ) / 16;
nextgerr[col + 2] += ( err ) / 16;
err = (sb - (long)PAM_GETB(acolormap[ind].acolor))*FS_SCALE * colorimp/256;
thisberr[col + 2] += ( err * 7 ) / 16;
nextberr[col ] += ( err * 3 ) / 16;
nextberr[col + 1] += ( err * 5 ) / 16;
nextberr[col + 2] += ( err ) / 16;
err = (sa - (long)PAM_GETA(acolormap[ind].acolor))*FS_SCALE;
thisaerr[col + 2] += ( err * 7 ) / 16;
nextaerr[col ] += ( err * 3 ) / 16;
nextaerr[col + 1] += ( err * 5 ) / 16;
nextaerr[col + 2] += ( err ) / 16;
} else {
err = (sr - (long)PAM_GETR(acolormap[ind].acolor))*FS_SCALE * colorimp/256;
thisrerr[col ] += ( err * 7 ) / 16;
nextrerr[col + 2] += ( err * 3 ) / 16;
nextrerr[col + 1] += ( err * 5 ) / 16;
nextrerr[col ] += ( err ) / 16;
err = (sg - (long)PAM_GETG(acolormap[ind].acolor))*FS_SCALE * colorimp/256;
thisgerr[col ] += ( err * 7 ) / 16;
nextgerr[col + 2] += ( err * 3 ) / 16;
nextgerr[col + 1] += ( err * 5 ) / 16;
nextgerr[col ] += ( err ) / 16;
err = (sb - (long)PAM_GETB(acolormap[ind].acolor))*FS_SCALE * colorimp/256;
thisberr[col ] += ( err * 7 ) / 16;
nextberr[col + 2] += ( err * 3 ) / 16;
nextberr[col + 1] += ( err * 5 ) / 16;
nextberr[col ] += ( err ) / 16;
err = (sa - (long)PAM_GETA(acolormap[ind].acolor))*FS_SCALE;
thisaerr[col ] += ( err * 7 ) / 16;
nextaerr[col + 2] += ( err * 3 ) / 16;
nextaerr[col + 1] += ( err * 5 ) / 16;
nextaerr[col ] += ( err ) / 16;
}
}
/* *pP = acolormap[ind].acolor; */
*pQ = (uch)remap[ind];
if ( ( ! floyd ) || fs_direction ) {
++col;
++pP;
++pQ;
} else {
--col;
--pP;