Debian Codegraph @

converter/other/pnmtopng.c

raw
1 /*
2 ** read a PNM image and produce a Portable Network Graphics file
3 **
4 ** derived from pnmtorast.c (c) 1990,1991 by Jef Poskanzer and some
5 ** parts derived from ppmtogif.c by Marcel Wijkstra <[email protected]>
6 **
7 ** Copyright (C) 1995-1998 by Alexander Lehmann <[email protected]>
8 ** and Willem van Schaik <[email protected]>
9 ** Copyright (C) 1999,2001 by Greg Roelofs <[email protected]>
10 **
11 ** Permission to use, copy, modify, and distribute this software and its
12 ** documentation for any purpose and without fee is hereby granted, provided
13 ** that the above copyright notice appear in all copies and that both that
14 ** copyright notice and this permission notice appear in supporting
15 ** documentation. This software is provided "as is" without express or
16 ** implied warranty.
17 */
18
19 /* This Netpbm version of Pnmtopng was derived from the independently
20 distributed program of the same name, Version 2.37.6 (21 July 2001).
21 */
22
23 /* A performance note: This program reads one row at a time because
24 the whole image won't fit in memory always. When you realize that
25 in a Netpbm xel array a one bit pixel can take 96 bits of memory,
26 it's easy to see that an ordinary fax could deplete your virtual
27 memory and even if it didn't, it might deplete your real memory and
28 iterating through the array would cause thrashing. This program
29 iterates through the image multiple times.
30
31 So instead, we read the image into memory one row at a time, into a
32 single row buffer. We use Netpbm's pm_openr_seekable() facility to
33 access the file. That facility copies the file into a temporary
34 file if it isn't seekable, so we always end up with a file that we
35 can rewind and reread multiple times.
36
37 This shouldn't cause I/O delays because the entire image ought to fit
38 in the system's I/O cache (remember that the file is a lot smaller than
39 the xel array you'd get by doing a pnm_readpnm() of it).
40
41 However, it does introduce some delay because of all the system calls
42 required to read the file. A future enhancement might read the entire
43 file into an xel array in some cases, and read one row at a time in
44 others, depending on the needs of the particular use.
45
46 We do still read the entire alpha mask (if there is one) into a
47 'gray' array, rather than access it one row at a time.
48
49 Before May 2001, we did in fact read the whole image into an xel array,
50 and we got complaints. Before April 2000, it wasn't as big a problem
51 because xels were only 24 bits. Now they're 96.
52 */
53
54 #ifndef PNMTOPNG_WARNING_LEVEL
55 # define PNMTOPNG_WARNING_LEVEL 0 /* use 0 for backward compatibility, */
56 #endif /* 2 for warnings (1 == error) */
57
58 #include <assert.h>
59 #include <stdbool.h>
60 #include <string.h> /* strcat() */
61 #include <limits.h>
62 #include <png.h>
63 #include <zlib.h>
64
65 #include "pm_c_util.h"
66 #include "pnm.h"
67 #include "pngx.h"
68 #include "pngtxt.h"
69 #include "shhopt.h"
70 #include "mallocvar.h"
71 #include "nstring.h"
72 #include "version.h"
73
74 struct zlibCompression {
75 /* These are parameters that describe a form of zlib compression.
76 Values have the same meaning as the similarly named arguments to
77 zlib's deflateInit2(). See zlib.h.
78 */
79 unsigned int levelSpec;
80 unsigned int level;
81 unsigned int memLevelSpec;
82 unsigned int mem_level;
83 unsigned int strategySpec;
84 unsigned int strategy;
85 unsigned int windowBitsSpec;
86 unsigned int window_bits;
87 unsigned int methodSpec;
88 unsigned int method;
89 unsigned int bufferSizeSpec;
90 unsigned int buffer_size;
91 };
92
93 typedef struct cahitem {
94 xel color;
95 gray alpha;
96 int value;
97 struct cahitem * next;
98 } cahitem;
99
100 typedef cahitem ** coloralphahash_table;
101
102 struct cmdlineInfo {
103 /* All the information the user supplied in the command line,
104 in a form easy for the program to use.
105 */
106 const char * inputFileName; /* '-' if stdin */
107 const char * alpha;
108 unsigned int verbose;
109 unsigned int downscale;
110 unsigned int interlace;
111 const char * transparent; /* NULL if none */
112 const char * background; /* NULL if none */
113 unsigned int gammaSpec;
114 float gamma; /* Meaningless if !gammaSpec */
115 unsigned int hist;
116 unsigned int rgbSpec;
117 struct pngx_chroma rgb; /* Meaningless if !rgbSpec */
118 unsigned int sizeSpec;
119 struct pngx_phys size; /* Meaningless if !sizeSpec */
120 unsigned int srgbintentSpec;
121 pngx_srgbIntent srgbintent;
122 const char * text; /* NULL if none */
123 const char * ztxt; /* NULL if none */
124 unsigned int modtimeSpec;
125 time_t modtime; /* Meaningless if !modtimeSpec */
126 const char * palette; /* NULL if none */
127 bool filterSetSpec;
128 int filterSet;
129 unsigned int force;
130 unsigned int libversion;
131 struct zlibCompression zlibCompression;
132 };
133
134
135
136 #ifndef NONE
137 # define NONE 0
138 #endif
139 #define MAXCOLORS 256
140 #define MAXPALETTEENTRIES 256
141
142 /* PALETTEMAXVAL is the maxval used in a PNG palette */
143 #define PALETTEMAXVAL 255
144
145 #define PALETTEOPAQUE 255
146 #define PALETTETRANSPARENT 0
147
148 static bool verbose;
149
150 static int errorlevel;
151
152
153
154 static void
155 parseSizeOpt(const char * const sizeOpt,
156 struct pngx_phys * const sizeP) {
157
158 int count;
159
160 count = sscanf(sizeOpt, "%d %d %d", &sizeP->x, &sizeP->y, &sizeP->unit);
161
162 if (count != 3)
163 pm_error("Invalid syntax for the -size option value '%s'. "
164 "Should be 3 integers: x, y, and unit code", sizeOpt);
165 }
166
167
168
169 static void
170 parseRgbOpt(const char * const rgbOpt,
171 struct pngx_chroma * const rgbP) {
172
173 int count;
174
175 count = sscanf(rgbOpt, "%f %f %f %f %f %f %f %f",
176 &rgbP->wx, &rgbP->wy,
177 &rgbP->rx, &rgbP->ry,
178 &rgbP->gx, &rgbP->gy,
179 &rgbP->bx, &rgbP->by);
180
181 if (count != 8)
182 pm_error("Invalid syntax for the -rgb option value '%s'. "
183 "Should be 8 floating point numbers: "
184 "x and y for each of white, red, green, and blue",
185 rgbOpt);
186 }
187
188
189
190 static void
191 parseSrgbintentOpt(const char * const srgbintentOpt,
192 pngx_srgbIntent * const srgbintentP) {
193
194 if (streq(srgbintentOpt, "perceptual"))
195 *srgbintentP = PNGX_PERCEPTUAL;
196 else if (streq(srgbintentOpt, "relativecolorimetric"))
197 *srgbintentP = PNGX_RELATIVE_COLORIMETRIC;
198 else if (streq(srgbintentOpt, "saturation"))
199 *srgbintentP = PNGX_SATURATION;
200 else if (streq(srgbintentOpt, "absolutecolorimetric"))
201 *srgbintentP = PNGX_ABSOLUTE_COLORIMETRIC;
202 else
203 pm_error("Unrecognized sRGB intent value '%s'. We understand "
204 "only 'perceptual', 'relativecolorimetric', "
205 "'saturation', and 'absolutecolorimetric'",
206 srgbintentOpt);
207 }
208
209
210
211 static void
212 parseModtimeOpt(const char * const modtimeOpt,
213 time_t * const modtimeP) {
214
215 struct tm brokenTime;
216 int year;
217 int month;
218 int count;
219
220 count = sscanf(modtimeOpt, "%d-%d-%d %d:%d:%d",
221 &year,
222 &month,
223 &brokenTime.tm_mday,
224 &brokenTime.tm_hour,
225 &brokenTime.tm_min,
226 &brokenTime.tm_sec);
227
228 if (count != 6)
229 pm_error("Invalid value for -modtime '%s'. It should have "
230 "the form [yy]yy-mm-dd hh:mm:ss.", modtimeOpt);
231
232 if (year < 0)
233 pm_error("Year is negative in -modtime value '%s'", modtimeOpt);
234 if (year > 9999)
235 pm_error("Year is more than 4 digits in -modtime value '%s'",
236 modtimeOpt);
237 if (month < 0)
238 pm_error("Month is negative in -modtime value '%s'", modtimeOpt);
239 if (month > 12)
240 pm_error("Month is >12 in -modtime value '%s'", modtimeOpt);
241 if (brokenTime.tm_mday < 0)
242 pm_error("Day of month is negative in -modtime value '%s'",
243 modtimeOpt);
244 if (brokenTime.tm_mday > 31)
245 pm_error("Day of month is >31 in -modtime value '%s'", modtimeOpt);
246 if (brokenTime.tm_hour < 0)
247 pm_error("Hour is negative in -modtime value '%s'", modtimeOpt);
248 if (brokenTime.tm_hour > 23)
249 pm_error("Hour is >23 in -modtime value '%s'", modtimeOpt);
250 if (brokenTime.tm_min < 0)
251 pm_error("Minute is negative in -modtime value '%s'", modtimeOpt);
252 if (brokenTime.tm_min > 59)
253 pm_error("Minute is >59 in -modtime value '%s'", modtimeOpt);
254 if (brokenTime.tm_sec < 0)
255 pm_error("Second is negative in -modtime value '%s'", modtimeOpt);
256 if (brokenTime.tm_sec > 59)
257 pm_error("Second is >59 in -modtime value '%s'", modtimeOpt);
258
259 brokenTime.tm_mon = month - 1;
260 if (year >= 1900)
261 brokenTime.tm_year = year - 1900;
262 else
263 brokenTime.tm_year = year;
264
265 /* Note that mktime() considers brokeTime to be in local time.
266 This is what we want, since we got it from a user. User should
267 set his local time zone to UTC if he wants absolute time.
268 */
269 *modtimeP = mktime(&brokenTime);
270 }
271
272
273
274 static void
275 parseCommandLine(int argc, const char ** argv,
276 struct cmdlineInfo * const cmdlineP) {
277 /*----------------------------------------------------------------------------
278 parse program command line described in Unix standard form by argc
279 and argv. Return the information in the options as *cmdlineP.
280
281 If command line is internally inconsistent (invalid options, etc.),
282 issue error message to stderr and abort program.
283
284 Note that the strings we return are stored in the storage that
285 was passed to us as the argv array. We also trash *argv.
286 -----------------------------------------------------------------------------*/
287 optEntry * option_def; /* Used by OPTENT3 */
288 optStruct3 opt;
289
290 unsigned int option_def_index;
291
292 unsigned int alphaSpec, transparentSpec, backgroundSpec;
293 unsigned int textSpec, ztxtSpec, paletteSpec;
294 unsigned int filterSpec;
295
296 unsigned int nofilter, sub, up, avg, paeth, filter;
297 unsigned int chroma, phys, time;
298 const char * size;
299 const char * rgb;
300 const char * modtime;
301 const char * compMethod;
302 const char * compStrategy;
303 const char * srgbintent;
304
305 MALLOCARRAY_NOFAIL(option_def, 100);
306
307 option_def_index = 0; /* incremented by OPTENT3 */
308 OPTENT3(0, "alpha", OPT_STRING, &cmdlineP->alpha,
309 &alphaSpec, 0);
310 OPTENT3(0, "transparent", OPT_STRING, &cmdlineP->transparent,
311 &transparentSpec, 0);
312 OPTENT3(0, "background", OPT_STRING, &cmdlineP->background,
313 &backgroundSpec, 0);
314 OPTENT3(0, "rgb", OPT_STRING, &rgb,
315 &cmdlineP->rgbSpec, 0);
316 OPTENT3(0, "size", OPT_STRING, &size,
317 &cmdlineP->sizeSpec, 0);
318 OPTENT3(0, "srgbintent", OPT_STRING, &srgbintent,
319 &cmdlineP->srgbintentSpec, 0);
320 OPTENT3(0, "text", OPT_STRING, &cmdlineP->text,
321 &textSpec, 0);
322 OPTENT3(0, "ztxt", OPT_STRING, &cmdlineP->ztxt,
323 &ztxtSpec, 0);
324 OPTENT3(0, "modtime", OPT_STRING, &modtime,
325 &cmdlineP->modtimeSpec,0);
326 OPTENT3(0, "palette", OPT_STRING, &cmdlineP->palette,
327 &paletteSpec, 0);
328 OPTENT3(0, "compression", OPT_UINT,
329 &cmdlineP->zlibCompression.level,
330 &cmdlineP->zlibCompression.levelSpec, 0);
331 OPTENT3(0, "comp_mem_level", OPT_UINT,
332 &cmdlineP->zlibCompression.mem_level,
333 &cmdlineP->zlibCompression.memLevelSpec, 0);
334 OPTENT3(0, "comp_strategy", OPT_STRING, &compStrategy,
335 &cmdlineP->zlibCompression.strategySpec, 0);
336 OPTENT3(0, "comp_window_bits", OPT_UINT,
337 &cmdlineP->zlibCompression.window_bits,
338 &cmdlineP->zlibCompression.windowBitsSpec, 0);
339 OPTENT3(0, "comp_method", OPT_STRING, &compMethod,
340 &cmdlineP->zlibCompression.methodSpec, 0);
341 OPTENT3(0, "comp_buffer_size", OPT_UINT,
342 &cmdlineP->zlibCompression.buffer_size,
343 &cmdlineP->zlibCompression.bufferSizeSpec, 0);
344 OPTENT3(0, "gamma", OPT_FLOAT, &cmdlineP->gamma,
345 &cmdlineP->gammaSpec, 0);
346 OPTENT3(0, "hist", OPT_FLAG, NULL,
347 &cmdlineP->hist, 0);
348 OPTENT3(0, "downscale", OPT_FLAG, NULL,
349 &cmdlineP->downscale, 0);
350 OPTENT3(0, "interlace", OPT_FLAG, NULL,
351 &cmdlineP->interlace, 0);
352 OPTENT3(0, "force", OPT_FLAG, NULL,
353 &cmdlineP->force, 0);
354 OPTENT3(0, "libversion", OPT_FLAG, NULL,
355 &cmdlineP->libversion, 0);
356 OPTENT3(0, "verbose", OPT_FLAG, NULL,
357 &cmdlineP->verbose, 0);
358 OPTENT3(0, "nofilter", OPT_FLAG, NULL,
359 &nofilter, 0);
360 OPTENT3(0, "sub", OPT_FLAG, NULL,
361 &sub, 0);
362 OPTENT3(0, "up", OPT_FLAG, NULL,
363 &up, 0);
364 OPTENT3(0, "avg", OPT_FLAG, NULL,
365 &avg, 0);
366 OPTENT3(0, "paeth", OPT_FLAG, NULL,
367 &paeth, 0);
368 OPTENT3(0, "filter", OPT_INT, &filter,
369 &filterSpec, 0);
370 OPTENT3(0, "verbose", OPT_FLAG, NULL,
371 &cmdlineP->verbose, 0);
372 OPTENT3(0, "chroma", OPT_FLAG, NULL,
373 &chroma, 0);
374 OPTENT3(0, "phys", OPT_FLAG, NULL,
375 &phys, 0);
376 OPTENT3(0, "time", OPT_FLAG, NULL,
377 &time, 0);
378
379
380 opt.opt_table = option_def;
381 opt.short_allowed = false; /* We have no short (old-fashioned) options */
382 opt.allowNegNum = false; /* We have no parms that are negative numbers */
383
384 pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
385 /* Uses and sets argc, argv, and some of *cmdlineP and others. */
386
387
388 if (chroma)
389 pm_error("The -chroma option no longer exists. Use -rgb instead.");
390 if (phys)
391 pm_error("The -phys option no longer exists. Use -size instead.");
392 if (time)
393 pm_error("The -time option no longer exists. Use -modtime instead.");
394
395 if (alphaSpec + transparentSpec > 1)
396 pm_error("You may not specify both -alpha and -transparent");
397 if (!alphaSpec)
398 cmdlineP->alpha = NULL;
399 if (!transparentSpec)
400 cmdlineP->transparent = NULL;
401 if (!backgroundSpec)
402 cmdlineP->background = NULL;
403 if (!textSpec)
404 cmdlineP->text = NULL;
405 if (!ztxtSpec)
406 cmdlineP->ztxt = NULL;
407 if (!paletteSpec)
408 cmdlineP->palette = NULL;
409
410 if (filterSpec && (nofilter + sub + up + avg + paeth > 0))
411 pm_error("You may not specify -filter with "
412 "-nofilter, -sub, -up, -avg, or -paeth");
413
414 if (filterSpec) {
415 if (filter < 0 || filter > 4)
416 pm_error("-filter is obsolete. Use -nofilter, -sub, -up, -avg, "
417 "and -paeth options instead.");
418 else {
419 cmdlineP->filterSetSpec = true;
420
421 switch (filter) {
422 case 0: cmdlineP->filterSet = PNG_FILTER_NONE; break;
423 case 1: cmdlineP->filterSet = PNG_FILTER_SUB; break;
424 case 2: cmdlineP->filterSet = PNG_FILTER_UP; break;
425 case 3: cmdlineP->filterSet = PNG_FILTER_AVG; break;
426 case 4: cmdlineP->filterSet = PNG_FILTER_PAETH; break;
427 }
428 }
429 } else {
430 if (nofilter + sub + up + avg + paeth == 0)
431 cmdlineP->filterSetSpec = false;
432 else {
433 cmdlineP->filterSetSpec = true;
434 cmdlineP->filterSet = PNG_NO_FILTERS; /* initial value */
435 if (nofilter)
436 cmdlineP->filterSet |= PNG_FILTER_NONE;
437 if (sub)
438 cmdlineP->filterSet |= PNG_FILTER_SUB;
439 if (up)
440 cmdlineP->filterSet |= PNG_FILTER_UP;
441 if (avg)
442 cmdlineP->filterSet |= PNG_FILTER_AVG;
443 if (paeth)
444 cmdlineP->filterSet |= PNG_FILTER_PAETH;
445 }
446 }
447 if (cmdlineP->sizeSpec)
448 parseSizeOpt(size, &cmdlineP->size);
449
450 if (cmdlineP->rgbSpec)
451 parseRgbOpt(rgb, &cmdlineP->rgb);
452
453 if (cmdlineP->srgbintentSpec)
454 parseSrgbintentOpt(srgbintent, &cmdlineP->srgbintent);
455
456 if (cmdlineP->modtimeSpec)
457 parseModtimeOpt(modtime, &cmdlineP->modtime);
458
459 if (cmdlineP->zlibCompression.levelSpec &&
460 cmdlineP->zlibCompression.level > 9)
461 pm_error("-compression value must be from 0 (no compression) "
462 "to 9 (maximum compression). You specified %u",
463 cmdlineP->zlibCompression.level);
464
465 if (cmdlineP->zlibCompression.memLevelSpec) {
466 if (cmdlineP->zlibCompression.mem_level < 1 ||
467 cmdlineP->zlibCompression.mem_level > 9)
468 pm_error("-comp_mem_level value must be from 1 (minimum memory usage) "
469 "to 9 (maximum memory usage). You specified %u",
470 cmdlineP->zlibCompression.mem_level);
471 }
472
473 if (cmdlineP->zlibCompression.methodSpec) {
474 if (streq(compMethod, "deflated"))
475 cmdlineP->zlibCompression.method = Z_DEFLATED;
476 else
477 pm_error("The only valid value for -method is 'deflated'. "
478 "You specified '%s'", compMethod);
479 }
480
481 if (cmdlineP->zlibCompression.strategySpec) {
482 if (streq(compStrategy, "huffman_only"))
483 cmdlineP->zlibCompression.strategy = Z_HUFFMAN_ONLY;
484 else if (streq(compStrategy, "filtered"))
485 cmdlineP->zlibCompression.strategy = Z_FILTERED;
486 else
487 pm_error("Valid values for -strategy are 'huffman_only' and "
488 "filtered. You specified '%s'", compStrategy);
489 }
490
491
492 if (argc-1 < 1)
493 cmdlineP->inputFileName = "-";
494 else if (argc-1 == 1)
495 cmdlineP->inputFileName = argv[1];
496 else
497 pm_error("Program takes at most one argument: input file name");
498
499 free(option_def);
500 }
501
502
503
504 static void
505 reportInputType(int const format,
506 xelval const maxval) {
507
508 switch (PNM_FORMAT_TYPE(format)) {
509 case PBM_TYPE:
510 pm_message ("reading a PBM file");
511 break;
512 case PGM_TYPE:
513 pm_message ("reading a PGM file (maxval=%d)", maxval);
514 break;
515 case PPM_TYPE:
516 pm_message ("reading a PPM file (maxval=%d)", maxval);
517 break;
518 default:
519 assert(false);
520 }
521 }
522
523
524
525 static png_color_16
526 xelToPngColor_16(xel const input,
527 xelval const maxval,
528 xelval const pngMaxval) {
529
530 png_color_16 retval;
531
532 xel scaled;
533
534 PPM_DEPTH(scaled, input, maxval, pngMaxval);
535
536 retval.red = PPM_GETR(scaled);
537 retval.green = PPM_GETG(scaled);
538 retval.blue = PPM_GETB(scaled);
539 retval.gray = PNM_GET1(scaled);
540
541 return retval;
542 }
543
544
545
546 static void
547 closestColorInPalette(pixel const targetColor,
548 pixel palette_pnm[],
549 unsigned int const paletteSize,
550 unsigned int * const bestIndexP,
551 unsigned int * const bestMatchP) {
552
553 unsigned int paletteIndex;
554 unsigned int bestIndex;
555 unsigned int bestMatch;
556
557 assert(paletteSize > 0);
558
559 bestMatch = UINT_MAX;
560 for (paletteIndex = 0; paletteIndex < paletteSize; ++paletteIndex) {
561 unsigned int const dist =
562 PPM_DISTANCE(palette_pnm[paletteIndex], targetColor);
563
564 if (dist < bestMatch) {
565 bestMatch = dist;
566 bestIndex = paletteIndex;
567 }
568 }
569 if (bestIndexP != NULL)
570 *bestIndexP = bestIndex;
571 if (bestMatchP != NULL)
572 *bestMatchP = bestMatch;
573 }
574
575
576
577 /* We really ought to make this hash function actually depend upon
578 the "a" argument; we just don't know a decent prime number off-hand.
579 */
580 #define HASH_SIZE 20023
581 #define hashpixelalpha(p,a) ((((long) PPM_GETR(p) * 33023 + \
582 (long) PPM_GETG(p) * 30013 + \
583 (long) PPM_GETB(p) * 27011 ) \
584 & 0x7fffffff ) % HASH_SIZE )
585
586 static coloralphahash_table
587 alloccoloralphahash(void) {
588 coloralphahash_table caht;
589 int i;
590
591 MALLOCARRAY(caht,HASH_SIZE);
592 if (caht == NULL)
593 pm_error( "out of memory allocating hash table" );
594
595 for (i = 0; i < HASH_SIZE; ++i)
596 caht[i] = NULL;
597
598 return caht;
599 }
600
601
602
603 static void
604 freecoloralphahash(coloralphahash_table const caht) {
605 int i;
606
607 for (i = 0; i < HASH_SIZE; ++i) {
608 cahitem * p;
609 cahitem * next;
610 for (p = caht[i]; p; p = next) {
611 next = p->next;
612 free(p);
613 }
614 }
615 free(caht);
616 }
617
618
619
620 static void
621 addtocoloralphahash(coloralphahash_table const caht,
622 pixel * const colorP,
623 gray * const alphaP,
624 int const value) {
625
626 int hash;
627 cahitem * itemP;
628
629 MALLOCVAR(itemP);
630 if (itemP == NULL)
631 pm_error("Out of memory building hash table");
632 hash = hashpixelalpha(*colorP, *alphaP);
633 itemP->color = *colorP;
634 itemP->alpha = *alphaP;
635 itemP->value = value;
636 itemP->next = caht[hash];
637 caht[hash] = itemP;
638 }
639
640
641
642 static int
643 lookupColorAlpha(coloralphahash_table const caht,
644 const pixel * const colorP,
645 const gray * const alphaP) {
646
647 int hash;
648 cahitem * p;
649
650 hash = hashpixelalpha(*colorP, *alphaP);
651 for (p = caht[hash]; p; p = p->next)
652 if (PPM_EQUAL(p->color, *colorP) && p->alpha == *alphaP)
653 return p->value;
654
655 return -1;
656 }
657
658
659
660 /* The following variables belong to getChv() and freeChv() */
661 static bool getChv_computed = false;
662 static colorhist_vector getChv_chv;
663
664
665
666 static void
667 getChv(FILE * const ifP,
668 pm_filepos const rasterPos,
669 int const cols,
670 int const rows,
671 xelval const maxval,
672 int const format,
673 int const maxColors,
674 colorhist_vector * const chvP,
675 unsigned int * const colorsP) {
676 /*----------------------------------------------------------------------------
677 Return a list of all the colors in a libnetpbm image and the number of
678 times they occur. The image is in the seekable file 'ifP', whose
679 raster starts at position 'rasterPos' of the file. The image's properties
680 are 'cols', 'rows', 'maxval', and 'format'.
681
682 Return the number of colors as *colorsP. Return the details of the
683 colors in newly malloc'ed storage, and its address as *chvP. If
684 there are more than 'maxColors' colors, though, just return NULL as
685 *chvP and leave *colorsP undefined.
686
687 Don't spend the time to read the file if this subroutine has been called
688 before. In that case, just assume the inputs are all the same and return
689 the previously computed information. Ick.
690
691 *chvP is in static program storage.
692 -----------------------------------------------------------------------------*/
693 static unsigned int getChv_colors;
694
695 if (!getChv_computed) {
696 int colorCount;
697 if (verbose)
698 pm_message ("Finding colors in input image...");
699
700 pm_seek2(ifP, &rasterPos, sizeof(rasterPos));
701 getChv_chv = ppm_computecolorhist2(ifP, cols, rows, maxval, format,
702 maxColors, &colorCount);
703
704 getChv_colors = colorCount;
705
706 if (verbose) {
707 if (getChv_chv)
708 pm_message("%u colors found", getChv_colors);
709 else
710 pm_message("Too many colors (more than %u) found", maxColors);
711 }
712 getChv_computed = true;
713 }
714 *chvP = getChv_chv;
715 *colorsP = getChv_colors;
716 }
717
718
719
720 static void freeChv(void) {
721
722 if (getChv_computed)
723 if (getChv_chv)
724 ppm_freecolorhist(getChv_chv);
725
726 getChv_computed = false;
727 }
728
729
730
731 static bool
732 pgmBitsAreRepeated(unsigned int const repeatedSize,
733 FILE * const ifP,
734 pm_filepos const rasterPos,
735 int const cols,
736 int const rows,
737 xelval const maxval,
738 int const format) {
739 /*----------------------------------------------------------------------------
740 Return true iff all the samples in the image in file 'ifP',
741 described by 'cols', 'rows', 'maxval', and 'format', consist in the
742 rightmost 'repeatedSize' * 2 bits of two identical sets of
743 'repeatedSize' bits.
744
745 The file has arbitrary position, but the raster is at file position
746 'rasterPos'.
747
748 E.g. for repeatedSize = 2, a sample value of 0xaa would qualify.
749 So would 0x0a.
750
751 Leave the file positioned where we found it.
752 -----------------------------------------------------------------------------*/
753 unsigned int const mask2 = (1 << repeatedSize*2) - 1;
754 unsigned int const mask1 = (1 << repeatedSize) - 1;
755
756 bool mayscale;
757 unsigned int row;
758 xel * xelrow;
759
760 xelrow = pnm_allocrow(cols);
761
762 pm_seek2(ifP, &rasterPos, sizeof(rasterPos));
763
764 mayscale = true; /* initial assumption */
765
766 for (row = 0; row < rows && mayscale; ++row) {
767 unsigned int col;
768 pnm_readpnmrow(ifP, xelrow, cols, maxval, format);
769 for (col = 0; col < cols && mayscale; ++col) {
770 xelval const testbits2 = PNM_GET1(xelrow[col]) & mask2;
771 /* The bits of interest in the sample */
772 xelval const testbits1 = testbits2 & mask1;
773 /* The lower half of the bits of interest in the sample */
774 if (((testbits1 << repeatedSize) | testbits1) != testbits2)
775 mayscale = false;
776 }
777 }
778 pnm_freerow(xelrow);
779
780 return mayscale;
781 }
782
783
784
785 static void
786 meaningful_bits_pgm(FILE * const ifP,
787 pm_filepos const rasterPos,
788 int const cols,
789 int const rows,
790 xelval const maxval,
791 int const format,
792 unsigned int * const retvalP) {
793 /*----------------------------------------------------------------------------
794 In the PGM raster with maxval 'maxval' at file offset 'rasterPos'
795 in file 'ifp', the samples may be composed of groups of 1, 2, 4, or 8
796 bits repeated. This would be the case if the image were converted
797 at some point from a 2 bits-per-pixel image to an 8-bits-per-pixel
798 image, for example.
799
800 If this is the case, we find out and find out how small these repeated
801 groups of bits are and return the number of bits.
802 -----------------------------------------------------------------------------*/
803 unsigned int maxMeaningfulBits;
804 /* progressive estimate of the maximum number of meaningful
805 (nonrepeated) bits in the samples.
806 */
807
808 maxMeaningfulBits = pm_maxvaltobits(maxval); /* initial value */
809
810 if (maxval == 0xffff || maxval == 0xff || maxval == 0xf || maxval == 0x3) {
811 if (maxMeaningfulBits == 16) {
812 if (pgmBitsAreRepeated(8,
813 ifP, rasterPos, cols, rows, maxval, format))
814 maxMeaningfulBits = 8;
815 }
816 if (maxMeaningfulBits == 8) {
817 if (pgmBitsAreRepeated(4,
818 ifP, rasterPos, cols, rows, maxval, format))
819 maxMeaningfulBits = 4;
820 }
821 if (maxMeaningfulBits == 4) {
822 if (pgmBitsAreRepeated(2,
823 ifP, rasterPos, cols, rows, maxval, format))
824 maxMeaningfulBits = 2;
825 }
826 if (maxMeaningfulBits == 2) {
827 if (pgmBitsAreRepeated(1,
828 ifP, rasterPos, cols, rows, maxval, format))
829 maxMeaningfulBits = 1;
830 }
831 }
832 *retvalP = maxMeaningfulBits;
833 }
834
835
836
837 static void
838 meaningful_bits_ppm(FILE * const ifp,
839 pm_filepos const rasterPos,
840 int const cols,
841 int const rows,
842 xelval const maxval,
843 int const format,
844 unsigned int * const retvalP) {
845 /*----------------------------------------------------------------------------
846 In the PPM raster with maxval 'maxval' at file offset 'rasterPos'
847 in file 'ifp', the samples may be composed of groups of 8
848 bits repeated twice. This would be the case if the image were converted
849 at some point from a 8 bits-per-pixel image to an 16-bits-per-pixel
850 image, for example.
851
852 We return the smallest number of bits we can take from the right of
853 a sample without losing information (8 or all).
854 -----------------------------------------------------------------------------*/
855 int mayscale;
856 unsigned int row;
857 xel * xelrow;
858 unsigned int maxMeaningfulBits;
859 /* progressive estimate of the maximum number of meaningful
860 (nonrepeated) bits in the samples.
861 */
862
863 xelrow = pnm_allocrow(cols);
864
865 maxMeaningfulBits = pm_maxvaltobits(maxval);
866
867 if (maxval == 65535) {
868 mayscale = true; /* initial assumption */
869 pm_seek2(ifp, &rasterPos, sizeof(rasterPos));
870 for (row = 0; row < rows && mayscale; ++row) {
871 unsigned int col;
872 pnm_readpnmrow(ifp, xelrow, cols, maxval, format);
873 for (col = 0; col < cols && mayscale; ++col) {
874 xel const p = xelrow[col];
875 if ((PPM_GETR(p) & 0xff) * 0x101 != PPM_GETR(p) ||
876 (PPM_GETG(p) & 0xff) * 0x101 != PPM_GETG(p) ||
877 (PPM_GETB(p) & 0xff) * 0x101 != PPM_GETB(p))
878 mayscale = false;
879 }
880 }
881 if (mayscale)
882 maxMeaningfulBits = 8;
883 }
884 pnm_freerow(xelrow);
885
886 *retvalP = maxMeaningfulBits;
887 }
888
889
890
891 static void
892 tryTransparentColor(FILE * const ifP,
893 pm_filepos const rasterPos,
894 int const cols,
895 int const rows,
896 xelval const maxval,
897 int const format,
898 gray ** const alphaMask,
899 gray const alphaMaxval,
900 pixel const transcolor,
901 bool * const singleColorIsTransP) {
902 /*----------------------------------------------------------------------------
903 Find out if the transparent pixels identified by alpha mask 'alphaMask'
904 (whose maxval is 'alphaMaxval') are exactly the pixels of color
905 'transcolor'. Return answer as *singleColorIsTransP.
906
907 The image we analyze is that on input stream *ifP, starting at position
908 'rasterPos', and we leave that stream positioned arbitrarily.
909 -----------------------------------------------------------------------------*/
910 int const pnmType = PNM_FORMAT_TYPE(format);
911
912 xel * xelrow;
913 bool singleColorIsTrans;
914 /* So far, it looks like a single color is uniquely transparent */
915 int row;
916
917 xelrow = pnm_allocrow(cols);
918
919 pm_seek2(ifP, &rasterPos, sizeof(rasterPos));
920
921 singleColorIsTrans = true; /* initial assumption */
922
923 for (row = 0; row < rows && singleColorIsTrans; ++row) {
924 int col;
925 pnm_readpnmrow(ifP, xelrow, cols, maxval, format);
926 for (col = 0 ; col < cols && singleColorIsTrans; ++col) {
927 if (alphaMask[row][col] == 0) { /* transparent */
928 /* If we have a second transparent color, we're
929 disqualified
930 */
931 if (pnmType == PPM_TYPE) {
932 if (!PPM_EQUAL(xelrow[col], transcolor))
933 singleColorIsTrans = false;
934 } else {
935 if (PNM_GET1(xelrow[col]) != PNM_GET1(transcolor))
936 singleColorIsTrans = false;
937 }
938 } else if (alphaMask[row][col] != alphaMaxval) {
939 /* Here's an area of the mask that is translucent. That
940 disqualified us.
941 */
942 singleColorIsTrans = false;
943 } else {
944 /* Here's an area of the mask that is opaque. If it's
945 the same color as our candidate transparent color,
946 that disqualifies us.
947 */
948 if (pnmType == PPM_TYPE) {
949 if (PPM_EQUAL(xelrow[col], transcolor))
950 singleColorIsTrans = false;
951 } else {
952 if (PNM_GET1(xelrow[col]) == PNM_GET1(transcolor))
953 singleColorIsTrans = false;
954 }
955 }
956 }
957 }
958 *singleColorIsTransP = singleColorIsTrans;
959
960 pnm_freerow(xelrow);
961 }
962
963
964
965 static void
966 analyzeAlpha(FILE * const ifP,
967 pm_filepos const rasterPos,
968 unsigned int const cols,
969 unsigned int const rows,
970 xelval const maxval,
971 int const format,
972 gray ** const alphaMask,
973 gray const alphaMaxval,
974 bool * const allOpaqueP,
975 bool * const singleColorIsTransP,
976 pixel * const alphaTranscolorP) {
977 /*----------------------------------------------------------------------------
978 Get information about the alpha mask, in combination with the masked
979 image, that Caller can use to choose the most efficient way to
980 represent the information in the alpha mask in a PNG. Simply
981 putting the alpha mask in the PNG is a last resort. But if the mask
982 says all opaque, we can simply omit any mention of transparency
983 instead -- default is opaque. And if the mask makes all the pixels
984 of a certain color fully transparent and every other pixel opaque,
985 we can simply identify that color in the PNG.
986
987 We have to do this before any scaling occurs, since alpha is possible
988 only with 8 and 16-bit.
989 -----------------------------------------------------------------------------*/
990 xel * xelrow;
991 bool foundTransparentPixel;
992 /* We found a pixel in the image where the alpha mask says it is
993 transparent.
994 */
995 pixel transcolor;
996 /* Color of the transparent pixel mentioned above. */
997 bool foundNonOpaquePixel;
998 /* We found a pixel in the image where the alpha mask says it is
999 not fully opaque.
1000 */
1001
1002 xelrow = pnm_allocrow(cols);
1003
1004 {
1005 unsigned int row;
1006 /* See if the mask says every pixel is opaque. */
1007 foundNonOpaquePixel = false; /* initial assumption */
1008 pm_seek2(ifP, &rasterPos, sizeof(rasterPos));
1009 for (row = 0; row < rows && !foundNonOpaquePixel; ++row) {
1010 unsigned int col;
1011 pnm_readpnmrow(ifP, xelrow, cols, maxval, format);
1012 for (col = 0; col < cols && !foundNonOpaquePixel; ++col) {
1013 if (alphaMask[row][col] != maxval)
1014 foundNonOpaquePixel = true;
1015 }
1016 }
1017 }
1018
1019 if (foundNonOpaquePixel) {
1020 unsigned int row;
1021 /* Find a candidate transparent color -- the color of any pixel in the
1022 image that the alpha mask says should be transparent.
1023 */
1024 foundTransparentPixel = false; /* initial assumption */
1025 pm_seek2(ifP, &rasterPos, sizeof(rasterPos));
1026 for (row = 0; row < rows && !foundTransparentPixel; ++row) {
1027 unsigned int col;
1028 pnm_readpnmrow(ifP, xelrow, cols, maxval, format);
1029 for (col = 0; col < cols && !foundTransparentPixel; ++col) {
1030 if (alphaMask[row][col] == 0) {
1031 foundTransparentPixel = true;
1032 transcolor = pnm_xeltopixel(xelrow[col], format);
1033 }
1034 }
1035 }
1036 } else
1037 foundTransparentPixel = false;
1038
1039 pnm_freerow(xelrow);
1040
1041 *allOpaqueP = !foundNonOpaquePixel;
1042
1043 if (foundTransparentPixel) {
1044 tryTransparentColor(ifP, rasterPos, cols, rows, maxval, format,
1045 alphaMask, alphaMaxval, transcolor,
1046 singleColorIsTransP);
1047 *alphaTranscolorP = transcolor;
1048 } else
1049 *singleColorIsTransP = false;
1050 }
1051
1052
1053
1054 static void
1055 determineTransparency(struct cmdlineInfo const cmdline,
1056 FILE * const ifP,
1057 pm_filepos const rasterPos,
1058 unsigned int const cols,
1059 unsigned int const rows,
1060 xelval const maxval,
1061 int const format,
1062 FILE * const afP,
1063 bool * const alphaP,
1064 int * const transparentP,
1065 pixel * const transColorP,
1066 bool * const transExactP,
1067 gray *** const alphaMaskP,
1068 gray * const alphaMaxvalP) {
1069 /*----------------------------------------------------------------------------
1070 Determine the various aspects of transparency we need to generate the
1071 PNG.
1072
1073 Note that there are two kinds of transparency: pixel-by-pixel
1074 transparency/translucency with an alpha mask and all pixels of a certain
1075 color being transparent. Both these exist both in input from the user and
1076 as representations in the PNG -- i.e. user may supply an alpha mask,
1077 or identify a transparent color and the PNG may contain an alpha mask
1078 or identify a transparent color.
1079
1080 We return as *transparentP:
1081
1082 -1 PNG is not to have single-color transparency
1083 1 PNG is to have single-color transparency as directed by user
1084 2 PNG is to have single-color transparency that effects an alpha
1085 mask that the user supplied.
1086
1087 In the cases where there is to be single-color transparency, *transColorP
1088 is that color.
1089 -----------------------------------------------------------------------------*/
1090 if (cmdline.alpha) {
1091 pixel alphaTranscolor;
1092 bool alphaCanBeTransparencyIndex;
1093 bool allOpaque;
1094 int alphaCols, alphaRows;
1095 gray alphaMaxval;
1096 gray ** alphaMask;
1097
1098 if (verbose)
1099 pm_message("reading alpha-channel image...");
1100 alphaMask = pgm_readpgm(afP, &alphaCols, &alphaRows, &alphaMaxval);
1101
1102 if (alphaCols != cols || alphaRows != rows) {
1103 pm_error("dimensions for image and alpha mask do not agree");
1104 }
1105 analyzeAlpha(ifP, rasterPos, cols, rows, maxval, format,
1106 alphaMask, alphaMaxval, &allOpaque,
1107 &alphaCanBeTransparencyIndex, &alphaTranscolor);
1108
1109 if (alphaCanBeTransparencyIndex && !cmdline.force) {
1110 if (verbose)
1111 pm_message("converting alpha mask to transparency index");
1112 *alphaP = false;
1113 *transparentP = 2;
1114 *transColorP = alphaTranscolor;
1115 } else if (allOpaque) {
1116 if (verbose)
1117 pm_message("Skipping alpha because mask is all opaque");
1118 *alphaP = false;
1119 *transparentP = -1;
1120 } else {
1121 *alphaP = true;
1122 *transparentP = -1;
1123 }
1124 *alphaMaxvalP = alphaMaxval;
1125 *alphaMaskP = alphaMask;
1126 } else {
1127 /* Though there's no alpha_mask, we still need an alpha_maxval for
1128 use with trans[], which can have stuff in it if the user specified
1129 a transparent color.
1130 */
1131 *alphaP = false;
1132 *alphaMaxvalP = 255;
1133
1134 if (cmdline.transparent) {
1135 const char * transstring2;
1136 /* The -transparent value, but with possible leading '=' removed */
1137 if (cmdline.transparent[0] == '=') {
1138 *transExactP = true;
1139 transstring2 = &cmdline.transparent[1];
1140 } else {
1141 *transExactP = false;
1142 transstring2 = cmdline.transparent;
1143 }
1144 /* We do this funny PPM_DEPTH thing instead of just passing 'maxval'
1145 to ppm_parsecolor() because ppm_parsecolor() does a cheap maxval
1146 scaling, and this is more precise.
1147 */
1148 PPM_DEPTH(*transColorP,
1149 ppm_parsecolor(transstring2, PNM_OVERALLMAXVAL),
1150 PNM_OVERALLMAXVAL, maxval);
1151
1152 *transparentP = 1;
1153 } else
1154 *transparentP = -1;
1155 }
1156 }
1157
1158
1159
1160 static void
1161 determineBackground(struct cmdlineInfo const cmdline,
1162 xelval const maxval,
1163 xel * const backColorP) {
1164
1165 if (cmdline.background)
1166 PPM_DEPTH(*backColorP,
1167 ppm_parsecolor(cmdline.background, PNM_OVERALLMAXVAL),
1168 PNM_OVERALLMAXVAL, maxval);;
1169 }
1170
1171
1172
1173 static bool
1174 hasColor(FILE * const ifP,
1175 unsigned int const cols,
1176 unsigned int const rows,
1177 xelval const maxval,
1178 int const format,
1179 pm_filepos const rasterPos) {
1180 /*----------------------------------------------------------------------------
1181 The image contains colors other than black, white, and gray.
1182 -----------------------------------------------------------------------------*/
1183 bool retval;
1184
1185 if (PNM_FORMAT_TYPE(format) == PPM_TYPE) {
1186 unsigned int row;
1187 xel * xelrow; /* malloc'ed */
1188 /* The row of the input image currently being analyzed */
1189 bool isGray;
1190
1191 xelrow = pnm_allocrow(cols);
1192
1193 pm_seek2(ifP, &rasterPos, sizeof(rasterPos));
1194
1195 for (row = 0, isGray = true; row < rows && isGray; ++row) {
1196 unsigned int col;
1197
1198 pnm_readpnmrow(ifP, xelrow, cols, maxval, format);
1199
1200 for (col = 0; col < cols && isGray; ++col) {
1201 xel const p = xelrow[col];
1202 if (PPM_GETR(p) != PPM_GETG(p) || PPM_GETG(p) != PPM_GETB(p))
1203 isGray = false;
1204 }
1205 }
1206
1207 pnm_freerow(xelrow);
1208
1209 retval = !isGray;
1210 } else
1211 retval = false;
1212
1213 return retval;
1214 }
1215
1216
1217
1218 static void
1219 findRedundantBits(FILE * const ifp,
1220 int const rasterPos,
1221 int const cols,
1222 int const rows,
1223 xelval const maxval,
1224 int const format,
1225 bool const alpha,
1226 bool const force,
1227 unsigned int * const meaningfulBitsP) {
1228 /*----------------------------------------------------------------------------
1229 Find out if we can use just a subset of the bits from each input
1230 sample. Often, people create an image with e.g. 8 bit samples from
1231 one that has e.g. only 4 bit samples by scaling by 255/15, which is
1232 the same as repeating the bits. E.g. 1011 becomes 10111011. We
1233 detect this case. We return as *meaningfulBitsP the minimum number
1234 of bits, starting from the least significant end, that contain
1235 original information.
1236 -----------------------------------------------------------------------------*/
1237 if (!alpha && PNM_FORMAT_TYPE(format) == PGM_TYPE && !force)
1238 meaningful_bits_pgm(ifp, rasterPos, cols, rows, maxval, format,
1239 meaningfulBitsP);
1240 else if (PNM_FORMAT_TYPE(format) == PPM_TYPE && !force)
1241 meaningful_bits_ppm(ifp, rasterPos, cols, rows, maxval, format,
1242 meaningfulBitsP);
1243 else
1244 *meaningfulBitsP = pm_maxvaltobits(maxval);
1245
1246 if (verbose && *meaningfulBitsP != pm_maxvaltobits(maxval))
1247 pm_message("Using only %d rightmost bits of input samples. The "
1248 "rest are redundant.", *meaningfulBitsP);
1249 }
1250
1251
1252
1253 static void
1254 readOrderedPalette(FILE * const pfp,
1255 xel ordered_palette[],
1256 unsigned int * const ordered_palette_size_p) {
1257
1258 xel ** xels;
1259 int cols, rows;
1260 xelval maxval;
1261 int format;
1262
1263 if (verbose)
1264 pm_message("reading ordered palette (colormap)...");
1265
1266 xels = pnm_readpnm(pfp, &cols, &rows, &maxval, &format);
1267
1268 if (PNM_FORMAT_TYPE(format) != PPM_TYPE)
1269 pm_error("ordered palette must be a PPM file, not type %d", format);
1270
1271 *ordered_palette_size_p = rows * cols;
1272 if (*ordered_palette_size_p > MAXCOLORS)
1273 pm_error("ordered-palette image contains %d pixels. Maximum is %d",
1274 *ordered_palette_size_p, MAXCOLORS);
1275 if (verbose)
1276 pm_message("%u colors found", *ordered_palette_size_p);
1277
1278 {
1279 unsigned int j;
1280 unsigned int row;
1281 j = 0; /* initial value */
1282 for (row = 0; row < rows; ++row) {
1283 int col;
1284 for (col = 0; col < cols; ++col)
1285 ordered_palette[j++] = xels[row][col];
1286 }
1287 }
1288 pnm_freearray(xels, rows);
1289 }
1290
1291
1292
1293 static void
1294 compute_nonalpha_palette(colorhist_vector const chv,
1295 int const colors,
1296 pixval const maxval,
1297 FILE * const pfp,
1298 pixel palette_pnm[],
1299 unsigned int * const paletteSizeP,
1300 gray trans_pnm[],
1301 unsigned int * const transSizeP) {
1302 /*----------------------------------------------------------------------------
1303 Compute the palette corresponding to the color set 'chv'
1304 (consisting of 'colors' distinct colors) assuming a pure-color (no
1305 transparency) palette.
1306
1307 If 'pfp' is non-null, assume it's a PPM file and read the palette
1308 from that. Make sure it contains the same colors as the palette
1309 we computed ourself would have. Caller supplied the file because he
1310 wants the colors in a particular order in the palette.
1311 -----------------------------------------------------------------------------*/
1312 unsigned int colorIndex;
1313
1314 xel ordered_palette[MAXCOLORS];
1315 unsigned int ordered_palette_size;
1316
1317 if (pfp) {
1318 readOrderedPalette(pfp, ordered_palette, &ordered_palette_size);
1319
1320 if (colors != ordered_palette_size)
1321 pm_error("sizes of ordered palette (%d) "
1322 "and existing palette (%d) differ",
1323 ordered_palette_size, colors);
1324
1325 /* Make sure the ordered palette contains all the colors in
1326 the image
1327 */
1328 for (colorIndex = 0; colorIndex < colors; colorIndex++) {
1329 int j;
1330 bool found;
1331
1332 found = false;
1333 for (j = 0; j < ordered_palette_size && !found; ++j) {
1334 if (PNM_EQUAL(ordered_palette[j], chv[colorIndex].color))
1335 found = true;
1336 }
1337 if (!found)
1338 pm_error("failed to find color (%d, %d, %d), which is in the "
1339 "input image, in the ordered palette",
1340 PPM_GETR(chv[colorIndex].color),
1341 PPM_GETG(chv[colorIndex].color),
1342 PPM_GETB(chv[colorIndex].color));
1343 }
1344 /* OK, the ordered palette passes muster as a palette; go ahead
1345 and return it as the palette.
1346 */
1347 for (colorIndex = 0; colorIndex < colors; ++colorIndex)
1348 palette_pnm[colorIndex] = ordered_palette[colorIndex];
1349 } else {
1350 for (colorIndex = 0; colorIndex < colors; ++colorIndex)
1351 palette_pnm[colorIndex] = chv[colorIndex].color;
1352 }
1353 *paletteSizeP = colors;
1354 *transSizeP = 0;
1355 }
1356
1357
1358
1359 static bool
1360 isPowerOfTwoOrZero(unsigned int const arg) {
1361
1362 unsigned int i;
1363 unsigned int mask;
1364 unsigned int nOneBit;
1365
1366 for (i = 0, mask = 0x1, nOneBit = 0;
1367 i < sizeof(arg) * 8;
1368 ++i, mask <<= 1) {
1369
1370 if (arg & mask)
1371 ++nOneBit;
1372 if (nOneBit > 1)
1373 return false;
1374 }
1375 return true;
1376 }
1377
1378
1379
1380 static void
1381 addColorAlphaPair(gray ** const alphasOfColor,
1382 unsigned int * const alphasOfColorCnt,
1383 unsigned int const colorIndex,
1384 gray const alpha) {
1385 /*----------------------------------------------------------------------------
1386 Add the pair (colorIndex, alpha) to the palette
1387 (alphasOfColor, alphasOfColorCnt).
1388 -----------------------------------------------------------------------------*/
1389 unsigned int const colorCnt = alphasOfColorCnt[colorIndex];
1390
1391 if (isPowerOfTwoOrZero(colorCnt)) {
1392 /* We've filled the current memory allocation. Expand. */
1393
1394 REALLOCARRAY(alphasOfColor[colorIndex], MAX(1, colorCnt * 2));
1395
1396 if (alphasOfColor[colorIndex] == NULL)
1397 pm_error("Out of memory allocating color/alpha palette space "
1398 "for %u alpha values for color index %u",
1399 colorCnt * 2, colorIndex);
1400 }
1401
1402 alphasOfColor[colorIndex][colorCnt] = alpha;
1403 ++alphasOfColorCnt[colorIndex];
1404 }
1405
1406
1407
1408 static void
1409 freeAlphasOfColor(gray ** const alphasOfColor,
1410 unsigned int const colorCount) {
1411
1412 unsigned int colorIndex;
1413
1414 for (colorIndex = 0; colorIndex < colorCount; ++colorIndex)
1415 free(alphasOfColor[colorIndex]);
1416 }
1417
1418
1419
1420 static void
1421 computeUnsortedAlphaPalette(FILE * const ifP,
1422 int const cols,
1423 int const rows,
1424 xelval const maxval,
1425 int const format,
1426 pm_filepos const rasterPos,
1427 gray ** const alphaMask,
1428 colorhist_vector const chv,
1429 int const colors,
1430 unsigned int const maxPaletteEntries,
1431 gray * alphasOfColor[],
1432 unsigned int alphasFirstIndex[],
1433 unsigned int alphasOfColorCnt[],
1434 bool * const tooBigP) {
1435 /*----------------------------------------------------------------------------
1436 Read the image at position 'rasterPos' in file *ifP, which is a PNM
1437 described by 'cols', 'rows', 'maxval', and 'format'.
1438
1439 Using the alpha mask 'alpha_mask' and color map 'chv' (of size 'colors')
1440 for the image, construct a palette of (color index, alpha) ordered pairs
1441 for the image, as follows.
1442
1443 The alpha/color palette is the set of all ordered pairs of
1444 (color,alpha) in the PNG, including the background color. The
1445 actual palette is an array. Each array element contains a color
1446 index from the color palette and an alpha value. All the elements
1447 with the same color index are contiguous. alphasFirstIndex[x] is
1448 the index in the alpha/color palette of the first element that has
1449 color index x. alphasOfColorCnt[x] is the number of elements that
1450 have color index x. alphasOfColor[x][y] is the yth alpha value
1451 that appears with color index x (in order of appearance).
1452
1453 The palette we produce does not go out of its way to include the
1454 background color; unless the background color is also in the image,
1455 Caller will have to add it.
1456
1457 To save time, we give up as soon as we know there are more than
1458 'maxPaletteEntries' in the palette. We return *tooBigP indicating
1459 whether that was the case.
1460 -----------------------------------------------------------------------------*/
1461 colorhash_table cht;
1462 int colorIndex;
1463 bool tooBig;
1464 int row;
1465 xel * xelrow;
1466 unsigned int alphaColorPairCnt;
1467 /* Number of different alpha/color pairs we've seen so far as we
1468 iterate through the image.
1469 */
1470
1471 cht = ppm_colorhisttocolorhash(chv, colors);
1472
1473 /* We have not seen any alphas of any color yet. */
1474 alphaColorPairCnt = 0;
1475 for (colorIndex = 0; colorIndex < colors; ++colorIndex) {
1476 alphasOfColor[colorIndex] = NULL;
1477 alphasOfColorCnt[colorIndex] = 0;
1478 }
1479
1480 pm_seek2(ifP, &rasterPos, sizeof(rasterPos));
1481
1482 xelrow = pnm_allocrow(cols);
1483
1484 tooBig = false; /* initial assumption */
1485
1486 for (row = 0; row < rows && !tooBig; ++row) {
1487 unsigned int col;
1488 pnm_readpnmrow(ifP, xelrow, cols, maxval, format);
1489 pnm_promoteformatrow(xelrow, cols, maxval, format, maxval, PPM_TYPE);
1490
1491 for (col = 0; col < cols; ++col) {
1492 unsigned int i;
1493 int const colorIndex = ppm_lookupcolor(cht, &xelrow[col]);
1494 for (i = 0 ; i < alphasOfColorCnt[colorIndex] ; ++i) {
1495 if (alphaMask[row][col] == alphasOfColor[colorIndex][i])
1496 break;
1497 }
1498 if (i == alphasOfColorCnt[colorIndex]) {
1499 if (alphaColorPairCnt >= maxPaletteEntries) {
1500 tooBig = true;
1501 break;
1502 } else {
1503 addColorAlphaPair(alphasOfColor, alphasOfColorCnt,
1504 colorIndex, alphaMask[row][col]);
1505 ++alphaColorPairCnt;
1506 }
1507 }
1508 }
1509 }
1510 if (tooBig)
1511 freeAlphasOfColor(alphasOfColor, colors);
1512 else {
1513 unsigned int i;
1514 alphasFirstIndex[0] = 0;
1515 for (i = 1; i < colors; ++i)
1516 alphasFirstIndex[i] = alphasFirstIndex[i-1] +
1517 alphasOfColorCnt[i-1];
1518 }
1519 pnm_freerow(xelrow);
1520 ppm_freecolorhash(cht);
1521
1522 *tooBigP = tooBig;
1523 }
1524
1525
1526
1527 static void
1528 sortAlphaPalette(gray * const alphasOfColor[],
1529 unsigned int const alphasFirstIndex[],
1530 unsigned int const alphasOfColorCnt[],
1531 unsigned int const colors,
1532 gray const alphaMaxval,
1533 unsigned int mapping[],
1534 unsigned int * const transSizeP) {
1535 /*----------------------------------------------------------------------------
1536 Remap the palette indices so opaque entries are last.
1537
1538 This is _not_ a sort in place -- we do not modify our inputs.
1539
1540 alphas_of_color[], alphas_first_index[], and alphas_of_color_cnt[]
1541 describe an unsorted PNG (alpha/color) palette. We generate
1542 mapping[] such that mapping[x] is the index into the sorted PNG
1543 palette of the alpha/color pair whose index is x in the unsorted
1544 PNG palette. This mapping sorts the palette so that opaque entries
1545 are last.
1546
1547 The unsorted PNG palette is sorted enough that all entries for a particular
1548 color (with varying transparencies) are contiguous. alphasFirstIndex[x] is
1549 the index in the unsorted PNG palette of the first entry with color x
1550 (where x is an index into some other palette). alphasOfColorCnt[x] is the
1551 number of non-opaque entries in the unsorted PNG palette with color x.
1552
1553 alphasOfColor[x][y] is the y'th alpha value for color x, in no particular
1554 order.
1555
1556 Return as *transSizeP the number of non-opaque entries in the palette
1557 (i.e. the index in the palette of the first opaque entry).
1558 -----------------------------------------------------------------------------*/
1559 if (colors == 0)
1560 *transSizeP = 0;
1561 else {
1562 unsigned int bot_idx;
1563 unsigned int top_idx;
1564 unsigned int colorIndex;
1565
1566 /* We start one index at the bottom of the palette index range
1567 and another at the top. We run through the unsorted palette,
1568 and when we see an opaque entry, we map it to the current top
1569 cursor and bump it down. When we see a non-opaque entry, we map
1570 it to the current bottom cursor and bump it up. Because the input
1571 and output palettes are the same size, the two cursors should meet
1572 right when we process the last entry of the unsorted palette.
1573 */
1574 bot_idx = 0;
1575 top_idx = alphasFirstIndex[colors-1] + alphasOfColorCnt[colors-1] - 1;
1576
1577 for (colorIndex = 0; colorIndex < colors; ++colorIndex) {
1578 unsigned int j;
1579 for (j = 0; j < alphasOfColorCnt[colorIndex]; ++j) {
1580 unsigned int const paletteIndex =
1581 alphasFirstIndex[colorIndex] + j;
1582 if (alphasOfColor[colorIndex][j] == alphaMaxval)
1583 mapping[paletteIndex] = top_idx--;
1584 else
1585 mapping[paletteIndex] = bot_idx++;
1586 }
1587 }
1588 /* indices should have just crossed paths */
1589 if (bot_idx != top_idx + 1) {
1590 pm_error ("internal inconsistency: "
1591 "remapped bot_idx = %u, top_idx = %u",
1592 bot_idx, top_idx);
1593 }
1594 *transSizeP = bot_idx;
1595 }
1596 }
1597
1598
1599
1600 static void
1601 compute_alpha_palette(FILE * const ifP,
1602 int const cols,
1603 int const rows,
1604 xelval const maxval,
1605 int const format,
1606 pm_filepos const rasterPos,
1607 gray ** const alpha_mask,
1608 gray const alphaMaxval,
1609 pixel palette_pnm[],
1610 gray trans_pnm[],
1611 unsigned int * const paletteSizeP,
1612 unsigned int * const transSizeP,
1613 bool * const tooBigP) {
1614 /*----------------------------------------------------------------------------
1615 Return the palette of color/alpha pairs for the image indicated by
1616 'ifP', 'cols', 'rows', 'maxval', 'format', and 'rasterPos'.
1617 alpha_mask[] is the Netpbm-style alpha mask for the image.
1618
1619 Return the palette as the arrays palette_pnm[] and trans_pnm[].
1620 The ith entry in the palette is the combination of palette_pnm[i],
1621 which defines the color, and trans_pnm[i], which defines the
1622 transparency.
1623
1624 Return the number of entries in the palette as *paletteSizeP.
1625
1626 The palette is sorted so that the opaque entries are last, and we return
1627 *transSizeP as the number of non-opaque entries.
1628
1629 palette[] and trans[] are allocated by the caller to at least
1630 MAXPALETTEENTRIES elements.
1631
1632 If there are more than MAXPALETTEENTRIES color/alpha pairs in the image,
1633 don't return any palette information -- just return *tooBigP == true.
1634 -----------------------------------------------------------------------------*/
1635 colorhist_vector chv;
1636 unsigned int colors;
1637
1638 gray * alphas_of_color[MAXPALETTEENTRIES];
1639 unsigned int alphas_first_index[MAXPALETTEENTRIES];
1640 unsigned int alphas_of_color_cnt[MAXPALETTEENTRIES];
1641
1642 getChv(ifP, rasterPos, cols, rows, maxval, format, MAXCOLORS,
1643 &chv, &colors);
1644
1645 assert(colors <= ARRAY_SIZE(alphas_of_color));
1646
1647 computeUnsortedAlphaPalette(ifP, cols, rows, maxval, format, rasterPos,
1648 alpha_mask, chv, colors,
1649 MAXPALETTEENTRIES,
1650 alphas_of_color,
1651 alphas_first_index,
1652 alphas_of_color_cnt,
1653 tooBigP);
1654
1655 if (!*tooBigP) {
1656 unsigned int mapping[MAXPALETTEENTRIES];
1657 /* Sorting of the alpha/color palette. mapping[x] is the
1658 index into the sorted PNG palette of the alpha/color
1659 pair whose index is x in the unsorted PNG palette.
1660 This mapping sorts the palette so that opaque entries
1661 are last.
1662 */
1663
1664 *paletteSizeP = colors == 0 ?
1665 0 :
1666 alphas_first_index[colors-1] + alphas_of_color_cnt[colors-1];
1667 assert(*paletteSizeP <= MAXPALETTEENTRIES);
1668
1669 /* Make the opaque palette entries last */
1670 sortAlphaPalette(alphas_of_color, alphas_first_index,
1671 alphas_of_color_cnt, colors, alphaMaxval,
1672 mapping, transSizeP);
1673
1674 {
1675 unsigned int colorIndex;
1676
1677 for (colorIndex = 0; colorIndex < colors; ++colorIndex) {
1678 unsigned int j;
1679 for (j = 0; j < alphas_of_color_cnt[colorIndex]; ++j) {
1680 unsigned int const paletteIndex =
1681 alphas_first_index[colorIndex] + j;
1682 palette_pnm[mapping[paletteIndex]] = chv[colorIndex].color;
1683 trans_pnm[mapping[paletteIndex]] =
1684 alphas_of_color[colorIndex][j];
1685 }
1686 }
1687 }
1688 freeAlphasOfColor(alphas_of_color, colors);
1689 }
1690 }
1691
1692
1693
1694 static void
1695 makeOneColorTransparentInPalette(xel const transColor,
1696 bool const exact,
1697 pixel palette_pnm[],
1698 unsigned int const paletteSize,
1699 gray trans_pnm[],
1700 unsigned int * const transSizeP) {
1701 /*----------------------------------------------------------------------------
1702 Find the color 'transColor' in the color/alpha palette defined by
1703 palette_pnm[], paletteSize, trans_pnm[] and *transSizeP.
1704
1705 Make that entry fully transparent.
1706
1707 Rearrange the palette so that that entry is first. (The PNG compressor
1708 can do a better job when the opaque entries are all last in the
1709 color/alpha palette).
1710
1711 If the specified color is not there and exact == true, return
1712 without changing anything, but issue a warning message. If it's
1713 not there and exact == false, just find the closest color.
1714
1715 We assume every entry in the palette is opaque upon entry.
1716
1717 A valid palette has at least one color.
1718 -----------------------------------------------------------------------------*/
1719 unsigned int transparentIndex;
1720 unsigned int distance;
1721
1722 assert(paletteSize > 0);
1723
1724 if (*transSizeP != 0)
1725 pm_error("Internal error: trying to make a color in the palette "
1726 "transparent where there already is one.");
1727
1728 closestColorInPalette(transColor, palette_pnm, paletteSize,
1729 &transparentIndex, &distance);
1730
1731 if (distance != 0 && exact) {
1732 pm_message("specified transparent color not present in palette; "
1733 "ignoring -transparent");
1734 errorlevel = PNMTOPNG_WARNING_LEVEL;
1735 } else {
1736 /* Swap this with the first entry in the palette */
1737 pixel tmp;
1738
1739 tmp = palette_pnm[transparentIndex];
1740 palette_pnm[transparentIndex] = palette_pnm[0];
1741 palette_pnm[0] = tmp;
1742
1743 /* Make it transparent */
1744 trans_pnm[0] = PGM_TRANSPARENT;
1745 *transSizeP = 1;
1746 if (verbose) {
1747 pixel const p = palette_pnm[0];
1748 pm_message("Making all occurrences of color (%u, %u, %u) "
1749 "transparent.",
1750 PPM_GETR(p), PPM_GETG(p), PPM_GETB(p));
1751 }
1752 }
1753 }
1754
1755
1756
1757 static void
1758 findOrAddBackgroundInPalette(pixel const backColor,
1759 pixel palette_pnm[],
1760 unsigned int * const paletteSizeP,
1761 unsigned int * const backgroundIndexP) {
1762 /*----------------------------------------------------------------------------
1763 Add the background color 'backColor' to the palette, unless
1764 it's already in there. If it's not present and there's no room to
1765 add it, choose a background color that's already in the palette,
1766 as close to 'backColor' as possible.
1767
1768 If we add an entry to the palette, make it opaque. But in searching the
1769 existing palette, ignore transparency.
1770
1771 Note that PNG specs say that transparency of the background is meaningless;
1772 i.e. a viewer must ignore the transparency of the palette entry when
1773 using the background color.
1774
1775 Return the palette index of the background color as *backgroundIndexP.
1776 -----------------------------------------------------------------------------*/
1777 int backgroundIndex; /* negative means not found */
1778 unsigned int paletteIndex;
1779
1780 backgroundIndex = -1;
1781 for (paletteIndex = 0;
1782 paletteIndex < *paletteSizeP;
1783 ++paletteIndex)
1784 if (PPM_EQUAL(palette_pnm[paletteIndex], backColor))
1785 backgroundIndex = paletteIndex;
1786
1787 if (backgroundIndex >= 0) {
1788 /* The background color is already in the palette. */
1789 *backgroundIndexP = backgroundIndex;
1790 if (verbose) {
1791 pixel const p = palette_pnm[*backgroundIndexP];
1792 pm_message("background color (%u, %u, %u) appears in image.",
1793 PPM_GETR(p), PPM_GETG(p), PPM_GETB(p));
1794 }
1795 } else {
1796 /* Try to add the background color, opaque, to the palette. */
1797 if (*paletteSizeP < MAXCOLORS) {
1798 /* There's room, so just add it to the end of the palette */
1799
1800 /* Because we're not expanding the transparency palette, this
1801 entry is not in it, and is thus opaque.
1802 */
1803 *backgroundIndexP = (*paletteSizeP)++;
1804 palette_pnm[*backgroundIndexP] = backColor;
1805 if (verbose) {
1806 pixel const p = palette_pnm[*backgroundIndexP];
1807 pm_message("added background color (%u, %u, %u) to palette.",
1808 PPM_GETR(p), PPM_GETG(p), PPM_GETB(p));
1809 }
1810 } else {
1811 closestColorInPalette(backColor, palette_pnm, *paletteSizeP,
1812 backgroundIndexP, NULL);
1813 errorlevel = PNMTOPNG_WARNING_LEVEL;
1814 {
1815 pixel const p = palette_pnm[*backgroundIndexP];
1816 pm_message("no room in palette for background color; "
1817 "using closest match (%u, %u, %u) instead",
1818 PPM_GETR(p), PPM_GETG(p), PPM_GETB(p));
1819 }
1820 }
1821 }
1822 }
1823
1824
1825
1826 static void
1827 buildColorLookup(pixel palette_pnm[],
1828 unsigned int const paletteSize,
1829 colorhash_table * const chtP) {
1830 /*----------------------------------------------------------------------------
1831 Create a colorhash_table out of the palette described by
1832 palette_pnm[] (which has 'paletteSize' entries) so one can look up
1833 the palette index of a given color.
1834
1835 Where the same color appears twice in the palette, the lookup table
1836 finds an arbitrary one of them. We don't consider transparency of
1837 palette entries, so if the same color appears in the palette once
1838 transparent and once opaque, the lookup table finds an arbitrary one
1839 of those two.
1840 -----------------------------------------------------------------------------*/
1841 colorhash_table const cht = ppm_alloccolorhash();
1842 unsigned int paletteIndex;
1843
1844 for (paletteIndex = 0; paletteIndex < paletteSize; ++paletteIndex) {
1845 ppm_addtocolorhash(cht, &palette_pnm[paletteIndex], paletteIndex);
1846 }
1847 *chtP = cht;
1848 }
1849
1850
1851
1852 static void
1853 buildColorAlphaLookup(pixel palettePnm[],
1854 unsigned int const paletteSize,
1855 gray transPnm[],
1856 unsigned int const transSize,
1857 gray const alphaMaxval,
1858 coloralphahash_table * const cahtP) {
1859
1860 coloralphahash_table const caht = alloccoloralphahash();
1861
1862 unsigned int paletteIndex;
1863
1864 for (paletteIndex = 0; paletteIndex < paletteSize; ++paletteIndex) {
1865 gray paletteTrans;
1866
1867 if (paletteIndex < transSize)
1868 paletteTrans = transPnm[paletteIndex];
1869 else
1870 paletteTrans = alphaMaxval;
1871
1872 addtocoloralphahash(caht, &palettePnm[paletteIndex],
1873 &paletteTrans, paletteIndex);
1874 }
1875 *cahtP = caht;
1876 }
1877
1878
1879
1880 static void
1881 tryAlphaPalette(FILE * const ifP,
1882 int const cols,
1883 int const rows,
1884 xelval const maxval,
1885 int const format,
1886 pm_filepos const rasterPos,
1887 gray ** const alpha_mask,
1888 gray const alphaMaxval,
1889 FILE * const pfP,
1890 pixel * const palette_pnm,
1891 unsigned int * const paletteSizeP,
1892 gray * const trans_pnm,
1893 unsigned int * const transSizeP,
1894 const char ** const impossibleReasonP) {
1895 /*----------------------------------------------------------------------------
1896 Try to make an alpha palette as 'trans_pnm', size *transSizeP.
1897
1898 If it's impossible, return as *impossibleReasonP newly malloced storage
1899 containing text that tells why. But if we succeed, return
1900 *impossibleReasonP == NULL.
1901 -----------------------------------------------------------------------------*/
1902 bool tooBig;
1903 if (pfP)
1904 pm_error("This program is not capable of generating "
1905 "a PNG with transparency when you specify "
1906 "the palette with -palette.");
1907
1908 compute_alpha_palette(ifP, cols, rows, maxval, format,
1909 rasterPos, alpha_mask, alphaMaxval,
1910 palette_pnm, trans_pnm,
1911 paletteSizeP, transSizeP, &tooBig);
1912 if (tooBig) {
1913 pm_asprintf(impossibleReasonP,
1914 "too many color/transparency pairs "
1915 "(more than the PNG maximum of %u",
1916 MAXPALETTEENTRIES);
1917 } else
1918 *impossibleReasonP = NULL;
1919 }
1920
1921
1922
1923 static void
1924 computePixelWidth(bool const colorPng,
1925 unsigned int const pnmMeaningfulBitCt,
1926 bool const alpha,
1927 unsigned int * const bitsPerSampleP,
1928 unsigned int * const bitsPerPixelP) {
1929
1930 unsigned int bitsPerSample, bitsPerPixel;
1931
1932 if (colorPng || alpha) {
1933 /* PNG allows only depths of 8 and 16 for a truecolor image
1934 and for a grayscale image with an alpha channel.
1935 */
1936 if (pnmMeaningfulBitCt > 8)
1937 bitsPerSample = 16;
1938 else
1939 bitsPerSample = 8;
1940 } else {
1941 /* A grayscale, non-colormapped, no-alpha PNG may have any
1942 bit depth from 1 to 16
1943 */
1944 if (pnmMeaningfulBitCt > 8)
1945 bitsPerSample = 16;
1946 else if (pnmMeaningfulBitCt > 4)
1947 bitsPerSample = 8;
1948 else if (pnmMeaningfulBitCt > 2)
1949 bitsPerSample = 4;
1950 else if (pnmMeaningfulBitCt > 1)
1951 bitsPerSample = 2;
1952 else
1953 bitsPerSample = 1;
1954 }
1955 if (alpha) {
1956 if (colorPng)
1957 bitsPerPixel = 4 * bitsPerSample;
1958 else
1959 bitsPerPixel = 2 * bitsPerSample;
1960 } else {
1961 if (colorPng)
1962 bitsPerPixel = 3 * bitsPerSample;
1963 else
1964 bitsPerPixel = bitsPerSample;
1965 }
1966 if (bitsPerPixelP)
1967 *bitsPerPixelP = bitsPerPixel;
1968 if (bitsPerSampleP)
1969 *bitsPerSampleP = bitsPerSample;
1970 }
1971
1972
1973
1974 static unsigned int
1975 paletteIndexBits(unsigned int const nColors) {
1976 /*----------------------------------------------------------------------------
1977 Return the number of bits that a palette index in the PNG will
1978 occupy given that the palette has 'nColors' colors in it. It is 1,
1979 2, 4, or 8 bits.
1980
1981 If 'nColors' is not a valid PNG palette size, return 0.
1982 -----------------------------------------------------------------------------*/
1983 unsigned int retval;
1984
1985 if (nColors < 1)
1986 retval = 0;
1987 else if (nColors <= 2)
1988 retval = 1;
1989 else if (nColors <= 4)
1990 retval = 2;
1991 else if (nColors <= 16)
1992 retval = 4;
1993 else if (nColors <= 256)
1994 retval = 8;
1995 else
1996 retval = 0;
1997
1998 return retval;
1999 }
2000
2001
2002
2003 static void
2004 computeColorMap(FILE * const ifP,
2005 pm_filepos const rasterPos,
2006 int const cols,
2007 int const rows,
2008 xelval const maxval,
2009 bool const colorPng,
2010 int const format,
2011 bool const force,
2012 FILE * const pfP,
2013 bool const alpha,
2014 bool const transparent,
2015 pixel const transcolor,
2016 bool const transexact,
2017 bool const background,
2018 pixel const backcolor,
2019 gray ** const alpha_mask,
2020 gray const alphaMaxval,
2021 unsigned int const pnm_meaningful_bits,
2022 /* Outputs */
2023 pixel * const palette_pnm,
2024 unsigned int * const paletteSizeP,
2025 gray * const trans_pnm,
2026 unsigned int * const transSizeP,
2027 unsigned int * const backgroundIndexP,
2028 const char ** const noColormapReasonP) {
2029 /*---------------------------------------------------------------------------
2030 Determine whether to do a colormapped or truecolor PNG and if
2031 colormapped, compute the full PNG palette -- both color and
2032 transparency.
2033
2034 If we decide to do truecolor, we return as *noColormapReasonP a text
2035 description of why, in newly malloced memory. If we decide to go
2036 with colormapped, we return *noColormapReasonP == NULL.
2037
2038 In the colormapped case, we return the palette as arrays
2039 palette_pnm[] and trans_pnm[], allocated by Caller, with sizes
2040 *paletteSizeP and *transSizeP.
2041
2042 'pfP' is a handle to the file that the user requested be used for the
2043 palette (it's a Netpbm image whose colors are the colors of the palette).
2044 'pfP' is null if the user did not request a particular palette.
2045
2046 'background' means the image is to have a background color, and that
2047 color is 'backcolor'. 'backcolor' is meaningless when 'background'
2048 is false.
2049
2050 If the image is to have a background color, we return the palette index
2051 of that color as *backgroundIndexP.
2052
2053 'colorPng' means the PNG will be of the RGB variety.
2054 -------------------------------------------------------------------------- */
2055 if (force)
2056 pm_asprintf(noColormapReasonP, "You requested no color map");
2057 else if (maxval > PALETTEMAXVAL)
2058 pm_asprintf(noColormapReasonP, "The maxval of the input image (%u) "
2059 "exceeds the PNG palette maxval (%u)",
2060 maxval, PALETTEMAXVAL);
2061 else {
2062 unsigned int bitsPerPixel;
2063 computePixelWidth(colorPng, pnm_meaningful_bits, alpha,
2064 NULL, &bitsPerPixel);
2065
2066 if (!pfP && bitsPerPixel == 1)
2067 /* No palette can beat 1 bit per pixel -- no need to waste time
2068 counting the colors.
2069 */
2070 pm_asprintf(noColormapReasonP, "pixel is already only 1 bit");
2071 else {
2072 /* We'll have to count the colors ('colors') to know if a
2073 palette is possible and desirable. Along the way, we'll
2074 compute the actual set of colors (chv) too, and then create
2075 the palette itself if we decide we want one.
2076 */
2077 colorhist_vector chv;
2078 unsigned int colors;
2079
2080 getChv(ifP, rasterPos, cols, rows, maxval, format, MAXCOLORS,
2081 &chv, &colors);
2082
2083 if (chv == NULL) {
2084 pm_asprintf(noColormapReasonP,
2085 "More than %u colors found -- too many for a "
2086 "colormapped PNG", MAXCOLORS);
2087 } else {
2088 /* There are few enough colors that a palette is possible */
2089 if (bitsPerPixel <= paletteIndexBits(colors) && !pfP)
2090 pm_asprintf(noColormapReasonP,
2091 "palette index for %u colors would be "
2092 "no smaller than the indexed value (%u bits)",
2093 colors, bitsPerPixel);
2094 else {
2095 unsigned int paletteSize;
2096 unsigned int transSize;
2097 if (alpha)
2098 tryAlphaPalette(ifP, cols, rows, maxval, format,
2099 rasterPos, alpha_mask, alphaMaxval,
2100 pfP,
2101 palette_pnm, &paletteSize,
2102 trans_pnm, &transSize,
2103 noColormapReasonP);
2104
2105 else {
2106 *noColormapReasonP = NULL;
2107
2108 compute_nonalpha_palette(chv, colors, maxval, pfP,
2109 palette_pnm, &paletteSize,
2110 trans_pnm, &transSize);
2111
2112 if (transparent)
2113 makeOneColorTransparentInPalette(
2114 transcolor, transexact,
2115 palette_pnm, paletteSize, trans_pnm,
2116 &transSize);
2117 }
2118 if (!*noColormapReasonP) {
2119 if (background)
2120 findOrAddBackgroundInPalette(
2121 backcolor, palette_pnm, &paletteSize,
2122 backgroundIndexP);
2123 *paletteSizeP = paletteSize;
2124 *transSizeP = transSize;
2125 }
2126 }
2127 }
2128 freeChv();
2129 }
2130 }
2131 }
2132
2133
2134
2135 static void computeColorMapLookupTable(
2136 bool const colorMapped,
2137 pixel palette_pnm[],
2138 unsigned int const palette_size,
2139 gray trans_pnm[],
2140 unsigned int const trans_size,
2141 bool const alpha,
2142 xelval const alpha_maxval,
2143 colorhash_table * const chtP,
2144 coloralphahash_table * const cahtP) {
2145 /*----------------------------------------------------------------------------
2146 Compute applicable lookup tables for the palette index. If there's no
2147 alpha mask, this is just a standard Netpbm colorhash_table. If there's
2148 an alpha mask, it is the slower Pnmtopng-specific
2149 coloralphahash_table.
2150
2151 If a lookup table is not applicable to the image, return NULL as
2152 its address. (If the image is not colormapped, both will be NULL).
2153 -----------------------------------------------------------------------------*/
2154 if (colorMapped) {
2155 if (alpha) {
2156 buildColorAlphaLookup(palette_pnm, palette_size,
2157 trans_pnm, trans_size, alpha_maxval, cahtP);
2158 *chtP = NULL;
2159 } else {
2160 buildColorLookup(palette_pnm, palette_size, chtP);
2161 *cahtP = NULL;
2162 }
2163 if (verbose)
2164 pm_message("PNG palette has %u entries, %u of them non-opaque",
2165 palette_size, trans_size);
2166 } else {
2167 *chtP = NULL;
2168 *cahtP = NULL;
2169 }
2170 }
2171
2172
2173
2174 static void
2175 computeRasterWidth(bool const colorMapped,
2176 unsigned int const paletteSize,
2177 bool const colorPng,
2178 unsigned int const pnmMeaningfulBitCt,
2179 bool const alpha,
2180 unsigned int * const bitsPerSampleP,
2181 unsigned int * const bitsPerPixelP) {
2182 /*----------------------------------------------------------------------------
2183 Compute the number of bits per raster sample and per raster pixel:
2184 *bitsPerSampleP and *bitsPerPixelP. Note that a raster element may be a
2185 palette index, or a gray value or color with or without alpha mask.
2186 -----------------------------------------------------------------------------*/
2187 if (colorMapped) {
2188 /* The raster element is a palette index */
2189 if (paletteSize <= 2)
2190 *bitsPerSampleP = 1;
2191 else if (paletteSize <= 4)
2192 *bitsPerSampleP = 2;
2193 else if (paletteSize <= 16)
2194 *bitsPerSampleP = 4;
2195 else
2196 *bitsPerSampleP = 8;
2197 *bitsPerPixelP = *bitsPerSampleP;
2198 if (verbose)
2199 pm_message("Writing %u-bit color indexes", *bitsPerSampleP);
2200 } else {
2201 /* The raster element is an explicit pixel -- color and transparency */
2202 computePixelWidth(colorPng, pnmMeaningfulBitCt, alpha,
2203 bitsPerSampleP, bitsPerPixelP);
2204
2205 if (verbose)
2206 pm_message("Writing %u bits per component per pixel",
2207 *bitsPerSampleP);
2208 }
2209 }
2210
2211
2212
2213 static void
2214 createPngPalette(pixel palette_pnm[],
2215 unsigned int const paletteSize,
2216 pixval const maxval,
2217 gray trans_pnm[],
2218 unsigned int const transSize,
2219 gray alpha_maxval,
2220 png_color palette[],
2221 png_byte trans[]) {
2222 /*----------------------------------------------------------------------------
2223 Create the data structure to be passed to the PNG compressor to represent
2224 the palette -- the whole palette, color + transparency.
2225
2226 This is basically just a maxval conversion from the Netpbm-format
2227 equivalents we get as input.
2228 -----------------------------------------------------------------------------*/
2229 unsigned int i;
2230
2231 for (i = 0; i < paletteSize; ++i) {
2232 pixel p;
2233 PPM_DEPTH(p, palette_pnm[i], maxval, PALETTEMAXVAL);
2234 palette[i].red = PPM_GETR(p);
2235 palette[i].green = PPM_GETG(p);
2236 palette[i].blue = PPM_GETB(p);
2237 }
2238
2239 for (i = 0; i < transSize; ++i) {
2240 unsigned int const newmv = PALETTEMAXVAL;
2241 unsigned int const oldmv = alpha_maxval;
2242 trans[i] = ROUNDDIV(trans_pnm[i] * newmv, oldmv);
2243 }
2244 }
2245
2246
2247
2248 static void
2249 setZlibCompression(struct pngx * const pngxP,
2250 struct zlibCompression const zlibCompression) {
2251
2252 if (zlibCompression.levelSpec)
2253 png_set_compression_level(pngxP->png_ptr, zlibCompression.level);
2254
2255 if (zlibCompression.memLevelSpec)
2256 png_set_compression_mem_level(pngxP->png_ptr,
2257 zlibCompression.mem_level);
2258
2259 if (zlibCompression.strategySpec)
2260 png_set_compression_strategy(pngxP->png_ptr, zlibCompression.strategy);
2261
2262 if (zlibCompression.windowBitsSpec)
2263 png_set_compression_window_bits(pngxP->png_ptr,
2264 zlibCompression.window_bits);
2265
2266 if (zlibCompression.methodSpec)
2267 png_set_compression_method(pngxP->png_ptr, zlibCompression.method);
2268
2269 if (zlibCompression.bufferSizeSpec) {
2270 pngx_setCompressionSize(pngxP, zlibCompression.buffer_size);
2271 }
2272 }
2273
2274
2275
2276 static void
2277 makePngLine(png_byte * const line,
2278 const xel * const xelrow,
2279 unsigned int const cols,
2280 xelval const maxval,
2281 bool const alpha,
2282 gray * const alpha_mask,
2283 colorhash_table const cht,
2284 coloralphahash_table const caht,
2285 struct pngx * const pngxP,
2286 xelval const png_maxval,
2287 unsigned int const depth) {
2288
2289 unsigned int col;
2290 png_byte *pp;
2291
2292 pp = line; /* start at beginning of line */
2293 for (col = 0; col < cols; ++col) {
2294 xel p_png;
2295 xel const p = xelrow[col];
2296 PPM_DEPTH(p_png, p, maxval, png_maxval);
2297 if (pngx_colorType(pngxP) == PNG_COLOR_TYPE_GRAY ||
2298 pngx_colorType(pngxP) == PNG_COLOR_TYPE_GRAY_ALPHA) {
2299 if (depth == 16)
2300 *pp++ = PNM_GET1(p_png) >> 8;
2301 *pp++ = PNM_GET1(p_png) & 0xff;
2302 } else if (pngx_colorType(pngxP) == PNG_COLOR_TYPE_PALETTE) {
2303 unsigned int paletteIndex;
2304 if (alpha)
2305 paletteIndex = lookupColorAlpha(caht, &p, &alpha_mask[col]);
2306 else
2307 paletteIndex = ppm_lookupcolor(cht, &p);
2308 *pp++ = paletteIndex;
2309 } else if (pngx_colorType(pngxP) == PNG_COLOR_TYPE_RGB ||
2310 pngx_colorType(pngxP) == PNG_COLOR_TYPE_RGB_ALPHA) {
2311 if (depth == 16)
2312 *pp++ = PPM_GETR(p_png) >> 8;
2313 *pp++ = PPM_GETR(p_png) & 0xff;
2314 if (depth == 16)
2315 *pp++ = PPM_GETG(p_png) >> 8;
2316 *pp++ = PPM_GETG(p_png) & 0xff;
2317 if (depth == 16)
2318 *pp++ = PPM_GETB(p_png) >> 8;
2319 *pp++ = PPM_GETB(p_png) & 0xff;
2320 } else
2321 pm_error("INTERNAL ERROR: undefined color_type");
2322
2323 if (pngx_colorType(pngxP) & PNG_COLOR_MASK_ALPHA) {
2324 int const png_alphaval = (int)
2325 alpha_mask[col] * (float) png_maxval / maxval + 0.5;
2326 if (depth == 16)
2327 *pp++ = png_alphaval >> 8;
2328 *pp++ = png_alphaval & 0xff;
2329 }
2330 }
2331 }
2332
2333
2334
2335 static void
2336 writeRaster(struct pngx * const pngxP,
2337 FILE * const ifP,
2338 pm_filepos const rasterPos,
2339 unsigned int const cols,
2340 unsigned int const rows,
2341 xelval const maxval,
2342 int const format,
2343 xelval const png_maxval,
2344 unsigned int const depth,
2345 bool const alpha,
2346 gray ** const alpha_mask,
2347 colorhash_table const cht,
2348 coloralphahash_table const caht
2349 ) {
2350 /*----------------------------------------------------------------------------
2351 Write the PNG raster via compressor *pngxP, reading the PNM raster
2352 from file *ifP, position 'rasterPos'.
2353
2354 The PNG raster consists of IDAT chunks.
2355
2356 'alpha_mask' is defined only if 'alpha' is true.
2357 -----------------------------------------------------------------------------*/
2358 xel * xelrow;
2359 png_byte * line;
2360 unsigned int pass;
2361
2362 xelrow = pnm_allocrow(cols);
2363
2364 /* max: 3 color channels, one alpha channel, 16-bit */
2365 MALLOCARRAY(line, cols * 8);
2366 if (line == NULL)
2367 pm_error("out of memory allocating PNG row buffer for %u columns",
2368 cols);
2369
2370 for (pass = 0; pass < pngxP->numPassesRequired; ++pass) {
2371 unsigned int row;
2372 pm_seek2(ifP, &rasterPos, sizeof(rasterPos));
2373 for (row = 0; row < rows; ++row) {
2374 pnm_readpnmrow(ifP, xelrow, cols, maxval, format);
2375 pnm_promoteformatrow(xelrow, cols, maxval, format, maxval,
2376 PPM_TYPE);
2377
2378 makePngLine(line, xelrow, cols, maxval,
2379 alpha, alpha ? alpha_mask[row] : NULL,
2380 cht, caht, pngxP, png_maxval, depth);
2381
2382 pngx_writeRow(pngxP, line);
2383 }
2384 }
2385 free(line);
2386 pnm_freerow(xelrow);
2387 }
2388
2389
2390
2391 static void
2392 doHistChunk(struct pngx * const pngxP,
2393 bool const histRequested,
2394 pixel const palettePnm[],
2395 FILE * const ifP,
2396 pm_filepos const rasterPos,
2397 unsigned int const cols,
2398 unsigned int const rows,
2399 xelval const maxval,
2400 int const format,
2401 bool const verbose) {
2402
2403 if (histRequested) {
2404 colorhist_vector chv;
2405 unsigned int colorCt;
2406 colorhash_table cht;
2407
2408 getChv(ifP, rasterPos, cols, rows, maxval, format, MAXCOLORS,
2409 &chv, &colorCt);
2410
2411 cht = ppm_colorhisttocolorhash(chv, colorCt);
2412
2413 {
2414 png_uint_16 * histogram; /* malloc'ed */
2415
2416 MALLOCARRAY(histogram, MAXCOLORS);
2417
2418 if (!histogram)
2419 pm_error("Failed to allocate memory for %u-color histogram",
2420 MAXCOLORS);
2421 else {
2422 unsigned int i;
2423 for (i = 0 ; i < MAXCOLORS; ++i) {
2424 int const chvIndex = ppm_lookupcolor(cht, &palettePnm[i]);
2425 if (chvIndex == -1)
2426 histogram[i] = 0;
2427 else
2428 histogram[i] = chv[chvIndex].value;
2429 }
2430
2431 pngx_setHist(pngxP, histogram);
2432
2433 if (verbose)
2434 pm_message("histogram created in PNG stream");
2435 }
2436 }
2437 ppm_freecolorhash(cht);
2438 }
2439 }
2440
2441
2442
2443 static void
2444 doIhdrChunk(struct pngx * const pngxP,
2445 unsigned int const width,
2446 unsigned int const height,
2447 unsigned int const depth,
2448 bool const colorMapped,
2449 bool const colorPng,
2450 bool const alpha,
2451 bool const interlace) {
2452
2453 int const interlaceMethod =
2454 interlace ? PNG_INTERLACE_ADAM7 : PNG_INTERLACE_NONE;
2455
2456 int colorType;
2457
2458 if (colorMapped)
2459 colorType = PNG_COLOR_TYPE_PALETTE;
2460 else if (colorPng)
2461 colorType = PNG_COLOR_TYPE_RGB;
2462 else
2463 colorType = PNG_COLOR_TYPE_GRAY;
2464
2465 if (alpha && colorType != PNG_COLOR_TYPE_PALETTE)
2466 colorType |= PNG_COLOR_MASK_ALPHA;
2467
2468 pngx_setIhdr(pngxP, width, height, depth, colorType,
2469 interlaceMethod, 0, 0);
2470 }
2471
2472
2473
2474 static void
2475 doGamaChunk(struct cmdlineInfo const cmdline,
2476 struct pngx * const pngxP) {
2477
2478 if (cmdline.gammaSpec)
2479 pngx_setGama(pngxP, cmdline.gamma);
2480 }
2481
2482
2483
2484 static void
2485 doChrmChunk(struct cmdlineInfo const cmdline,
2486 struct pngx * const pngxP) {
2487
2488 if (cmdline.rgbSpec)
2489 pngx_setChrm(pngxP, cmdline.rgb);
2490 }
2491
2492
2493
2494 static void
2495 doPhysChunk(struct cmdlineInfo const cmdline,
2496 struct pngx * const pngxP) {
2497
2498 if (cmdline.sizeSpec)
2499 pngx_setPhys(pngxP, cmdline.size);
2500 }
2501
2502
2503
2504 static void
2505 doTimeChunk(struct cmdlineInfo const cmdline,
2506 struct pngx * const pngxP) {
2507
2508 if (cmdline.modtimeSpec)
2509 pngx_setTime(pngxP, cmdline.modtime);
2510 }
2511
2512
2513
2514 static void
2515 reportFilterSet(int const filterSet) {
2516
2517 pm_message("Limiting filter to: %s%s%s%s%s",
2518 (filterSet & PNG_FILTER_NONE) ? "NONE " : "",
2519 (filterSet & PNG_FILTER_SUB) ? "SUB " : "",
2520 (filterSet & PNG_FILTER_UP) ? "UP " : "",
2521 (filterSet & PNG_FILTER_AVG) ? "AVG " : "",
2522 (filterSet & PNG_FILTER_PAETH) ? "PAETH " : "");
2523 }
2524
2525
2526
2527 static void
2528 doFilters(struct cmdlineInfo const cmdline,
2529 struct pngx * const pngxP) {
2530
2531 if (cmdline.filterSetSpec) {
2532 if (verbose)
2533 reportFilterSet(cmdline.filterSet);
2534 pngx_setFilter(pngxP, cmdline.filterSet);
2535 }
2536 }
2537
2538
2539
2540 static void
2541 reportTrans(struct pngx * const pngxP) {
2542
2543 if (pngx_chunkIsPresent(pngxP, PNG_INFO_tRNS)) {
2544 struct pngx_trns const transInfo = pngx_trns(pngxP);
2545
2546 pm_message("%u transparency values", transInfo.numTrans);
2547
2548 pm_message("Transparent color {gray, red, green, blue} = "
2549 "{%d, %d, %d, %d}",
2550 transInfo.transColor.gray,
2551 transInfo.transColor.red,
2552 transInfo.transColor.green,
2553 transInfo.transColor.blue);
2554 } else
2555 pm_message("No transparent color");
2556 }
2557
2558
2559
2560 static void
2561 doTrnsChunk(struct pngx * const pngxP,
2562 png_byte const transPalette[],
2563 unsigned int const transPaletteSize,
2564 int const transparent,
2565 pixel const transColor,
2566 xelval const maxval,
2567 xelval const pngMaxval) {
2568
2569 switch (pngx_colorType(pngxP)) {
2570 case PNG_COLOR_TYPE_PALETTE:
2571 if (transPaletteSize > 0)
2572 pngx_setTrnsPalette(pngxP, transPalette,
2573 transPaletteSize /* omit opaque values */);
2574 break;
2575 case PNG_COLOR_TYPE_GRAY:
2576 case PNG_COLOR_TYPE_RGB:
2577 if (transparent > 0)
2578 pngx_setTrnsValue(pngxP,
2579 xelToPngColor_16(transColor, maxval, pngMaxval));
2580 break;
2581 default:
2582 /* This is PNG_COLOR_MASK_ALPHA. Transparency will be handled
2583 by the alpha channel, not a transparency color.
2584 */
2585 {}
2586 }
2587 if (verbose)
2588 reportTrans(pngxP);
2589 }
2590
2591
2592
2593 static void
2594 doBkgdChunk(struct pngx * const pngxP,
2595 bool const bkgdRequested,
2596 unsigned int const backgroundIndex,
2597 pixel const backColor,
2598 xelval const maxval,
2599 xelval const pngMaxval,
2600 bool const verbose) {
2601
2602 if (bkgdRequested) {
2603 if (pngx_colorType(pngxP) == PNG_COLOR_TYPE_PALETTE)
2604 pngx_setBkgdPalette(pngxP, backgroundIndex);
2605 else {
2606 png_color_16 const pngBackground =
2607 xelToPngColor_16(backColor, maxval, pngMaxval);
2608 pngx_setBkgdRgb(pngxP, pngBackground);
2609 if (verbose)
2610 pm_message("Writing bKGD chunk with background color "
2611 " {gray, red, green, blue} = {%d, %d, %d, %d}",
2612 pngBackground.gray,
2613 pngBackground.red,
2614 pngBackground.green,
2615 pngBackground.blue );
2616 }
2617 }
2618 }
2619
2620
2621
2622 static void
2623 doSbitChunk(struct pngx * const pngxP,
2624 xelval const pngMaxval,
2625 xelval const maxval,
2626 bool const alpha,
2627 xelval const alphaMaxval) {
2628
2629 if (pngx_colorType(pngxP) != PNG_COLOR_TYPE_PALETTE &&
2630 (pngMaxval > maxval || (alpha && pngMaxval > alphaMaxval))) {
2631
2632 /* We're writing in a bit depth that doesn't match the maxval of the
2633 input image and the alpha mask. So we write an sBIT chunk to tell
2634 what the original image's maxval was. The sBit chunk doesn't let
2635 us specify any maxval -- only powers of two minus one. So we pick
2636 the power of two minus one which is greater than or equal to the
2637 actual input maxval.
2638
2639 PNG also doesn't let an sBIT chunk indicate a maxval _greater_ than
2640 the PNG maxval. The designers probably did not conceive of the
2641 case where that would happen. The case is this: We detected
2642 redundancy in the bits so were able to store fewer bits than the
2643 user provided. But since PNG doesn't allow it, we don't attempt to
2644 create such an sBIT chunk.
2645 */
2646
2647 {
2648 int const sbitval = pm_maxvaltobits(MIN(maxval, pngMaxval));
2649
2650 png_color_8 sbit;
2651
2652 if (pngx_colorType(pngxP) & PNG_COLOR_MASK_COLOR) {
2653 sbit.red = sbitval;
2654 sbit.green = sbitval;
2655 sbit.blue = sbitval;
2656 } else
2657 sbit.gray = sbitval;
2658
2659 if (verbose)
2660 pm_message("Writing sBIT chunk with bits = %d", sbitval);
2661
2662 if (pngx_colorType(pngxP) & PNG_COLOR_MASK_ALPHA) {
2663 sbit.alpha = pm_maxvaltobits(MIN(alphaMaxval, pngMaxval));
2664 if (verbose)
2665 pm_message(" alpha bits = %d", sbit.alpha);
2666 }
2667
2668 pngx_setSbit(pngxP, sbit);
2669 }
2670 }
2671 }
2672
2673
2674
2675 static void
2676 addSrgbChunk(struct pngx * const pngxP,
2677 pngx_srgbIntent const srgbIntent) {
2678
2679 pngx_setSrgb(pngxP, srgbIntent);
2680
2681 if (verbose) {
2682 pm_message("writing sRGB chunk with intent value %s",
2683 pngx_srgbIntentDesc(srgbIntent));
2684 }
2685 }
2686
2687
2688
2689 static void
2690 convertpnm(struct cmdlineInfo const cmdline,
2691 FILE * const ifP,
2692 FILE * const ofP,
2693 FILE * const afP,
2694 FILE * const pfP,
2695 FILE * const tfP,
2696 int * const errorLevelP
2697 ) {
2698 /*----------------------------------------------------------------------------
2699 Design note: It's is really a modularity violation that we have
2700 all the command line parameters as an argument. We do it because we're
2701 lazy -- it takes a great deal of work to carry all that information as
2702 separate arguments -- and it's only a very small violation.
2703 -----------------------------------------------------------------------------*/
2704 int rows, cols, format;
2705 xelval maxval;
2706 /* The maxval of the input image */
2707 xelval pngMaxval;
2708 /* The maxval of the samples in the PNG output
2709 (must be 1, 3, 7, 15, 255, or 65535)
2710 */
2711 pixel transcolor;
2712 /* The color that is to be transparent, with maxval equal to that
2713 of the input image.
2714 */
2715 bool transExact;
2716 /* boolean: the user wants only the exact color he specified to be
2717 transparent; not just something close to it.
2718 */
2719 int transparent;
2720 bool alpha;
2721 /* There will be an alpha mask */
2722 unsigned int pnmMeaningfulBitCt;
2723 pixel backColor;
2724 /* The background color, with maxval equal to that of the input
2725 image.
2726 */
2727 struct pngx * pngxP;
2728
2729 bool colorMapped;
2730 pixel palettePnm[MAXCOLORS];
2731 png_color palette[MAXCOLORS];
2732 /* The color part of the color/alpha palette passed to the PNG
2733 compressor
2734 */
2735 unsigned int paletteSize;
2736
2737 gray transPnm[MAXCOLORS];
2738 png_byte trans[MAXCOLORS];
2739 /* The alpha part of the color/alpha palette passed to the PNG
2740 compressor
2741 */
2742 unsigned int transSize;
2743
2744 colorhash_table cht;
2745 coloralphahash_table caht;
2746
2747 unsigned int backgroundIndex;
2748 /* Index into palette[] of the background color. */
2749
2750 gray alphaMaxval;
2751 const char * noColormapReason;
2752 /* The reason that we shouldn't make a colormapped PNG, or NULL if
2753 we should. malloc'ed null-terminated string.
2754 */
2755 unsigned int depth;
2756 /* The number of bits per sample in the (uncompressed) png
2757 raster -- if the raster contains palette indices, this is the
2758 number of bits in the index.
2759 */
2760 unsigned int fulldepth;
2761 /* The total number of bits per pixel in the (uncompressed) png
2762 raster, including all channels.
2763 */
2764 pm_filepos rasterPos;
2765 /* file position in input image file of start of image (i.e. after
2766 the header)
2767 */
2768 xel * xelrow; /* malloc'ed */
2769 /* The row of the input image currently being processed */
2770
2771 gray ** alpha_mask;
2772
2773 bool colorPng;
2774 /* The PNG shall be of the color (RGB) variety */
2775
2776 /* We initialize these guys to quiet compiler warnings: */
2777 depth = 0;
2778
2779 errorlevel = 0;
2780
2781 pngx_create(&pngxP, PNGX_WRITE, NULL);
2782
2783 pnm_readpnminit(ifP, &cols, &rows, &maxval, &format);
2784 pm_tell2(ifP, &rasterPos, sizeof(rasterPos));
2785
2786 xelrow = pnm_allocrow(cols);
2787
2788 if (verbose)
2789 reportInputType(format, maxval);
2790
2791 determineTransparency(cmdline, ifP, rasterPos, cols, rows, maxval, format,
2792 afP,
2793 &alpha, &transparent, &transcolor, &transExact,
2794 &alpha_mask, &alphaMaxval);
2795
2796 determineBackground(cmdline, maxval, &backColor);
2797
2798 if (cmdline.force)
2799 colorPng = (PNM_FORMAT_TYPE(format) == PPM_TYPE);
2800 else {
2801 if (PNM_FORMAT_TYPE(format) == PPM_TYPE) {
2802 colorPng = hasColor(ifP, cols, rows, maxval, format, rasterPos);
2803 } else
2804 colorPng = false;
2805 }
2806
2807
2808 /* handle `odd' maxvalues */
2809
2810 if (maxval > 65535 && !cmdline.downscale) {
2811 pm_error("can only handle files up to 16-bit "
2812 "(use -downscale to override");
2813 }
2814
2815 findRedundantBits(ifP, rasterPos, cols, rows, maxval, format, alpha,
2816 cmdline.force, &pnmMeaningfulBitCt);
2817
2818 computeColorMap(ifP, rasterPos, cols, rows, maxval, colorPng, format,
2819 cmdline.force, pfP,
2820 alpha, transparent >= 0, transcolor, transExact,
2821 !!cmdline.background, backColor,
2822 alpha_mask, alphaMaxval, pnmMeaningfulBitCt,
2823 palettePnm, &paletteSize, transPnm, &transSize,
2824 &backgroundIndex, &noColormapReason);
2825
2826 if (noColormapReason) {
2827 if (pfP)
2828 pm_error("You specified a particular palette, but this image "
2829 "cannot be represented by any palette. %s",
2830 noColormapReason);
2831 if (verbose)
2832 pm_message("Not using color map. %s", noColormapReason);
2833 pm_strfree(noColormapReason);
2834 colorMapped = false;
2835 } else
2836 colorMapped = true;
2837
2838 computeColorMapLookupTable(colorMapped, palettePnm, paletteSize,
2839 transPnm, transSize, alpha, alphaMaxval,
2840 &cht, &caht);
2841
2842 computeRasterWidth(colorMapped, paletteSize, colorPng,
2843 pnmMeaningfulBitCt, alpha,
2844 &depth, &fulldepth);
2845 if (verbose)
2846 pm_message ("writing a%s %d-bit %s%s file%s",
2847 fulldepth == 8 ? "n" : "", fulldepth,
2848 colorMapped ? "palette":
2849 colorPng ? "RGB" : "gray",
2850 alpha ? (colorMapped ? "+transparency" : "+alpha") : "",
2851 cmdline.interlace ? " (interlaced)" : "");
2852
2853 /* now write the file */
2854
2855 pngMaxval = pm_bitstomaxval(depth);
2856
2857 doIhdrChunk(pngxP, cols, rows, depth, colorMapped, colorPng, alpha,
2858 cmdline.interlace);
2859
2860 doGamaChunk(cmdline, pngxP);
2861
2862 doChrmChunk(cmdline, pngxP);
2863
2864 doPhysChunk(cmdline, pngxP);
2865
2866 if (pngx_colorType(pngxP) == PNG_COLOR_TYPE_PALETTE) {
2867
2868 /* creating PNG palette (Not counting the transparency palette) */
2869
2870 createPngPalette(palettePnm, paletteSize, maxval,
2871 transPnm, transSize, alphaMaxval,
2872 palette, trans);
2873 pngx_setPlte(pngxP, palette, paletteSize);
2874
2875 doHistChunk(pngxP, cmdline.hist, palettePnm, ifP, rasterPos,
2876 cols, rows, maxval, format, cmdline.verbose);
2877 }
2878
2879 doTrnsChunk(pngxP, trans, transSize,
2880 transparent, transcolor, maxval, pngMaxval);
2881
2882 doBkgdChunk(pngxP, !!cmdline.background,
2883 backgroundIndex, backColor,
2884 maxval, pngMaxval, cmdline.verbose);
2885
2886 doSbitChunk(pngxP, pngMaxval, maxval, alpha, alphaMaxval);
2887
2888 if (cmdline.srgbintentSpec)
2889 addSrgbChunk(pngxP, cmdline.srgbintent);
2890
2891 /* tEXT and zTXT chunks */
2892 if (cmdline.text || cmdline.ztxt)
2893 pngtxt_addChunk(pngxP, tfP, !!cmdline.ztxt, false, cmdline.verbose);
2894
2895 doTimeChunk(cmdline, pngxP);
2896
2897 doFilters(cmdline, pngxP);
2898
2899 setZlibCompression(pngxP, cmdline.zlibCompression);
2900
2901 png_init_io(pngxP->png_ptr, ofP);
2902
2903 /* write the png-info struct */
2904 pngx_writeInfo(pngxP);
2905
2906 /* let libpng take care of, e.g., bit-depth conversions */
2907 pngx_setPacking(pngxP);
2908
2909 pngx_setInterlaceHandling(pngxP);
2910
2911 writeRaster(pngxP, ifP, rasterPos,
2912 cols, rows, maxval, format,
2913 pngMaxval, depth, alpha, alpha_mask, cht, caht);
2914
2915 pngx_writeEnd(pngxP);
2916
2917 pngx_destroy(pngxP);
2918
2919 pnm_freerow(xelrow);
2920
2921 if (cht)
2922 ppm_freecolorhash(cht);
2923 if (caht)
2924 freecoloralphahash(caht);
2925
2926 *errorLevelP = errorlevel;
2927 }
2928
2929
2930
2931 static void
2932 displayVersion() {
2933
2934 fprintf(stderr,"Pnmtopng version %s.\n", NETPBM_VERSION);
2935
2936 /* We'd like to display the version of libpng with which we're _linked_ as
2937 well as the one with which we're compiled, but it isn't practical.
2938 While libpng is capable of telling you what it's level is, different
2939 versions of it do it two different ways: with png_libpng_ver or with
2940 png_get_header_ver. So we have to be compiled for a particular version
2941 just to find out what version it is! It's not worth having a link
2942 failure, much less a compile failure, if we choose wrong.
2943 png_get_header_ver is not in anything older than libpng 1.0.2a (Dec
2944 1998). png_libpng_ver is not there in libraries built without
2945 USE_GLOBAL_ARRAYS. Cygwin versions are normally built without
2946 USE_GLOBAL_ARRAYS. -bjh 2002.06.17.
2947
2948 We'd also like to display the version of libz with which we're linked,
2949 with zlib_version (which nowadays is a macro for zlibVersion), but we
2950 can't for reasons of modularity: We don't really link libz. libpng
2951 does. It's none of our business whether libz is even present. And at
2952 least on Mac OS X, we can't access libz's symbols from here -- we get
2953 undefined reference to zlibVersion. We would have to explicitly link
2954 libz just to find out its version. The right way to do this is for a
2955 subroutine in libpng to give us the information. Until 10.07.08, we
2956 did display zlib_version, but for years Mac OS X build was failing (and
2957 we erroneously thought it was a libpng-config --ldflags bug).
2958
2959 We _do_ use the compile-time part of libpng (<png.h>), because it's
2960 part of the interface to libpng.
2961 */
2962 fprintf(stderr, " Pnmtopng Compiled with libpng %s.\n",
2963 PNG_LIBPNG_VER_STRING);
2964 fprintf(stderr, " Pnmtopng (not libpng) compiled with zlib %s.\n",
2965 ZLIB_VERSION);
2966 fprintf(stderr, "\n");
2967 }
2968
2969
2970
2971 int
2972 main(int argc, const char * argv[]) {
2973
2974 struct cmdlineInfo cmdline;
2975 FILE * ifP;
2976 FILE * afP;
2977 FILE * pfP;
2978 FILE * tfP;
2979
2980 int errorlevel;
2981
2982 pm_proginit(&argc, argv);
2983
2984 parseCommandLine(argc, argv, &cmdline);
2985
2986 if (cmdline.libversion) {
2987 displayVersion();
2988 return 0;
2989 }
2990 verbose = cmdline.verbose;
2991
2992 ifP = pm_openr_seekable(cmdline.inputFileName);
2993
2994 if (cmdline.alpha)
2995 afP = pm_openr(cmdline.alpha);
2996 else
2997 afP = NULL;
2998
2999 if (cmdline.palette)
3000 pfP = pm_openr(cmdline.palette);
3001 else
3002 pfP = NULL;
3003
3004 if (cmdline.text)
3005 tfP = pm_openr(cmdline.text);
3006 else if (cmdline.ztxt)
3007 tfP = pm_openr(cmdline.ztxt);
3008 else
3009 tfP = NULL;
3010
3011 convertpnm(cmdline, ifP, stdout, afP, pfP, tfP, &errorlevel);
3012
3013 if (afP)
3014 pm_close(afP);
3015 if (pfP)
3016 pm_close(pfP);
3017 if (tfP)
3018 pm_close(tfP);
3019
3020 pm_close(ifP);
3021 pm_close(stdout);
3022
3023 return errorlevel;
3024 }
3025
3026
3027