Merge branch 'upstream' into tizen
[platform/upstream/libpng.git] / contrib / libtests / makepng.c
1 /* makepng.c */
2 #define _ISOC99_SOURCE
3 /* Copyright: */
4 #define COPYRIGHT "\251 2013,2015 John Cunningham Bowler"
5 /*
6  * This code is released under the libpng license.
7  * For conditions of distribution and use, see the disclaimer
8  * and license in png.h
9  *
10  * Make a test PNG image.  The arguments are as follows:
11  *
12  *    makepng [--sRGB|--linear|--1.8] [--tRNS] [--nofilters] \
13  *       color-type bit-depth [file-name]
14  *
15  * The color-type may be numeric (and must match the numbers used by the PNG
16  * specification) or one of the format names listed below.  The bit-depth is the
17  * component bit depth, or the pixel bit-depth for a color-mapped image.
18  *
19  * Without any options no color-space information is written, with the options
20  * an sRGB or the appropriate gAMA chunk is written.  "1.8" refers to the
21  * display system used on older Apple computers to correct for high ambient
22  * light levels in the viewing environment; it applies a transform of
23  * approximately value^(1/1.45) to the color values and so a gAMA chunk of 65909
24  * is written (1.45/2.2).
25  *
26  * The image data is generated internally.  Unless --color is given the images
27  * used are as follows:
28  *
29  * 1 channel: a square image with a diamond, the least luminous colors are on
30  *    the edge of the image, the most luminous in the center.
31  *
32  * 2 channels: the color channel increases in luminosity from top to bottom, the
33  *    alpha channel increases in opacity from left to right.
34  *
35  * 3 channels: linear combinations of, from the top-left corner clockwise,
36  *    black, green, white, red.
37  *
38  * 4 channels: linear combinations of, from the top-left corner clockwise,
39  *    transparent, red, green, blue.
40  *
41  * For color-mapped images a four channel color-map is used and if --tRNS is
42  * given the PNG file has a tRNS chunk, as follows:
43  *
44  * 1-bit: entry 0 is transparent-red, entry 1 is opaque-white
45  * 2-bit: entry 0: transparent-green
46  *        entry 1: 40%-red
47  *        entry 2: 80%-blue
48  *        entry 3: opaque-white
49  * 4-bit: the 16 combinations of the 2-bit case
50  * 8-bit: the 256 combinations of the 4-bit case
51  *
52  * The palette always has 2^bit-depth entries and the tRNS chunk one fewer.  The
53  * image is the 1-channel diamond, but using palette index, not luminosity.
54  *
55  * For formats other than color-mapped ones if --tRNS is specified a tRNS chunk
56  * is generated with all channels equal to the low bits of 0x0101.
57  *
58  * Image size is determined by the final pixel depth in bits, i.e. channels x
59  * bit-depth, as follows:
60  *
61  * 8 bits or less:    64x64
62  * 16 bits:           256x256
63  * More than 16 bits: 1024x1024
64  *
65  * Row filtering is the libpng default but may be turned off (the 'none' filter
66  * is used on every row) with the --nofilters option.
67  *
68  * The images are not interlaced.
69  *
70  * If file-name is given then the PNG is written to that file, else it is
71  * written to stdout.  Notice that stdout is not supported on systems where, by
72  * default, it assumes text output; this program makes no attempt to change the
73  * text mode of stdout!
74  *
75  *    makepng --color=<color> ...
76  *
77  * If --color is given then the whole image has that color, color-mapped images
78  * will have exactly one palette entry and all image files with be 16x16 in
79  * size.  The color value is 1 to 4 decimal numbers as appropriate for the color
80  * type.
81  *
82  *    makepng --small ...
83  *
84  * If --small is given the images are no larger than required to include every
85  * possible pixel value for the format.
86  *
87  * For formats with pixels 8 bits or fewer in size the images consist of a
88  * single row with 2^pixel-depth pixels, one of every possible value.
89  *
90  * For formats with 16-bit pixels a 256x256 image is generated containing every
91  * possible pixel value.
92  *
93  * For larger pixel sizes a 256x256 image is generated where the first row
94  * consists of each pixel that has identical byte values throughout the pixel
95  * followed by rows where the byte values differ within the pixel.
96  *
97  * In all cases the pixel values are arranged in such a way that the SUB and UP
98  * filters give byte sequences for maximal zlib compression.  By default (if
99  * --nofilters is not given) the SUB filter is used on the first row and the UP
100  * filter on all following rows.
101  *
102  * The --small option is meant to provide good test-case coverage, however the
103  * images are not easy to examine visually.  Without the --small option the
104  * images contain identical color values; the pixel values are adjusted
105  * according to the gamma encoding with no gamma encoding being interpreted as
106  * sRGB.
107  *
108  * LICENSING
109  * =========
110  *
111  * This code is copyright of the authors, see the COPYRIGHT define above.  The
112  * code is licensed as above, using the libpng license.  The code generates
113  * images which are solely the product of the code; the options choose which of
114  * the many possibilities to generate.  The images that result (but not the code
115  * which generates them) are licensed as defined here:
116  *
117  * IMPORTANT: the COPYRIGHT #define must contain ISO-Latin-1 characters, the
118  * IMAGE_LICENSING #define must contain UTF-8 characters.  The 'copyright'
119  * symbol 0xA9U (\251) in ISO-Latin-1 encoding and 0xC20xA9 (\302\251) in UTF-8.
120  */
121 #define IMAGE_LICENSING "Dedicated to the public domain per Creative Commons "\
122     "license \"CC0 1.0\"; https://creativecommons.org/publicdomain/zero/1.0/"
123
124 #include <stddef.h> /* for offsetof */
125 #include <stdlib.h>
126 #include <stdio.h>
127 #include <string.h>
128 #include <ctype.h>
129 #include <math.h>
130 #include <errno.h>
131 #include <assert.h>
132 #include <stdint.h>
133
134 #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
135 #  include <config.h>
136 #endif
137
138 /* Define the following to use this test against your installed libpng, rather
139  * than the one being built here:
140  */
141 #ifdef PNG_FREESTANDING_TESTS
142 #  include <png.h>
143 #else
144 #  include "../../png.h"
145 #endif
146
147 #include <zlib.h>
148
149 /* Work round for GCC complaints about casting a (double) function result to
150  * an unsigned:
151  */
152 static unsigned int
153 flooru(double d)
154 {
155    d = floor(d);
156    return (unsigned int)d;
157 }
158
159 static png_byte
160 floorb(double d)
161 {
162    d = floor(d);
163    return (png_byte)d;
164 }
165
166 /* This structure is used for inserting extra chunks (the --insert argument, not
167  * documented above.)
168  */
169 typedef struct chunk_insert
170 {
171    struct chunk_insert *next;
172    void               (*insert)(png_structp, png_infop, int, png_charpp);
173    int                  nparams;
174    png_charp            parameters[1];
175 } chunk_insert;
176
177 static unsigned int
178 channels_of_type(int color_type)
179 {
180    if (color_type & PNG_COLOR_MASK_PALETTE)
181       return 1;
182
183    else
184    {
185       int channels = 1;
186
187       if (color_type & PNG_COLOR_MASK_COLOR)
188          channels = 3;
189
190       if (color_type & PNG_COLOR_MASK_ALPHA)
191          return channels + 1;
192
193       else
194          return channels;
195    }
196 }
197
198 static unsigned int
199 pixel_depth_of_type(int color_type, int bit_depth)
200 {
201    return channels_of_type(color_type) * bit_depth;
202 }
203
204 static unsigned int
205 image_size_of_type(int color_type, int bit_depth, unsigned int *colors,
206    int small)
207 {
208    if (*colors)
209       return 16;
210
211    else
212    {
213       int pixel_depth = pixel_depth_of_type(color_type, bit_depth);
214
215       if (small)
216       {
217          if (pixel_depth <= 8) /* there will be one row */
218             return 1 << pixel_depth;
219
220          else
221             return 256;
222       }
223
224       else if (pixel_depth < 8)
225          return 64;
226
227       else if (pixel_depth > 16)
228          return 1024;
229
230       else
231          return 256;
232    }
233 }
234
235 static void
236 set_color(png_colorp color, png_bytep trans, unsigned int red,
237    unsigned int green, unsigned int blue, unsigned int alpha,
238    png_const_bytep gamma_table)
239 {
240    color->red = gamma_table[red];
241    color->green = gamma_table[green];
242    color->blue = gamma_table[blue];
243    *trans = (png_byte)alpha;
244 }
245
246 static int
247 generate_palette(png_colorp palette, png_bytep trans, int bit_depth,
248    png_const_bytep gamma_table, unsigned int *colors)
249 {
250    /*
251     * 1-bit: entry 0 is transparent-red, entry 1 is opaque-white
252     * 2-bit: entry 0: transparent-green
253     *        entry 1: 40%-red
254     *        entry 2: 80%-blue
255     *        entry 3: opaque-white
256     * 4-bit: the 16 combinations of the 2-bit case
257     * 8-bit: the 256 combinations of the 4-bit case
258     */
259    switch (colors[0])
260    {
261       default:
262          fprintf(stderr, "makepng: --colors=...: invalid count %u\n",
263             colors[0]);
264          exit(1);
265
266       case 1:
267          set_color(palette+0, trans+0, colors[1], colors[1], colors[1], 255,
268             gamma_table);
269          return 1;
270
271       case 2:
272          set_color(palette+0, trans+0, colors[1], colors[1], colors[1],
273             colors[2], gamma_table);
274          return 1;
275
276       case 3:
277          set_color(palette+0, trans+0, colors[1], colors[2], colors[3], 255,
278             gamma_table);
279          return 1;
280
281       case 4:
282          set_color(palette+0, trans+0, colors[1], colors[2], colors[3],
283             colors[4], gamma_table);
284          return 1;
285
286       case 0:
287          if (bit_depth == 1)
288          {
289             set_color(palette+0, trans+0, 255, 0, 0, 0, gamma_table);
290             set_color(palette+1, trans+1, 255, 255, 255, 255, gamma_table);
291             return 2;
292          }
293
294          else
295          {
296             unsigned int size = 1U << (bit_depth/2); /* 2, 4 or 16 */
297             unsigned int x, y;
298             volatile unsigned int ip = 0;
299
300             for (x=0; x<size; ++x)
301             {
302                for (y=0; y<size; ++y)
303                {
304                   ip = x + (size * y);
305
306                   /* size is at most 16, so the scaled value below fits in 16 bits
307                   */
308 #                 define interp(pos, c1, c2) ((pos * c1) + ((size-pos) * c2))
309 #                 define xyinterp(x, y, c1, c2, c3, c4) (((size * size / 2) +\
310                      (interp(x, c1, c2) * y + (size-y) * interp(x, c3, c4))) /\
311                      (size*size))
312
313                   set_color(palette+ip, trans+ip,
314                      /* color:    green, red,blue,white */
315                      xyinterp(x, y,   0, 255,   0, 255),
316                      xyinterp(x, y, 255,   0,   0, 255),
317                      xyinterp(x, y,   0,   0, 255, 255),
318                      /* alpha:        0, 102, 204, 255) */
319                      xyinterp(x, y,   0, 102, 204, 255),
320                      gamma_table);
321                }
322             }
323
324             return ip+1;
325          }
326    }
327 }
328
329 static void
330 set_value(png_bytep row, size_t rowbytes, png_uint_32 x, unsigned int bit_depth,
331    png_uint_32 value, png_const_bytep gamma_table, double conv)
332 {
333    unsigned int mask = (1U << bit_depth)-1;
334
335    x *= bit_depth;  /* Maximum x is 4*1024, maximum bit_depth is 16 */
336
337    if (value <= mask)
338    {
339       png_uint_32 offset = x >> 3;
340
341       if (offset < rowbytes && (bit_depth < 16 || offset+1 < rowbytes))
342       {
343          row += offset;
344
345          switch (bit_depth)
346          {
347             case 1:
348             case 2:
349             case 4:
350                /* Don't gamma correct - values get smashed */
351                {
352                   unsigned int shift = (8 - bit_depth) - (x & 0x7U);
353
354                   mask <<= shift;
355                   value = (value << shift) & mask;
356                   *row = (png_byte)((*row & ~mask) | value);
357                }
358                return;
359
360             default:
361                fprintf(stderr, "makepng: bad bit depth (internal error)\n");
362                exit(1);
363
364             case 16:
365                value = flooru(65535*pow(value/65535.,conv)+.5);
366                *row++ = (png_byte)(value >> 8);
367                *row = (png_byte)value;
368                return;
369
370             case 8:
371                *row = gamma_table[value];
372                return;
373          }
374       }
375
376       else
377       {
378          fprintf(stderr, "makepng: row buffer overflow (internal error)\n");
379          exit(1);
380       }
381    }
382
383    else
384    {
385       fprintf(stderr, "makepng: component overflow (internal error)\n");
386       exit(1);
387    }
388 }
389
390 static int /* filter mask for row */
391 generate_row(png_bytep row, size_t rowbytes, unsigned int y, int color_type,
392    int bit_depth, png_const_bytep gamma_table, double conv,
393    unsigned int *colors, int small)
394 {
395    int filters = 0; /* file *MASK*, 0 means the default, not NONE */
396    png_uint_32 size_max =
397       image_size_of_type(color_type, bit_depth, colors, small)-1;
398    png_uint_32 depth_max = (1U << bit_depth)-1; /* up to 65536 */
399
400    if (colors[0] == 0 && small)
401    {
402       unsigned int pixel_depth = pixel_depth_of_type(color_type, bit_depth);
403
404       /* For pixel depths less than 16 generate a single row containing all the
405        * possible pixel values.  For 16 generate all 65536 byte pair
406        * combinations in a 256x256 pixel array.
407        */
408       switch (pixel_depth)
409       {
410          case 1:
411             assert(y == 0 && rowbytes == 1 && size_max == 1);
412             row[0] = 0x6CU; /* binary: 01101100, only top 2 bits used */
413             filters = PNG_FILTER_NONE;
414             break;
415
416          case 2:
417             assert(y == 0 && rowbytes == 1 && size_max == 3);
418             row[0] = 0x1BU; /* binary 00011011, all bits used */
419             filters = PNG_FILTER_NONE;
420             break;
421
422          case 4:
423             assert(y == 0 && rowbytes == 8 && size_max == 15);
424             row[0] = 0x01U;
425             row[1] = 0x23U; /* SUB gives 0x22U for all following bytes */
426             row[2] = 0x45U;
427             row[3] = 0x67U;
428             row[4] = 0x89U;
429             row[5] = 0xABU;
430             row[6] = 0xCDU;
431             row[7] = 0xEFU;
432             filters = PNG_FILTER_SUB;
433             break;
434
435          case 8:
436             /* The row will have all the pixel values in order starting with
437              * '1', the SUB filter will change every byte into '1' (including
438              * the last, which generates pixel value '0').  Since the SUB filter
439              * has value 1 this should result in maximum compression.
440              */
441             assert(y == 0 && rowbytes == 256 && size_max == 255);
442             for (;;)
443             {
444                row[size_max] = 0xFFU & (size_max+1);
445                if (size_max == 0)
446                   break;
447                --size_max;
448             }
449             filters = PNG_FILTER_SUB;
450             break;
451
452          case 16:
453             /* Rows are generated such that each row has a constant difference
454              * between the first and second byte of each pixel and so that the
455              * difference increases by 1 at each row.  The rows start with the
456              * first byte value of 0 and the value increases to 255 across the
457              * row.
458              *
459              * The difference starts at 1, so the first row is:
460              *
461              *     0 1 1 2 2 3 3 4 ... 254 255 255 0
462              *
463              * This means that running the SUB filter on the first row produces:
464              *
465              *   [SUB==1] 0 1 0 1 0 1...
466              *
467              * Then the difference is 2 on the next row, giving:
468              *
469              *    0 2 1 3 2 4 3 5 ... 254 0 255 1
470              *
471              * When the UP filter is run on this libpng produces:
472              *
473              *   [UP ==2] 0 1 0 1 0 1...
474              *
475              * And so on for all the remain rows to the final two * rows:
476              *
477              *    row 254: 0 255 1 0 2 1 3 2 4 3 ... 254 253 255 254
478              *    row 255: 0   0 1 1 2 2 3 3 4 4 ... 254 254 255 255
479              */
480             assert(rowbytes == 512 && size_max == 255);
481             for (;;)
482             {
483                row[2*size_max  ] = 0xFFU & size_max;
484                row[2*size_max+1] = 0xFFU & (size_max+y+1);
485                if (size_max == 0)
486                   break;
487                --size_max;
488             }
489             /* The first row must include PNG_FILTER_UP so that libpng knows we
490              * need to keep it for the following row:
491              */
492             filters = (y == 0 ? PNG_FILTER_SUB+PNG_FILTER_UP : PNG_FILTER_UP);
493             break;
494
495          case 24:
496          case 32:
497          case 48:
498          case 64:
499             /* The rows are filled by an algorithm similar to the above, in the
500              * first row pixel bytes are all equal, increasing from 0 by 1 for
501              * each pixel.  In the second row the bytes within a pixel are
502              * incremented 1,3,5,7,... from the previous row byte.  Using an odd
503              * number ensures all the possible byte values are used.
504              */
505             assert(size_max == 255 && rowbytes == 256*(pixel_depth>>3));
506             pixel_depth >>= 3; /* now in bytes */
507             while (rowbytes > 0)
508             {
509                const size_t pixel_index = --rowbytes/pixel_depth;
510
511                if (y == 0)
512                   row[rowbytes] = 0xFFU & pixel_index;
513
514                else
515                {
516                   const size_t byte_offset =
517                      rowbytes - pixel_index * pixel_depth;
518
519                   row[rowbytes] =
520                      0xFFU & (pixel_index + (byte_offset * 2*y) + 1);
521                }
522             }
523             filters = (y == 0 ? PNG_FILTER_SUB+PNG_FILTER_UP : PNG_FILTER_UP);
524             break;
525
526          default:
527             assert(0/*NOT REACHED*/);
528       }
529    }
530
531    else switch (channels_of_type(color_type))
532    {
533    /* 1 channel: a square image with a diamond, the least luminous colors are on
534     *    the edge of the image, the most luminous in the center.
535     */
536       case 1:
537          {
538             png_uint_32 x;
539             png_uint_32 base = 2*size_max - abs(2*y-size_max);
540
541             for (x=0; x<=size_max; ++x)
542             {
543                png_uint_32 luma = base - abs(2*x-size_max);
544
545                /* 'luma' is now in the range 0..2*size_max, we need
546                 * 0..depth_max
547                 */
548                luma = (luma*depth_max + size_max) / (2*size_max);
549                set_value(row, rowbytes, x, bit_depth, luma, gamma_table, conv);
550             }
551          }
552          break;
553
554    /* 2 channels: the color channel increases in luminosity from top to bottom,
555     *    the alpha channel increases in opacity from left to right.
556     */
557       case 2:
558          {
559             png_uint_32 alpha = (depth_max * y * 2 + size_max) / (2 * size_max);
560             png_uint_32 x;
561
562             for (x=0; x<=size_max; ++x)
563             {
564                set_value(row, rowbytes, 2*x, bit_depth,
565                   (depth_max * x * 2 + size_max) / (2 * size_max), gamma_table,
566                   conv);
567                set_value(row, rowbytes, 2*x+1, bit_depth, alpha, gamma_table,
568                   conv);
569             }
570          }
571          break;
572
573    /* 3 channels: linear combinations of, from the top-left corner clockwise,
574     *    black, green, white, red.
575     */
576       case 3:
577          {
578             /* x0: the black->red scale (the value of the red component) at the
579              *     start of the row (blue and green are 0).
580              * x1: the green->white scale (the value of the red and blue
581              *     components at the end of the row; green is depth_max).
582              */
583             png_uint_32 Y = (depth_max * y * 2 + size_max) / (2 * size_max);
584             png_uint_32 x;
585
586             /* Interpolate x/depth_max from start to end:
587              *
588              *        start end         difference
589              * red:     Y    Y            0
590              * green:   0   depth_max   depth_max
591              * blue:    0    Y            Y
592              */
593             for (x=0; x<=size_max; ++x)
594             {
595                set_value(row, rowbytes, 3*x+0, bit_depth, /* red */ Y,
596                      gamma_table, conv);
597                set_value(row, rowbytes, 3*x+1, bit_depth, /* green */
598                   (depth_max * x * 2 + size_max) / (2 * size_max),
599                   gamma_table, conv);
600                set_value(row, rowbytes, 3*x+2, bit_depth, /* blue */
601                   (Y * x * 2 + size_max) / (2 * size_max),
602                   gamma_table, conv);
603             }
604          }
605          break;
606
607    /* 4 channels: linear combinations of, from the top-left corner clockwise,
608     *    transparent, red, green, blue.
609     */
610       case 4:
611          {
612             /* x0: the transparent->blue scale (the value of the blue and alpha
613              *     components) at the start of the row (red and green are 0).
614              * x1: the red->green scale (the value of the red and green
615              *     components at the end of the row; blue is 0 and alpha is
616              *     depth_max).
617              */
618             png_uint_32 Y = (depth_max * y * 2 + size_max) / (2 * size_max);
619             png_uint_32 x;
620
621             /* Interpolate x/depth_max from start to end:
622              *
623              *        start    end       difference
624              * red:     0   depth_max-Y depth_max-Y
625              * green:   0       Y             Y
626              * blue:    Y       0            -Y
627              * alpha:   Y    depth_max  depth_max-Y
628              */
629             for (x=0; x<=size_max; ++x)
630             {
631                set_value(row, rowbytes, 4*x+0, bit_depth, /* red */
632                   ((depth_max-Y) * x * 2 + size_max) / (2 * size_max),
633                   gamma_table, conv);
634                set_value(row, rowbytes, 4*x+1, bit_depth, /* green */
635                   (Y * x * 2 + size_max) / (2 * size_max),
636                   gamma_table, conv);
637                set_value(row, rowbytes, 4*x+2, bit_depth, /* blue */
638                   Y - (Y * x * 2 + size_max) / (2 * size_max),
639                   gamma_table, conv);
640                set_value(row, rowbytes, 4*x+3, bit_depth, /* alpha */
641                   Y + ((depth_max-Y) * x * 2 + size_max) / (2 * size_max),
642                   gamma_table, conv);
643             }
644          }
645          break;
646
647       default:
648          fprintf(stderr, "makepng: internal bad channel count\n");
649          exit(2);
650    }
651
652    else if (color_type & PNG_COLOR_MASK_PALETTE)
653    {
654       /* Palette with fixed color: the image rows are all 0 and the image width
655        * is 16.
656        */
657       memset(row, 0, rowbytes);
658    }
659
660    else if (colors[0] == channels_of_type(color_type))
661       switch (channels_of_type(color_type))
662       {
663          case 1:
664             {
665                png_uint_32 luma = colors[1];
666                png_uint_32 x;
667
668                for (x=0; x<=size_max; ++x)
669                   set_value(row, rowbytes, x, bit_depth, luma, gamma_table,
670                      conv);
671             }
672             break;
673
674          case 2:
675             {
676                png_uint_32 luma = colors[1];
677                png_uint_32 alpha = colors[2];
678                png_uint_32 x;
679
680                for (x=0; x<size_max; ++x)
681                {
682                   set_value(row, rowbytes, 2*x, bit_depth, luma, gamma_table,
683                      conv);
684                   set_value(row, rowbytes, 2*x+1, bit_depth, alpha, gamma_table,
685                      conv);
686                }
687             }
688             break;
689
690          case 3:
691             {
692                png_uint_32 red = colors[1];
693                png_uint_32 green = colors[2];
694                png_uint_32 blue = colors[3];
695                png_uint_32 x;
696
697                for (x=0; x<=size_max; ++x)
698                {
699                   set_value(row, rowbytes, 3*x+0, bit_depth, red, gamma_table,
700                      conv);
701                   set_value(row, rowbytes, 3*x+1, bit_depth, green, gamma_table,
702                      conv);
703                   set_value(row, rowbytes, 3*x+2, bit_depth, blue, gamma_table,
704                      conv);
705                }
706             }
707             break;
708
709          case 4:
710             {
711                png_uint_32 red = colors[1];
712                png_uint_32 green = colors[2];
713                png_uint_32 blue = colors[3];
714                png_uint_32 alpha = colors[4];
715                png_uint_32 x;
716
717                for (x=0; x<=size_max; ++x)
718                {
719                   set_value(row, rowbytes, 4*x+0, bit_depth, red, gamma_table,
720                      conv);
721                   set_value(row, rowbytes, 4*x+1, bit_depth, green, gamma_table,
722                      conv);
723                   set_value(row, rowbytes, 4*x+2, bit_depth, blue, gamma_table,
724                      conv);
725                   set_value(row, rowbytes, 4*x+3, bit_depth, alpha, gamma_table,
726                      conv);
727                }
728             }
729          break;
730
731          default:
732             fprintf(stderr, "makepng: internal bad channel count\n");
733             exit(2);
734       }
735
736    else
737    {
738       fprintf(stderr,
739          "makepng: --color: count(%u) does not match channels(%u)\n",
740          colors[0], channels_of_type(color_type));
741       exit(1);
742    }
743
744    return filters;
745 }
746
747
748 static void PNGCBAPI
749 makepng_warning(png_structp png_ptr, png_const_charp message)
750 {
751    const char **ep = png_get_error_ptr(png_ptr);
752    const char *name;
753
754    if (ep != NULL && *ep != NULL)
755       name = *ep;
756
757    else
758       name = "makepng";
759
760   fprintf(stderr, "%s: warning: %s\n", name, message);
761 }
762
763 static void PNGCBAPI
764 makepng_error(png_structp png_ptr, png_const_charp message)
765 {
766    makepng_warning(png_ptr, message);
767    png_longjmp(png_ptr, 1);
768 }
769
770 static int /* 0 on success, else an error code */
771 write_png(const char **name, FILE *fp, int color_type, int bit_depth,
772    volatile png_fixed_point gamma, chunk_insert * volatile insert,
773    unsigned int filters, unsigned int *colors, int small, int tRNS)
774 {
775    png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
776       name, makepng_error, makepng_warning);
777    volatile png_infop info_ptr = NULL;
778    volatile png_bytep row = NULL;
779
780    if (png_ptr == NULL)
781    {
782       fprintf(stderr, "makepng: OOM allocating write structure\n");
783       return 1;
784    }
785
786    if (setjmp(png_jmpbuf(png_ptr)))
787    {
788       png_structp nv_ptr = png_ptr;
789       png_infop nv_info = info_ptr;
790
791       png_ptr = NULL;
792       info_ptr = NULL;
793       png_destroy_write_struct(&nv_ptr, &nv_info);
794       if (row != NULL) free(row);
795       return 1;
796    }
797
798    /* Allow benign errors so that we can write PNGs with errors */
799    png_set_benign_errors(png_ptr, 1/*allowed*/);
800
801    /* Max out the text compression level in an attempt to make the license
802     * small.   If --small then do the same for the IDAT.
803     */
804    if (small)
805       png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
806
807    png_set_text_compression_level(png_ptr, Z_BEST_COMPRESSION);
808
809    png_init_io(png_ptr, fp);
810
811    info_ptr = png_create_info_struct(png_ptr);
812    if (info_ptr == NULL)
813       png_error(png_ptr, "OOM allocating info structure");
814
815    {
816       unsigned int size =
817          image_size_of_type(color_type, bit_depth, colors, small);
818       unsigned int ysize;
819       png_fixed_point real_gamma = 45455; /* For sRGB */
820       png_byte gamma_table[256];
821       double conv;
822
823       /* Normally images are square, but with 'small' we want to simply generate
824        * all the pixel values, or all that we reasonably can:
825        */
826       if (small)
827       {
828          unsigned int pixel_depth =
829             pixel_depth_of_type(color_type, bit_depth);
830
831          if (pixel_depth <= 8U)
832          {
833             assert(size == (1U<<pixel_depth));
834             ysize = 1U;
835          }
836
837          else
838          {
839             assert(size == 256U);
840             ysize = 256U;
841          }
842       }
843
844       else
845          ysize = size;
846
847       /* This function uses the libpng values used on read to carry extra
848        * information about the gamma:
849        */
850       if (gamma == PNG_GAMMA_MAC_18)
851          gamma = 65909;
852
853       else if (gamma > 0 && gamma < 1000)
854          gamma = PNG_FP_1;
855
856       if (gamma > 0)
857          real_gamma = gamma;
858
859       {
860          unsigned int i;
861
862          if (real_gamma == 45455)
863          {
864             for (i=0; i<256; ++i)
865             {
866                gamma_table[i] = (png_byte)i;
867                conv = 1.;
868             }
869          }
870
871          else
872          {
873             /* Convert 'i' from sRGB (45455) to real_gamma, this makes
874              * the images look the same regardless of the gAMA chunk.
875              */
876             conv = real_gamma;
877             conv /= 45455;
878
879             gamma_table[0] = 0;
880
881             for (i=1; i<255; ++i)
882                gamma_table[i] = floorb(pow(i/255.,conv) * 255 + .5);
883
884             gamma_table[255] = 255;
885          }
886       }
887
888       png_set_IHDR(png_ptr, info_ptr, size, ysize, bit_depth, color_type,
889          PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
890
891       if (color_type & PNG_COLOR_MASK_PALETTE)
892       {
893          int npalette;
894          png_color palette[256];
895          png_byte trans[256];
896
897          npalette = generate_palette(palette, trans, bit_depth, gamma_table,
898             colors);
899          png_set_PLTE(png_ptr, info_ptr, palette, npalette);
900
901          if (tRNS)
902             png_set_tRNS(png_ptr, info_ptr, trans, npalette-1,
903                NULL/*transparent color*/);
904
905          /* Reset gamma_table to prevent the image rows being changed */
906          for (npalette=0; npalette<256; ++npalette)
907             gamma_table[npalette] = (png_byte)npalette;
908       }
909
910       else if (tRNS)
911       {
912          png_color_16 col;
913
914          col.red = col.green = col.blue = col.gray =
915             0x0101U & ((1U<<bit_depth)-1U);
916          col.index = 0U;
917          png_set_tRNS(png_ptr, info_ptr, NULL/*trans*/, 1U, &col);
918       }
919
920       if (gamma == PNG_DEFAULT_sRGB)
921          png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_ABSOLUTE);
922
923       else if (gamma > 0) /* Else don't set color space information */
924       {
925          png_set_gAMA_fixed(png_ptr, info_ptr, real_gamma);
926
927          /* Just use the sRGB values here. */
928          png_set_cHRM_fixed(png_ptr, info_ptr,
929             /* color      x       y */
930             /* white */ 31270, 32900,
931             /* red   */ 64000, 33000,
932             /* green */ 30000, 60000,
933             /* blue  */ 15000,  6000
934          );
935       }
936
937       /* Insert extra information. */
938       while (insert != NULL)
939       {
940          insert->insert(png_ptr, info_ptr, insert->nparams, insert->parameters);
941          insert = insert->next;
942       }
943
944       /* Write the file header. */
945       png_write_info(png_ptr, info_ptr);
946
947       /* Restrict the filters */
948       png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, filters);
949
950       {
951 #        ifdef PNG_WRITE_INTERLACING_SUPPORTED
952             int passes = png_set_interlace_handling(png_ptr);
953 #        else /* !WRITE_INTERLACING */
954             int passes = 1;
955 #        endif /* !WRITE_INTERLACING */
956          int pass;
957          size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr);
958
959          row = malloc(rowbytes);
960
961          if (row == NULL)
962             png_error(png_ptr, "OOM allocating row buffer");
963
964          for (pass = 0; pass < passes; ++pass)
965          {
966             unsigned int y;
967
968             for (y=0; y<ysize; ++y)
969             {
970                unsigned int row_filters =
971                   generate_row(row, rowbytes, y, color_type, bit_depth,
972                         gamma_table, conv, colors, small);
973
974                if (row_filters != 0 && filters == PNG_ALL_FILTERS)
975                   png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, row_filters);
976
977                png_write_row(png_ptr, row);
978             }
979          }
980       }
981    }
982
983    /* Finish writing the file. */
984    png_write_end(png_ptr, info_ptr);
985
986    {
987       png_structp nv_ptr = png_ptr;
988       png_infop nv_info = info_ptr;
989
990       png_ptr = NULL;
991       info_ptr = NULL;
992       png_destroy_write_struct(&nv_ptr, &nv_info);
993    }
994    free(row);
995    return 0;
996 }
997
998
999 static size_t
1000 load_file(png_const_charp name, png_bytepp result)
1001 {
1002    FILE *fp = tmpfile();
1003
1004    if (fp != NULL)
1005    {
1006       FILE *ip = fopen(name, "rb");
1007
1008       if (ip != NULL)
1009       {
1010          size_t total = 0;
1011          int ch;
1012
1013          for (;;)
1014          {
1015             ch = getc(ip);
1016             if (ch == EOF) break;
1017             putc(ch, fp);
1018             ++total;
1019          }
1020
1021          if (ferror(ip))
1022          {
1023             perror(name);
1024             fprintf(stderr, "%s: read error\n", name);
1025             (void)fclose(ip);
1026          }
1027
1028          else
1029          {
1030             (void)fclose(ip);
1031
1032             if (ferror(fp))
1033             {
1034                perror("temporary file");
1035                fprintf(stderr, "temporary file write error\n");
1036             }
1037
1038             else
1039             {
1040                rewind(fp);
1041
1042                if (total > 0)
1043                {
1044                   /* Round up to a multiple of 4 here to allow an iCCP profile
1045                    * to be padded to a 4x boundary.
1046                    */
1047                   png_bytep data = malloc((total+3)&~3);
1048
1049                   if (data != NULL)
1050                   {
1051                      size_t new_size = 0;
1052
1053                      for (;;)
1054                      {
1055                         ch = getc(fp);
1056                         if (ch == EOF) break;
1057                         data[new_size++] = (png_byte)ch;
1058                      }
1059
1060                      if (ferror(fp) || new_size != total)
1061                      {
1062                         perror("temporary file");
1063                         fprintf(stderr, "temporary file read error\n");
1064                         free(data);
1065                      }
1066
1067                      else
1068                      {
1069                         (void)fclose(fp);
1070                         *result = data;
1071                         return total;
1072                      }
1073                   }
1074
1075                   else
1076                      fprintf(stderr, "%s: out of memory loading file\n", name);
1077                }
1078
1079                else
1080                   fprintf(stderr, "%s: empty file\n", name);
1081             }
1082          }
1083       }
1084
1085       else
1086       {
1087          perror(name);
1088          fprintf(stderr, "%s: open failed\n", name);
1089       }
1090
1091       fclose(fp);
1092    }
1093
1094    else
1095       fprintf(stderr, "makepng: %s: could not open temporary file\n", name);
1096
1097    exit(1);
1098    return 0;
1099 }
1100
1101 static size_t
1102 load_fake(png_charp param, png_bytepp profile)
1103 {
1104    char *endptr = NULL;
1105    uint64_t size = strtoull(param, &endptr, 0/*base*/);
1106
1107    /* The 'fake' format is <number>*[string] */
1108    if (endptr != NULL && *endptr == '*')
1109    {
1110       size_t len = strlen(++endptr);
1111       size_t result = (size_t)size;
1112
1113       if (len == 0) len = 1; /* capture the terminating '\0' */
1114
1115       /* Now repeat that string to fill 'size' bytes. */
1116       if (result == size && (*profile = malloc(result)) != NULL)
1117       {
1118          png_bytep out = *profile;
1119
1120          if (len == 1)
1121             memset(out, *endptr, result);
1122
1123          else
1124          {
1125             while (size >= len)
1126             {
1127                memcpy(out, endptr, len);
1128                out += len;
1129                size -= len;
1130             }
1131             memcpy(out, endptr, size);
1132          }
1133
1134          return result;
1135       }
1136
1137       else
1138       {
1139          fprintf(stderr, "%s: size exceeds system limits\n", param);
1140          exit(1);
1141       }
1142    }
1143
1144    return 0;
1145 }
1146
1147 static void
1148 check_param_count(int nparams, int expect)
1149 {
1150    if (nparams != expect)
1151    {
1152       fprintf(stderr, "bad parameter count (internal error)\n");
1153       exit(1);
1154    }
1155 }
1156
1157 static void
1158 insert_iCCP(png_structp png_ptr, png_infop info_ptr, int nparams,
1159    png_charpp params)
1160 {
1161    png_bytep profile = NULL;
1162    png_uint_32 proflen = 0;
1163    int result;
1164
1165    check_param_count(nparams, 2);
1166
1167    switch (params[1][0])
1168    {
1169       case '<':
1170          {
1171             size_t filelen = load_file(params[1]+1, &profile);
1172             if (filelen > 0xfffffffc) /* Maximum profile length */
1173             {
1174                fprintf(stderr, "%s: file too long (%lu) for an ICC profile\n",
1175                   params[1]+1, (unsigned long)filelen);
1176                exit(1);
1177             }
1178
1179             proflen = (png_uint_32)filelen;
1180          }
1181          break;
1182
1183       case '0': case '1': case '2': case '3': case '4':
1184       case '5': case '6': case '7': case '8': case '9':
1185          {
1186             size_t fake_len = load_fake(params[1], &profile);
1187
1188             if (fake_len > 0) /* else a simple parameter */
1189             {
1190                if (fake_len > 0xffffffff) /* Maximum profile length */
1191                {
1192                   fprintf(stderr,
1193                      "%s: fake data too long (%lu) for an ICC profile\n",
1194                      params[1], (unsigned long)fake_len);
1195                   exit(1);
1196                }
1197                proflen = (png_uint_32)(fake_len & ~3U);
1198                /* Always fix up the profile length. */
1199                png_save_uint_32(profile, proflen);
1200                break;
1201             }
1202          }
1203
1204       default:
1205          fprintf(stderr, "--insert iCCP \"%s\": unrecognized\n", params[1]);
1206          fprintf(stderr, "  use '<' to read a file: \"<filename\"\n");
1207          exit(1);
1208    }
1209
1210    result = 1;
1211
1212    if (proflen & 3)
1213    {
1214       fprintf(stderr,
1215          "makepng: --insert iCCP %s: profile length made a multiple of 4\n",
1216          params[1]);
1217
1218       /* load_file allocates extra space for this padding, the ICC spec requires
1219        * padding with zero bytes.
1220        */
1221       while (proflen & 3)
1222          profile[proflen++] = 0;
1223    }
1224
1225    if (profile != NULL && proflen > 3)
1226    {
1227       png_uint_32 prof_header = png_get_uint_32(profile);
1228
1229       if (prof_header != proflen)
1230       {
1231          fprintf(stderr, "--insert iCCP %s: profile length field wrong:\n",
1232             params[1]);
1233          fprintf(stderr, "  actual %lu, recorded value %lu (corrected)\n",
1234             (unsigned long)proflen, (unsigned long)prof_header);
1235          png_save_uint_32(profile, proflen);
1236       }
1237    }
1238
1239    if (result && profile != NULL && proflen >=4)
1240       png_set_iCCP(png_ptr, info_ptr, params[0], PNG_COMPRESSION_TYPE_BASE,
1241          profile, proflen);
1242
1243    if (profile)
1244       free(profile);
1245
1246    if (!result)
1247       exit(1);
1248 }
1249
1250 static void
1251 clear_text(png_text *text, png_charp keyword)
1252 {
1253    text->compression = -1; /* none */
1254    text->key = keyword;
1255    text->text = NULL;
1256    text->text_length = 0; /* libpng calculates this */
1257    text->itxt_length = 0; /* libpng calculates this */
1258    text->lang = NULL;
1259    text->lang_key = NULL;
1260 }
1261
1262 static void
1263 set_text(png_structp png_ptr, png_infop info_ptr, png_textp text,
1264    png_charp param)
1265 {
1266    switch (param[0])
1267    {
1268       case '<':
1269          {
1270             png_bytep file = NULL;
1271
1272             text->text_length = load_file(param+1, &file);
1273             text->text = (png_charp)file;
1274          }
1275          break;
1276
1277       case '0': case '1': case '2': case '3': case '4':
1278       case '5': case '6': case '7': case '8': case '9':
1279          {
1280             png_bytep data = NULL;
1281             size_t fake_len = load_fake(param, &data);
1282
1283             if (fake_len > 0) /* else a simple parameter */
1284             {
1285                text->text_length = fake_len;
1286                text->text = (png_charp)data;
1287                break;
1288             }
1289          }
1290
1291       default:
1292          text->text = param;
1293          break;
1294    }
1295
1296    png_set_text(png_ptr, info_ptr, text, 1);
1297
1298    if (text->text != param)
1299       free(text->text);
1300 }
1301
1302 static void
1303 insert_tEXt(png_structp png_ptr, png_infop info_ptr, int nparams,
1304    png_charpp params)
1305 {
1306    png_text text;
1307
1308    check_param_count(nparams, 2);
1309    clear_text(&text, params[0]);
1310    set_text(png_ptr, info_ptr, &text, params[1]);
1311 }
1312
1313 static void
1314 insert_zTXt(png_structp png_ptr, png_infop info_ptr, int nparams,
1315    png_charpp params)
1316 {
1317    png_text text;
1318
1319    check_param_count(nparams, 2);
1320    clear_text(&text, params[0]);
1321    text.compression = 0; /* deflate */
1322    set_text(png_ptr, info_ptr, &text, params[1]);
1323 }
1324
1325 static void
1326 insert_iTXt(png_structp png_ptr, png_infop info_ptr, int nparams,
1327    png_charpp params)
1328 {
1329    png_text text;
1330
1331    check_param_count(nparams, 4);
1332    clear_text(&text, params[0]);
1333    text.compression = 2; /* iTXt + deflate */
1334    text.lang = params[1];/* language tag */
1335    text.lang_key = params[2]; /* translated keyword */
1336    set_text(png_ptr, info_ptr, &text, params[3]);
1337 }
1338
1339 static void
1340 insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams,
1341       png_charpp params)
1342 {
1343    int i;
1344    png_uint_16 freq[256];
1345
1346    /* libpng takes the count from the PLTE count; we don't check it here but we
1347     * do set the array to 0 for unspecified entries.
1348     */
1349    memset(freq, 0, sizeof freq);
1350    for (i=0; i<nparams; ++i)
1351    {
1352       char *endptr = NULL;
1353       unsigned long int l = strtoul(params[i], &endptr, 0/*base*/);
1354
1355       if (params[i][0] && *endptr == 0 && l <= 65535)
1356          freq[i] = (png_uint_16)l;
1357
1358       else
1359       {
1360          fprintf(stderr, "hIST[%d]: %s: invalid frequency\n", i, params[i]);
1361          exit(1);
1362       }
1363    }
1364
1365    png_set_hIST(png_ptr, info_ptr, freq);
1366 }
1367
1368 static png_byte
1369 bval(png_const_structrp png_ptr, png_charp param, unsigned int maxval)
1370 {
1371    char *endptr = NULL;
1372    unsigned long int l = strtoul(param, &endptr, 0/*base*/);
1373
1374    if (param[0] && *endptr == 0 && l <= maxval)
1375       return (png_byte)l;
1376
1377    else
1378       png_error(png_ptr, "sBIT: invalid sBIT value");
1379 }
1380
1381 static void
1382 insert_sBIT(png_structp png_ptr, png_infop info_ptr, int nparams,
1383       png_charpp params)
1384 {
1385    int ct = png_get_color_type(png_ptr, info_ptr);
1386    int c = (ct & PNG_COLOR_MASK_COLOR ? 3 : 1) +
1387       (ct & PNG_COLOR_MASK_ALPHA ? 1 : 0);
1388    unsigned int maxval =
1389       ct & PNG_COLOR_MASK_PALETTE ? 8U : png_get_bit_depth(png_ptr, info_ptr);
1390    png_color_8 sBIT;
1391
1392    if (nparams != c)
1393       png_error(png_ptr, "sBIT: incorrect parameter count");
1394
1395    if (ct & PNG_COLOR_MASK_COLOR)
1396    {
1397       sBIT.red = bval(png_ptr, params[0], maxval);
1398       sBIT.green = bval(png_ptr, params[1], maxval);
1399       sBIT.blue = bval(png_ptr, params[2], maxval);
1400       sBIT.gray = 42;
1401    }
1402
1403    else
1404    {
1405       sBIT.red = sBIT.green = sBIT.blue = 42;
1406       sBIT.gray = bval(png_ptr, params[0], maxval);
1407    }
1408
1409    if (ct & PNG_COLOR_MASK_ALPHA)
1410       sBIT.alpha = bval(png_ptr, params[nparams-1], maxval);
1411
1412    else
1413       sBIT.alpha = 42;
1414
1415    png_set_sBIT(png_ptr, info_ptr, &sBIT);
1416 }
1417
1418 #if 0
1419 static void
1420 insert_sPLT(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params)
1421 {
1422    fprintf(stderr, "insert sPLT: NYI\n");
1423 }
1424 #endif
1425
1426 static int
1427 find_parameters(png_const_charp what, png_charp param, png_charp *list,
1428    int nparams)
1429 {
1430    /* Parameters are separated by '\n' or ':' characters, up to nparams are
1431     * accepted (more is an error) and the number found is returned.
1432     */
1433    int i;
1434    for (i=0; *param && i<nparams; ++i)
1435    {
1436       list[i] = param;
1437       while (*++param)
1438       {
1439          if (*param == '\n' || *param == ':')
1440          {
1441             *param++ = 0; /* Terminate last parameter */
1442             break;        /* And start a new one. */
1443          }
1444       }
1445    }
1446
1447    if (*param)
1448    {
1449       fprintf(stderr, "--insert %s: too many parameters (%s)\n", what, param);
1450       exit(1);
1451    }
1452
1453    list[i] = NULL; /* terminates list */
1454    return i; /* number of parameters filled in */
1455 }
1456
1457 static void
1458 bad_parameter_count(png_const_charp what, int nparams)
1459 {
1460    fprintf(stderr, "--insert %s: bad parameter count %d\n", what, nparams);
1461    exit(1);
1462 }
1463
1464 static chunk_insert *
1465 make_insert(png_const_charp what,
1466    void (*insert)(png_structp, png_infop, int, png_charpp),
1467    int nparams, png_charpp list)
1468 {
1469    int i;
1470    chunk_insert *cip;
1471
1472    cip = malloc(offsetof(chunk_insert,parameters) +
1473       nparams * sizeof (png_charp));
1474
1475    if (cip == NULL)
1476    {
1477       fprintf(stderr, "--insert %s: out of memory allocating %d parameters\n",
1478          what, nparams);
1479       exit(1);
1480    }
1481
1482    cip->next = NULL;
1483    cip->insert = insert;
1484    cip->nparams = nparams;
1485    for (i=0; i<nparams; ++i)
1486       cip->parameters[i] = list[i];
1487
1488    return cip;
1489 }
1490
1491 static chunk_insert *
1492 find_insert(png_const_charp what, png_charp param)
1493 {
1494    png_uint_32 chunk = 0;
1495    png_charp parameter_list[1024];
1496    int i, nparams;
1497
1498    /* Assemble the chunk name */
1499    for (i=0; i<4; ++i)
1500    {
1501       char ch = what[i];
1502
1503       if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))
1504          chunk = (chunk << 8) + what[i];
1505
1506       else
1507          break;
1508    }
1509
1510    if (i < 4 || what[4] != 0)
1511    {
1512       fprintf(stderr, "makepng --insert \"%s\": invalid chunk name\n", what);
1513       exit(1);
1514    }
1515
1516    /* Assemble the parameter list. */
1517    nparams = find_parameters(what, param, parameter_list, 1024);
1518
1519 #  define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d))
1520
1521    switch (chunk)
1522    {
1523       case CHUNK(105,67,67,80):  /* iCCP */
1524          if (nparams == 2)
1525             return make_insert(what, insert_iCCP, nparams, parameter_list);
1526          break;
1527
1528       case CHUNK(116,69,88,116): /* tEXt */
1529          if (nparams == 2)
1530             return make_insert(what, insert_tEXt, nparams, parameter_list);
1531          break;
1532
1533       case CHUNK(122,84,88,116): /* zTXt */
1534          if (nparams == 2)
1535             return make_insert(what, insert_zTXt, nparams, parameter_list);
1536          break;
1537
1538       case CHUNK(105,84,88,116): /* iTXt */
1539          if (nparams == 4)
1540             return make_insert(what, insert_iTXt, nparams, parameter_list);
1541          break;
1542
1543       case CHUNK(104,73,83,84):  /* hIST */
1544          if (nparams <= 256)
1545             return make_insert(what, insert_hIST, nparams, parameter_list);
1546          break;
1547
1548       case CHUNK(115,66,73,84): /* sBIT */
1549          if (nparams <= 4)
1550             return make_insert(what, insert_sBIT, nparams, parameter_list);
1551          break;
1552
1553 #if 0
1554       case CHUNK(115,80,76,84):  /* sPLT */
1555          return make_insert(what, insert_sPLT, nparams, parameter_list);
1556 #endif
1557
1558       default:
1559          fprintf(stderr, "makepng --insert \"%s\": unrecognized chunk name\n",
1560             what);
1561          exit(1);
1562    }
1563
1564    bad_parameter_count(what, nparams);
1565    return NULL;
1566 }
1567
1568 /* This is necessary because libpng expects writeable strings for things like
1569  * text chunks (maybe this should be fixed...)
1570  */
1571 static png_charp
1572 strstash(png_const_charp foo)
1573 {
1574    /* The program indicates a memory allocation error by crashing, this is by
1575     * design.
1576     */
1577    if (foo != NULL)
1578    {
1579       png_charp bar = malloc(strlen(foo)+1);
1580       return strcpy(bar, foo);
1581    }
1582
1583    return NULL;
1584 }
1585
1586 static png_charp
1587 strstash_list(const png_const_charp *text)
1588 {
1589    size_t foo = 0;
1590    png_charp result, bar;
1591    const png_const_charp *line = text;
1592
1593    while (*line != NULL)
1594       foo += strlen(*line++);
1595
1596    result = bar = malloc(foo+1);
1597
1598    line = text;
1599    while (*line != NULL)
1600    {
1601       foo = strlen(*line);
1602       memcpy(bar, *line++, foo);
1603       bar += foo;
1604    }
1605
1606    *bar = 0;
1607    return result;
1608 }
1609
1610 /* These are used to insert Copyright and Licence fields, they allow the text to
1611  * have \n unlike the --insert option.
1612  */
1613 static chunk_insert *
1614 add_tEXt(const char *key, const png_const_charp *text)
1615 {
1616    static char what[5] = { 116, 69, 88, 116, 0 };
1617    png_charp parameter_list[3];
1618
1619    parameter_list[0] = strstash(key);
1620    parameter_list[1] = strstash_list(text);
1621    parameter_list[2] = NULL;
1622
1623    return make_insert(what, insert_tEXt, 2, parameter_list);
1624 }
1625
1626 static chunk_insert *
1627 add_iTXt(const char *key, const char *language, const char *language_key,
1628       const png_const_charp *text)
1629 {
1630    static char what[5] = { 105, 84, 88, 116, 0 };
1631    png_charp parameter_list[5];
1632
1633    parameter_list[0] = strstash(key);
1634    parameter_list[1] = strstash(language);
1635    parameter_list[2] = strstash(language_key);
1636    parameter_list[3] = strstash_list(text);
1637    parameter_list[4] = NULL;
1638
1639    return make_insert(what, insert_iTXt, 4, parameter_list);
1640 }
1641
1642 /* This is a not-very-good parser for a sequence of numbers (including 0).  It
1643  * doesn't accept some apparently valid things, but it accepts all the sensible
1644  * combinations.
1645  */
1646 static void
1647 parse_color(char *arg, unsigned int *colors)
1648 {
1649    unsigned int ncolors = 0;
1650
1651    while (*arg && ncolors < 4)
1652    {
1653       char *ep = arg;
1654
1655       unsigned long ul = strtoul(arg, &ep, 0);
1656
1657       if (ul > 65535)
1658       {
1659          fprintf(stderr, "makepng --color=...'%s': too big\n", arg);
1660          exit(1);
1661       }
1662
1663       if (ep == arg)
1664       {
1665          fprintf(stderr, "makepng --color=...'%s': not a valid color\n", arg);
1666          exit(1);
1667       }
1668
1669       if (*ep) ++ep; /* skip a separator */
1670       arg = ep;
1671
1672       colors[++ncolors] = (unsigned int)ul; /* checked above */
1673    }
1674
1675    if (*arg)
1676    {
1677       fprintf(stderr, "makepng --color=...'%s': too many values\n", arg);
1678       exit(1);
1679    }
1680
1681    *colors = ncolors;
1682 }
1683
1684 int
1685 main(int argc, char **argv)
1686 {
1687    FILE *fp = stdout;
1688    const char *file_name = NULL;
1689    int color_type = 8; /* invalid */
1690    int bit_depth = 32; /* invalid */
1691    int small = 0; /* make full size images */
1692    int tRNS = 0; /* don't output a tRNS chunk */
1693    unsigned int colors[5];
1694    unsigned int filters = PNG_ALL_FILTERS;
1695    png_fixed_point gamma = 0; /* not set */
1696    chunk_insert *head_insert = NULL;
1697    chunk_insert **insert_ptr = &head_insert;
1698
1699    memset(colors, 0, sizeof colors);
1700
1701    while (--argc > 0)
1702    {
1703       char *arg = *++argv;
1704
1705       if (strcmp(arg, "--small") == 0)
1706       {
1707          small = 1;
1708          continue;
1709       }
1710
1711       if (strcmp(arg, "--tRNS") == 0)
1712       {
1713          tRNS = 1;
1714          continue;
1715       }
1716
1717       if (strcmp(arg, "--sRGB") == 0)
1718       {
1719          gamma = PNG_DEFAULT_sRGB;
1720          continue;
1721       }
1722
1723       if (strcmp(arg, "--linear") == 0)
1724       {
1725          gamma = PNG_FP_1;
1726          continue;
1727       }
1728
1729       if (strcmp(arg, "--1.8") == 0)
1730       {
1731          gamma = PNG_GAMMA_MAC_18;
1732          continue;
1733       }
1734
1735       if (strcmp(arg, "--nofilters") == 0)
1736       {
1737          filters = PNG_FILTER_NONE;
1738          continue;
1739       }
1740
1741       if (strncmp(arg, "--color=", 8) == 0)
1742       {
1743           parse_color(arg+8, colors);
1744           continue;
1745       }
1746
1747       if (argc >= 3 && strcmp(arg, "--insert") == 0)
1748       {
1749          png_const_charp what = *++argv;
1750          png_charp param = *++argv;
1751          chunk_insert *new_insert;
1752
1753          argc -= 2;
1754
1755          new_insert = find_insert(what, param);
1756
1757          if (new_insert != NULL)
1758          {
1759             *insert_ptr = new_insert;
1760             insert_ptr = &new_insert->next;
1761          }
1762
1763          continue;
1764       }
1765
1766       if (arg[0] == '-')
1767       {
1768          fprintf(stderr, "makepng: %s: invalid option\n", arg);
1769          exit(1);
1770       }
1771
1772       if (strcmp(arg, "palette") == 0)
1773       {
1774          color_type = PNG_COLOR_TYPE_PALETTE;
1775          continue;
1776       }
1777
1778       if (strncmp(arg, "gray", 4) == 0)
1779       {
1780          if (arg[4] == 0)
1781          {
1782             color_type = PNG_COLOR_TYPE_GRAY;
1783             continue;
1784          }
1785
1786          else if (strcmp(arg+4, "a") == 0 ||
1787             strcmp(arg+4, "alpha") == 0 ||
1788             strcmp(arg+4, "-alpha") == 0)
1789          {
1790             color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
1791             continue;
1792          }
1793       }
1794
1795       if (strncmp(arg, "rgb", 3) == 0)
1796       {
1797          if (arg[3] == 0)
1798          {
1799             color_type = PNG_COLOR_TYPE_RGB;
1800             continue;
1801          }
1802
1803          else if (strcmp(arg+3, "a") == 0 ||
1804             strcmp(arg+3, "alpha") == 0 ||
1805             strcmp(arg+3, "-alpha") == 0)
1806          {
1807             color_type = PNG_COLOR_TYPE_RGB_ALPHA;
1808             continue;
1809          }
1810       }
1811
1812       if (color_type == 8 && isdigit(arg[0]))
1813       {
1814          color_type = atoi(arg);
1815          if (color_type < 0 || color_type > 6 || color_type == 1 ||
1816             color_type == 5)
1817          {
1818             fprintf(stderr, "makepng: %s: not a valid color type\n", arg);
1819             exit(1);
1820          }
1821
1822          continue;
1823       }
1824
1825       if (bit_depth == 32 && isdigit(arg[0]))
1826       {
1827          bit_depth = atoi(arg);
1828          if (bit_depth <= 0 || bit_depth > 16 ||
1829             (bit_depth & -bit_depth) != bit_depth)
1830          {
1831             fprintf(stderr, "makepng: %s: not a valid bit depth\n", arg);
1832             exit(1);
1833          }
1834
1835          continue;
1836       }
1837
1838       if (argc == 1) /* It's the file name */
1839       {
1840          fp = fopen(arg, "wb");
1841          if (fp == NULL)
1842          {
1843             fprintf(stderr, "%s: %s: could not open\n", arg, strerror(errno));
1844             exit(1);
1845          }
1846
1847          file_name = arg;
1848          continue;
1849       }
1850
1851       fprintf(stderr, "makepng: %s: unknown argument\n", arg);
1852       exit(1);
1853    } /* argument while loop */
1854
1855    if (color_type == 8 || bit_depth == 32)
1856    {
1857       fprintf(stderr, "usage: makepng [--small] [--sRGB|--linear|--1.8] "
1858          "[--color=...] color-type bit-depth [file-name]\n"
1859          "  Make a test PNG file, by default writes to stdout.\n"
1860          "  Other options are available, UTSL.\n");
1861       exit(1);
1862    }
1863
1864    /* Check the colors */
1865    {
1866       unsigned int lim = (color_type == PNG_COLOR_TYPE_PALETTE ? 255U :
1867          (1U<<bit_depth)-1);
1868       unsigned int i;
1869
1870       for (i=1; i<=colors[0]; ++i)
1871          if (colors[i] > lim)
1872          {
1873             fprintf(stderr, "makepng: --color=...: %u out of range [0..%u]\n",
1874                colors[i], lim);
1875             exit(1);
1876          }
1877    }
1878
1879    /* small and colors are incompatible (will probably crash if both are used at
1880     * the same time!)
1881     */
1882    if (small && colors[0] != 0)
1883    {
1884       fprintf(stderr, "makepng: --color --small: only one at a time!\n");
1885       exit(1);
1886    }
1887
1888    /* Restrict the filters for more speed to those we know are used for the
1889     * generated images.
1890     */
1891    if (filters == PNG_ALL_FILTERS && !small/*small provides defaults*/)
1892    {
1893       if ((color_type & PNG_COLOR_MASK_PALETTE) != 0 || bit_depth < 8)
1894          filters = PNG_FILTER_NONE;
1895
1896       else if (color_type & PNG_COLOR_MASK_COLOR) /* rgb */
1897       {
1898          if (bit_depth == 8)
1899             filters &= ~(PNG_FILTER_NONE | PNG_FILTER_AVG);
1900
1901          else
1902             filters = PNG_FILTER_SUB | PNG_FILTER_PAETH;
1903       }
1904
1905       else /* gray 8 or 16-bit */
1906          filters &= ~PNG_FILTER_NONE;
1907    }
1908
1909    /* Insert standard copyright and licence text. */
1910    {
1911       static png_const_charp copyright[] =
1912       {
1913          COPYRIGHT, /* ISO-Latin-1 */
1914          NULL
1915       };
1916       static png_const_charp licensing[] =
1917       {
1918          IMAGE_LICENSING, /* UTF-8 */
1919          NULL
1920       };
1921
1922       chunk_insert *new_insert;
1923
1924       new_insert = add_tEXt("Copyright", copyright);
1925       if (new_insert != NULL)
1926       {
1927          *insert_ptr = new_insert;
1928          insert_ptr = &new_insert->next;
1929       }
1930
1931       new_insert = add_iTXt("Licensing", "en", NULL, licensing);
1932       if (new_insert != NULL)
1933       {
1934          *insert_ptr = new_insert;
1935          insert_ptr = &new_insert->next;
1936       }
1937    }
1938
1939    {
1940       int ret = write_png(&file_name, fp, color_type, bit_depth, gamma,
1941          head_insert, filters, colors, small, tRNS);
1942
1943       if (ret != 0 && file_name != NULL)
1944          remove(file_name);
1945
1946       return ret;
1947    }
1948 }