55d094592a4b4bd28f7fbf2eb0a6be844c034936
[platform/upstream/libpng.git] / contrib / libtests / pngvalid.c
1
2 /* pngvalid.c - validate libpng by constructing then reading png files.
3  *
4  * Last changed in libpng 1.6.21 [January 15, 2016]
5  * Copyright (c) 2014-2016 Glenn Randers-Pehrson
6  * Written by John Cunningham Bowler
7  *
8  * This code is released under the libpng license.
9  * For conditions of distribution and use, see the disclaimer
10  * and license in png.h
11  *
12  * NOTES:
13  *   This is a C program that is intended to be linked against libpng.  It
14  *   generates bitmaps internally, stores them as PNG files (using the
15  *   sequential write code) then reads them back (using the sequential
16  *   read code) and validates that the result has the correct data.
17  *
18  *   The program can be modified and extended to test the correctness of
19  *   transformations performed by libpng.
20  */
21
22 #define _POSIX_SOURCE 1
23 #define _ISOC99_SOURCE 1 /* For floating point */
24 #define _GNU_SOURCE 1 /* For the floating point exception extension */
25
26 #include <signal.h>
27 #include <stdio.h>
28
29 #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
30 #  include <config.h>
31 #endif
32
33 #ifdef HAVE_FEENABLEEXCEPT /* from config.h, if included */
34 #  include <fenv.h>
35 #endif
36
37 #ifndef FE_DIVBYZERO
38 #  define FE_DIVBYZERO 0
39 #endif
40 #ifndef FE_INVALID
41 #  define FE_INVALID 0
42 #endif
43 #ifndef FE_OVERFLOW
44 #  define FE_OVERFLOW 0
45 #endif
46
47 /* Define the following to use this test against your installed libpng, rather
48  * than the one being built here:
49  */
50 #ifdef PNG_FREESTANDING_TESTS
51 #  include <png.h>
52 #else
53 #  include "../../png.h"
54 #endif
55
56 #ifdef PNG_ZLIB_HEADER
57 #  include PNG_ZLIB_HEADER
58 #else
59 #  include <zlib.h>   /* For crc32 */
60 #endif
61
62 /* 1.6.1 added support for the configure test harness, which uses 77 to indicate
63  * a skipped test, in earlier versions we need to succeed on a skipped test, so:
64  */
65 #if PNG_LIBPNG_VER < 10601
66 #  define SKIP 0
67 #else
68 #  define SKIP 77
69 #endif
70
71 /* pngvalid requires write support and one of the fixed or floating point APIs.
72  */
73 #if defined(PNG_WRITE_SUPPORTED) &&\
74    (defined(PNG_FIXED_POINT_SUPPORTED) || defined(PNG_FLOATING_POINT_SUPPORTED))
75
76 #if PNG_LIBPNG_VER < 10500
77 /* This deliberately lacks the const. */
78 typedef png_byte *png_const_bytep;
79
80 /* This is copied from 1.5.1 png.h: */
81 #define PNG_INTERLACE_ADAM7_PASSES 7
82 #define PNG_PASS_START_ROW(pass) (((1U&~(pass))<<(3-((pass)>>1)))&7)
83 #define PNG_PASS_START_COL(pass) (((1U& (pass))<<(3-(((pass)+1)>>1)))&7)
84 #define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3)
85 #define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3)
86 #define PNG_PASS_ROWS(height, pass) (((height)+(((1<<PNG_PASS_ROW_SHIFT(pass))\
87    -1)-PNG_PASS_START_ROW(pass)))>>PNG_PASS_ROW_SHIFT(pass))
88 #define PNG_PASS_COLS(width, pass) (((width)+(((1<<PNG_PASS_COL_SHIFT(pass))\
89    -1)-PNG_PASS_START_COL(pass)))>>PNG_PASS_COL_SHIFT(pass))
90 #define PNG_ROW_FROM_PASS_ROW(yIn, pass) \
91    (((yIn)<<PNG_PASS_ROW_SHIFT(pass))+PNG_PASS_START_ROW(pass))
92 #define PNG_COL_FROM_PASS_COL(xIn, pass) \
93    (((xIn)<<PNG_PASS_COL_SHIFT(pass))+PNG_PASS_START_COL(pass))
94 #define PNG_PASS_MASK(pass,off) ( \
95    ((0x110145AFU>>(((7-(off))-(pass))<<2)) & 0xFU) | \
96    ((0x01145AF0U>>(((7-(off))-(pass))<<2)) & 0xF0U))
97 #define PNG_ROW_IN_INTERLACE_PASS(y, pass) \
98    ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1)
99 #define PNG_COL_IN_INTERLACE_PASS(x, pass) \
100    ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1)
101
102 /* These are needed too for the default build: */
103 #define PNG_WRITE_16BIT_SUPPORTED
104 #define PNG_READ_16BIT_SUPPORTED
105
106 /* This comes from pnglibconf.h afer 1.5: */
107 #define PNG_FP_1 100000
108 #define PNG_GAMMA_THRESHOLD_FIXED\
109    ((png_fixed_point)(PNG_GAMMA_THRESHOLD * PNG_FP_1))
110 #endif
111
112 #if PNG_LIBPNG_VER < 10600
113    /* 1.6.0 constifies many APIs, the following exists to allow pngvalid to be
114     * compiled against earlier versions.
115     */
116 #  define png_const_structp png_structp
117 #endif
118
119 #ifndef RELEASE_BUILD
120    /* RELEASE_BUILD is true for releases and release candidates: */
121 #  define RELEASE_BUILD (PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC)
122 #endif
123 #if RELEASE_BUILD
124 #   define debugonly(something)
125 #else /* !RELEASE_BUILD */
126 #   define debugonly(something) something
127 #endif /* !RELEASE_BUILD */
128
129 #include <float.h>  /* For floating point constants */
130 #include <stdlib.h> /* For malloc */
131 #include <string.h> /* For memcpy, memset */
132 #include <math.h>   /* For floor */
133
134 /* Unused formal parameter errors are removed using the following macro which is
135  * expected to have no bad effects on performance.
136  */
137 #ifndef UNUSED
138 #  if defined(__GNUC__) || defined(_MSC_VER)
139 #     define UNUSED(param) (void)param;
140 #  else
141 #     define UNUSED(param)
142 #  endif
143 #endif
144
145 /***************************** EXCEPTION HANDLING *****************************/
146 #ifdef PNG_FREESTANDING_TESTS
147 #  include <cexcept.h>
148 #else
149 #  include "../visupng/cexcept.h"
150 #endif
151
152 #ifdef __cplusplus
153 #  define this not_the_cpp_this
154 #  define new not_the_cpp_new
155 #  define voidcast(type, value) static_cast<type>(value)
156 #else
157 #  define voidcast(type, value) (value)
158 #endif /* __cplusplus */
159
160 struct png_store;
161 define_exception_type(struct png_store*);
162
163 /* The following are macros to reduce typing everywhere where the well known
164  * name 'the_exception_context' must be defined.
165  */
166 #define anon_context(ps) struct exception_context *the_exception_context = \
167    &(ps)->exception_context
168 #define context(ps,fault) anon_context(ps); png_store *fault
169
170 /* This macro returns the number of elements in an array as an (unsigned int),
171  * it is necessary to avoid the inability of certain versions of GCC to use
172  * the value of a compile-time constant when performing range checks.  It must
173  * be passed an array name.
174  */
175 #define ARRAY_SIZE(a) ((unsigned int)((sizeof (a))/(sizeof (a)[0])))
176
177 /* GCC BUG 66447 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66447) requires
178  * some broken GCC versions to be fixed up to avoid invalid whining about auto
179  * variables that are *not* changed within the scope of a setjmp being changed.
180  *
181  * Feel free to extend the list of broken versions.
182  */
183 #define is_gnu(major,minor)\
184    (defined __GNUC__) && __GNUC__ == (major) && __GNUC_MINOR__ == (minor)
185 #define is_gnu_patch(major,minor,patch)\
186    is_gnu(major,minor) && __GNUC_PATCHLEVEL__ == 0
187 /* For the moment just do it always; all versions of GCC seem to be broken: */
188 #ifdef __GNUC__
189    const void * volatile make_volatile_for_gnu;
190 #  define gnu_volatile(x) make_volatile_for_gnu = &x;
191 #else /* !GNUC broken versions */
192 #  define gnu_volatile(x)
193 #endif /* !GNUC broken versions */
194
195 /******************************* UTILITIES ************************************/
196 /* Error handling is particularly problematic in production code - error
197  * handlers often themselves have bugs which lead to programs that detect
198  * minor errors crashing.  The following functions deal with one very
199  * common class of errors in error handlers - attempting to format error or
200  * warning messages into buffers that are too small.
201  */
202 static size_t safecat(char *buffer, size_t bufsize, size_t pos,
203    const char *cat)
204 {
205    while (pos < bufsize && cat != NULL && *cat != 0)
206       buffer[pos++] = *cat++;
207
208    if (pos >= bufsize)
209       pos = bufsize-1;
210
211    buffer[pos] = 0;
212    return pos;
213 }
214
215 static size_t safecatn(char *buffer, size_t bufsize, size_t pos, int n)
216 {
217    char number[64];
218    sprintf(number, "%d", n);
219    return safecat(buffer, bufsize, pos, number);
220 }
221
222 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
223 static size_t safecatd(char *buffer, size_t bufsize, size_t pos, double d,
224     int precision)
225 {
226    char number[64];
227    sprintf(number, "%.*f", precision, d);
228    return safecat(buffer, bufsize, pos, number);
229 }
230 #endif
231
232 static const char invalid[] = "invalid";
233 static const char sep[] = ": ";
234
235 static const char *colour_types[8] =
236 {
237    "grayscale", invalid, "truecolour", "indexed-colour",
238    "grayscale with alpha", invalid, "truecolour with alpha", invalid
239 };
240
241 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
242 /* Convert a double precision value to fixed point. */
243 static png_fixed_point
244 fix(double d)
245 {
246    d = floor(d * PNG_FP_1 + .5);
247    return (png_fixed_point)d;
248 }
249 #endif /* PNG_READ_SUPPORTED */
250
251 /* Generate random bytes.  This uses a boring repeatable algorithm and it
252  * is implemented here so that it gives the same set of numbers on every
253  * architecture.  It's a linear congruential generator (Knuth or Sedgewick
254  * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
255  * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise
256  * Generation.)
257  */
258 static void
259 make_random_bytes(png_uint_32* seed, void* pv, size_t size)
260 {
261    png_uint_32 u0 = seed[0], u1 = seed[1];
262    png_bytep bytes = voidcast(png_bytep, pv);
263
264    /* There are thirty three bits, the next bit in the sequence is bit-33 XOR
265     * bit-20.  The top 1 bit is in u1, the bottom 32 are in u0.
266     */
267    size_t i;
268    for (i=0; i<size; ++i)
269    {
270       /* First generate 8 new bits then shift them in at the end. */
271       png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
272       u1 <<= 8;
273       u1 |= u0 >> 24;
274       u0 <<= 8;
275       u0 |= u;
276       *bytes++ = (png_byte)u;
277    }
278
279    seed[0] = u0;
280    seed[1] = u1;
281 }
282
283 static void
284 make_four_random_bytes(png_uint_32* seed, png_bytep bytes)
285 {
286    make_random_bytes(seed, bytes, 4);
287 }
288
289 #if defined PNG_READ_SUPPORTED || defined PNG_WRITE_tRNS_SUPPORTED ||\
290     defined PNG_WRITE_FILTER_SUPPORTED
291 static void
292 randomize(void *pv, size_t size)
293 {
294    static png_uint_32 random_seed[2] = {0x56789abc, 0xd};
295    make_random_bytes(random_seed, pv, size);
296 }
297
298 #define R8(this) randomize(&(this), sizeof (this))
299
300 static void r16(png_uint_16p p16, size_t count)
301 {
302    size_t i;
303
304    for (i=0; i<count; ++i)
305    {
306       unsigned char b2[2];
307       randomize(b2, sizeof b2);
308       *p16++ = png_get_uint_16(b2);
309    }
310 }
311
312 #ifdef __COVERITY__
313 #  define R16(this)\
314    r16(&(this), (sizeof (this))/2U/*(sizeof (png_uint_16))*/)
315 #else
316 #  define R16(this)\
317    r16(&(this), (sizeof (this))/(sizeof (png_uint_16)))
318 #endif
319
320 #if defined PNG_READ_RGB_TO_GRAY_SUPPORTED ||\
321     defined PNG_READ_FILLER_SUPPORTED
322 static void r32(png_uint_32p p32, size_t count)
323 {
324    size_t i;
325
326    for (i=0; i<count; ++i)
327    {
328       unsigned char b4[4];
329       randomize(b4, sizeof b4);
330       *p32++ = png_get_uint_32(b4);
331    }
332 }
333
334 #ifdef __COVERITY__
335 #  define R32(this)\
336    r32(&(this), (sizeof (this))/4U/*(sizeof (png_uint_32))*/)
337 #else
338 #  define R32(this)\
339    r32(&(this), (sizeof (this))/(sizeof (png_uint_32)))
340 #endif
341
342 #endif /* READ_FILLER || READ_RGB_TO_GRAY */
343
344 #endif /* READ || WRITE_tRNS || WRITE_FILTER */
345
346 #if defined PNG_READ_TRANSFORMS_SUPPORTED ||\
347     defined PNG_WRITE_FILTER_SUPPORTED
348 static unsigned int
349 random_mod(unsigned int max)
350 {
351    png_uint_16 x;
352
353    R16(x);
354
355    return x % max; /* 0 .. max-1 */
356 }
357 #endif /* READ_TRANSFORMS || WRITE_FILTER */
358
359 #if (defined PNG_READ_RGB_TO_GRAY_SUPPORTED) ||\
360     (defined PNG_READ_FILLER_SUPPORTED)
361 static int
362 random_choice(void)
363 {
364    unsigned char x;
365
366    R8(x);
367
368    return x & 1;
369 }
370 #endif /* READ_RGB_TO_GRAY || READ_FILLER */
371
372 /* A numeric ID based on PNG file characteristics.  The 'do_interlace' field
373  * simply records whether pngvalid did the interlace itself or whether it
374  * was done by libpng.  Width and height must be less than 256.  'palette' is an
375  * index of the palette to use for formats with a palette otherwise a boolean
376  * indicating if a tRNS chunk was generated.
377  */
378 #define FILEID(col, depth, palette, interlace, width, height, do_interlace) \
379    ((png_uint_32)((col) + ((depth)<<3) + ((palette)<<8) + ((interlace)<<13) + \
380     (((do_interlace)!=0)<<15) + ((width)<<16) + ((height)<<24)))
381
382 #define COL_FROM_ID(id) ((png_byte)((id)& 0x7U))
383 #define DEPTH_FROM_ID(id) ((png_byte)(((id) >> 3) & 0x1fU))
384 #define PALETTE_FROM_ID(id) (((id) >> 8) & 0x1f)
385 #define INTERLACE_FROM_ID(id) ((png_byte)(((id) >> 13) & 0x3))
386 #define DO_INTERLACE_FROM_ID(id) ((int)(((id)>>15) & 1))
387 #define WIDTH_FROM_ID(id) (((id)>>16) & 0xff)
388 #define HEIGHT_FROM_ID(id) (((id)>>24) & 0xff)
389
390 /* Utility to construct a standard name for a standard image. */
391 static size_t
392 standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type,
393     int bit_depth, unsigned int npalette, int interlace_type,
394     png_uint_32 w, png_uint_32 h, int do_interlace)
395 {
396    pos = safecat(buffer, bufsize, pos, colour_types[colour_type]);
397    if (colour_type == 3) /* must have a palette */
398    {
399       pos = safecat(buffer, bufsize, pos, "[");
400       pos = safecatn(buffer, bufsize, pos, npalette);
401       pos = safecat(buffer, bufsize, pos, "]");
402    }
403
404    else if (npalette != 0)
405       pos = safecat(buffer, bufsize, pos, "+tRNS");
406
407    pos = safecat(buffer, bufsize, pos, " ");
408    pos = safecatn(buffer, bufsize, pos, bit_depth);
409    pos = safecat(buffer, bufsize, pos, " bit");
410
411    if (interlace_type != PNG_INTERLACE_NONE)
412    {
413       pos = safecat(buffer, bufsize, pos, " interlaced");
414       if (do_interlace)
415          pos = safecat(buffer, bufsize, pos, "(pngvalid)");
416       else
417          pos = safecat(buffer, bufsize, pos, "(libpng)");
418    }
419
420    if (w > 0 || h > 0)
421    {
422       pos = safecat(buffer, bufsize, pos, " ");
423       pos = safecatn(buffer, bufsize, pos, w);
424       pos = safecat(buffer, bufsize, pos, "x");
425       pos = safecatn(buffer, bufsize, pos, h);
426    }
427
428    return pos;
429 }
430
431 static size_t
432 standard_name_from_id(char *buffer, size_t bufsize, size_t pos, png_uint_32 id)
433 {
434    return standard_name(buffer, bufsize, pos, COL_FROM_ID(id),
435       DEPTH_FROM_ID(id), PALETTE_FROM_ID(id), INTERLACE_FROM_ID(id),
436       WIDTH_FROM_ID(id), HEIGHT_FROM_ID(id), DO_INTERLACE_FROM_ID(id));
437 }
438
439 /* Convenience API and defines to list valid formats.  Note that 16 bit read and
440  * write support is required to do 16 bit read tests (we must be able to make a
441  * 16 bit image to test!)
442  */
443 #ifdef PNG_WRITE_16BIT_SUPPORTED
444 #  define WRITE_BDHI 4
445 #  ifdef PNG_READ_16BIT_SUPPORTED
446 #     define READ_BDHI 4
447 #     define DO_16BIT
448 #  endif
449 #else
450 #  define WRITE_BDHI 3
451 #endif
452 #ifndef DO_16BIT
453 #  define READ_BDHI 3
454 #endif
455
456 /* The following defines the number of different palettes to generate for
457  * each log bit depth of a colour type 3 standard image.
458  */
459 #define PALETTE_COUNT(bit_depth) ((bit_depth) > 4 ? 1U : 16U)
460
461 static int
462 next_format(png_bytep colour_type, png_bytep bit_depth,
463    unsigned int* palette_number, int low_depth_gray, int tRNS)
464 {
465    if (*bit_depth == 0)
466    {
467       *colour_type = 0;
468       if (low_depth_gray)
469          *bit_depth = 1;
470       else
471          *bit_depth = 8;
472       *palette_number = 0;
473       return 1;
474    }
475
476    if  (*colour_type < 4/*no alpha channel*/)
477    {
478       /* Add multiple palettes for colour type 3, one image with tRNS
479        * and one without for other non-alpha formats:
480        */
481       unsigned int pn = ++*palette_number;
482       png_byte ct = *colour_type;
483
484       if (((ct == 0/*GRAY*/ || ct/*RGB*/ == 2) && tRNS && pn < 2) ||
485           (ct == 3/*PALETTE*/ && pn < PALETTE_COUNT(*bit_depth)))
486          return 1;
487
488       /* No: next bit depth */
489       *palette_number = 0;
490    }
491
492    *bit_depth = (png_byte)(*bit_depth << 1);
493
494    /* Palette images are restricted to 8 bit depth */
495    if (*bit_depth <= 8
496 #ifdef DO_16BIT
497          || (*colour_type != 3 && *bit_depth <= 16)
498 #endif
499       )
500       return 1;
501
502    /* Move to the next color type, or return 0 at the end. */
503    switch (*colour_type)
504    {
505       case 0:
506          *colour_type = 2;
507          *bit_depth = 8;
508          return 1;
509
510       case 2:
511          *colour_type = 3;
512          *bit_depth = 1;
513          return 1;
514
515       case 3:
516          *colour_type = 4;
517          *bit_depth = 8;
518          return 1;
519
520       case 4:
521          *colour_type = 6;
522          *bit_depth = 8;
523          return 1;
524
525       default:
526          return 0;
527    }
528 }
529
530 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
531 static unsigned int
532 sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth,
533     png_uint_32 x, unsigned int sample_index, int swap16, int littleendian)
534 {
535    png_uint_32 bit_index, result;
536
537    /* Find a sample index for the desired sample: */
538    x *= bit_depth;
539    bit_index = x;
540
541    if ((colour_type & 1) == 0) /* !palette */
542    {
543       if (colour_type & 2)
544          bit_index *= 3;
545
546       if (colour_type & 4)
547          bit_index += x; /* Alpha channel */
548
549       /* Multiple channels; select one: */
550       if (colour_type & (2+4))
551          bit_index += sample_index * bit_depth;
552    }
553
554    /* Return the sample from the row as an integer. */
555    row += bit_index >> 3;
556    result = *row;
557
558    if (bit_depth == 8)
559       return result;
560
561    else if (bit_depth > 8)
562    {
563       if (swap16)
564          return (*++row << 8) + result;
565       else
566          return (result << 8) + *++row;
567    }
568
569    /* Less than 8 bits per sample.  By default PNG has the big end of
570     * the egg on the left of the screen, but if littleendian is set
571     * then the big end is on the right.
572     */
573    bit_index &= 7;
574
575    if (!littleendian)
576       bit_index = 8-bit_index-bit_depth;
577
578    return (result >> bit_index) & ((1U<<bit_depth)-1);
579 }
580 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
581
582 /* Copy a single pixel, of a given size, from one buffer to another -
583  * while this is basically bit addressed there is an implicit assumption
584  * that pixels 8 or more bits in size are byte aligned and that pixels
585  * do not otherwise cross byte boundaries.  (This is, so far as I know,
586  * universally true in bitmap computer graphics.  [JCB 20101212])
587  *
588  * NOTE: The to and from buffers may be the same.
589  */
590 static void
591 pixel_copy(png_bytep toBuffer, png_uint_32 toIndex,
592    png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize,
593    int littleendian)
594 {
595    /* Assume we can multiply by 'size' without overflow because we are
596     * just working in a single buffer.
597     */
598    toIndex *= pixelSize;
599    fromIndex *= pixelSize;
600    if (pixelSize < 8) /* Sub-byte */
601    {
602       /* Mask to select the location of the copied pixel: */
603       unsigned int destMask = ((1U<<pixelSize)-1) <<
604          (littleendian ? toIndex&7 : 8-pixelSize-(toIndex&7));
605       /* The following read the entire pixels and clears the extra: */
606       unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask;
607       unsigned int sourceByte = fromBuffer[fromIndex >> 3];
608
609       /* Don't rely on << or >> supporting '0' here, just in case: */
610       fromIndex &= 7;
611       if (littleendian)
612       {
613          if (fromIndex > 0) sourceByte >>= fromIndex;
614          if ((toIndex & 7) > 0) sourceByte <<= toIndex & 7;
615       }
616
617       else
618       {
619          if (fromIndex > 0) sourceByte <<= fromIndex;
620          if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7;
621       }
622
623       toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask));
624    }
625    else /* One or more bytes */
626       memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3);
627 }
628
629 #ifdef PNG_READ_SUPPORTED
630 /* Copy a complete row of pixels, taking into account potential partial
631  * bytes at the end.
632  */
633 static void
634 row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth,
635       int littleendian)
636 {
637    memcpy(toBuffer, fromBuffer, bitWidth >> 3);
638
639    if ((bitWidth & 7) != 0)
640    {
641       unsigned int mask;
642
643       toBuffer += bitWidth >> 3;
644       fromBuffer += bitWidth >> 3;
645       if (littleendian)
646          mask = 0xff << (bitWidth & 7);
647       else
648          mask = 0xff >> (bitWidth & 7);
649       *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask));
650    }
651 }
652
653 /* Compare pixels - they are assumed to start at the first byte in the
654  * given buffers.
655  */
656 static int
657 pixel_cmp(png_const_bytep pa, png_const_bytep pb, png_uint_32 bit_width)
658 {
659 #if PNG_LIBPNG_VER < 10506
660    if (memcmp(pa, pb, bit_width>>3) == 0)
661    {
662       png_uint_32 p;
663
664       if ((bit_width & 7) == 0) return 0;
665
666       /* Ok, any differences? */
667       p = pa[bit_width >> 3];
668       p ^= pb[bit_width >> 3];
669
670       if (p == 0) return 0;
671
672       /* There are, but they may not be significant, remove the bits
673        * after the end (the low order bits in PNG.)
674        */
675       bit_width &= 7;
676       p >>= 8-bit_width;
677
678       if (p == 0) return 0;
679    }
680 #else
681    /* From libpng-1.5.6 the overwrite should be fixed, so compare the trailing
682     * bits too:
683     */
684    if (memcmp(pa, pb, (bit_width+7)>>3) == 0)
685       return 0;
686 #endif
687
688    /* Return the index of the changed byte. */
689    {
690       png_uint_32 where = 0;
691
692       while (pa[where] == pb[where]) ++where;
693       return 1+where;
694    }
695 }
696 #endif /* PNG_READ_SUPPORTED */
697
698 /*************************** BASIC PNG FILE WRITING ***************************/
699 /* A png_store takes data from the sequential writer or provides data
700  * to the sequential reader.  It can also store the result of a PNG
701  * write for later retrieval.
702  */
703 #define STORE_BUFFER_SIZE 500 /* arbitrary */
704 typedef struct png_store_buffer
705 {
706    struct png_store_buffer*  prev;    /* NOTE: stored in reverse order */
707    png_byte                  buffer[STORE_BUFFER_SIZE];
708 } png_store_buffer;
709
710 #define FILE_NAME_SIZE 64
711
712 typedef struct store_palette_entry /* record of a single palette entry */
713 {
714    png_byte red;
715    png_byte green;
716    png_byte blue;
717    png_byte alpha;
718 } store_palette_entry, store_palette[256];
719
720 typedef struct png_store_file
721 {
722    struct png_store_file*  next;      /* as many as you like... */
723    char                    name[FILE_NAME_SIZE];
724    png_uint_32             id;        /* must be correct (see FILEID) */
725    png_size_t              datacount; /* In this (the last) buffer */
726    png_store_buffer        data;      /* Last buffer in file */
727    int                     npalette;  /* Number of entries in palette */
728    store_palette_entry*    palette;   /* May be NULL */
729 } png_store_file;
730
731 /* The following is a pool of memory allocated by a single libpng read or write
732  * operation.
733  */
734 typedef struct store_pool
735 {
736    struct png_store    *store;   /* Back pointer */
737    struct store_memory *list;    /* List of allocated memory */
738    png_byte             mark[4]; /* Before and after data */
739
740    /* Statistics for this run. */
741    png_alloc_size_t     max;     /* Maximum single allocation */
742    png_alloc_size_t     current; /* Current allocation */
743    png_alloc_size_t     limit;   /* Highest current allocation */
744    png_alloc_size_t     total;   /* Total allocation */
745
746    /* Overall statistics (retained across successive runs). */
747    png_alloc_size_t     max_max;
748    png_alloc_size_t     max_limit;
749    png_alloc_size_t     max_total;
750 } store_pool;
751
752 typedef struct png_store
753 {
754    /* For cexcept.h exception handling - simply store one of these;
755     * the context is a self pointer but it may point to a different
756     * png_store (in fact it never does in this program.)
757     */
758    struct exception_context
759                       exception_context;
760
761    unsigned int       verbose :1;
762    unsigned int       treat_warnings_as_errors :1;
763    unsigned int       expect_error :1;
764    unsigned int       expect_warning :1;
765    unsigned int       saw_warning :1;
766    unsigned int       speed :1;
767    unsigned int       progressive :1; /* use progressive read */
768    unsigned int       validated :1;   /* used as a temporary flag */
769    int                nerrors;
770    int                nwarnings;
771    int                noptions;       /* number of options below: */
772    struct {
773       unsigned char   option;         /* option number, 0..30 */
774       unsigned char   setting;        /* setting (unset,invalid,on,off) */
775    }                  options[16];
776    char               test[128];      /* Name of test */
777    char               error[256];
778
779    /* Read fields */
780    png_structp        pread;    /* Used to read a saved file */
781    png_infop          piread;
782    png_store_file*    current;  /* Set when reading */
783    png_store_buffer*  next;     /* Set when reading */
784    png_size_t         readpos;  /* Position in *next */
785    png_byte*          image;    /* Buffer for reading interlaced images */
786    png_size_t         cb_image; /* Size of this buffer */
787    png_size_t         cb_row;   /* Row size of the image(s) */
788    png_uint_32        image_h;  /* Number of rows in a single image */
789    store_pool         read_memory_pool;
790
791    /* Write fields */
792    png_store_file*    saved;
793    png_structp        pwrite;   /* Used when writing a new file */
794    png_infop          piwrite;
795    png_size_t         writepos; /* Position in .new */
796    char               wname[FILE_NAME_SIZE];
797    png_store_buffer   new;      /* The end of the new PNG file being written. */
798    store_pool         write_memory_pool;
799    store_palette_entry* palette;
800    int                  npalette;
801 } png_store;
802
803 /* Initialization and cleanup */
804 static void
805 store_pool_mark(png_bytep mark)
806 {
807    static png_uint_32 store_seed[2] = { 0x12345678, 1};
808
809    make_four_random_bytes(store_seed, mark);
810 }
811
812 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
813 /* Use this for random 32 bit values; this function makes sure the result is
814  * non-zero.
815  */
816 static png_uint_32
817 random_32(void)
818 {
819
820    for (;;)
821    {
822       png_byte mark[4];
823       png_uint_32 result;
824
825       store_pool_mark(mark);
826       result = png_get_uint_32(mark);
827
828       if (result != 0)
829          return result;
830    }
831 }
832 #endif /* PNG_READ_SUPPORTED */
833
834 static void
835 store_pool_init(png_store *ps, store_pool *pool)
836 {
837    memset(pool, 0, sizeof *pool);
838
839    pool->store = ps;
840    pool->list = NULL;
841    pool->max = pool->current = pool->limit = pool->total = 0;
842    pool->max_max = pool->max_limit = pool->max_total = 0;
843    store_pool_mark(pool->mark);
844 }
845
846 static void
847 store_init(png_store* ps)
848 {
849    memset(ps, 0, sizeof *ps);
850    init_exception_context(&ps->exception_context);
851    store_pool_init(ps, &ps->read_memory_pool);
852    store_pool_init(ps, &ps->write_memory_pool);
853    ps->verbose = 0;
854    ps->treat_warnings_as_errors = 0;
855    ps->expect_error = 0;
856    ps->expect_warning = 0;
857    ps->saw_warning = 0;
858    ps->speed = 0;
859    ps->progressive = 0;
860    ps->validated = 0;
861    ps->nerrors = ps->nwarnings = 0;
862    ps->pread = NULL;
863    ps->piread = NULL;
864    ps->saved = ps->current = NULL;
865    ps->next = NULL;
866    ps->readpos = 0;
867    ps->image = NULL;
868    ps->cb_image = 0;
869    ps->cb_row = 0;
870    ps->image_h = 0;
871    ps->pwrite = NULL;
872    ps->piwrite = NULL;
873    ps->writepos = 0;
874    ps->new.prev = NULL;
875    ps->palette = NULL;
876    ps->npalette = 0;
877    ps->noptions = 0;
878 }
879
880 static void
881 store_freebuffer(png_store_buffer* psb)
882 {
883    if (psb->prev)
884    {
885       store_freebuffer(psb->prev);
886       free(psb->prev);
887       psb->prev = NULL;
888    }
889 }
890
891 static void
892 store_freenew(png_store *ps)
893 {
894    store_freebuffer(&ps->new);
895    ps->writepos = 0;
896    if (ps->palette != NULL)
897    {
898       free(ps->palette);
899       ps->palette = NULL;
900       ps->npalette = 0;
901    }
902 }
903
904 static void
905 store_storenew(png_store *ps)
906 {
907    png_store_buffer *pb;
908
909    if (ps->writepos != STORE_BUFFER_SIZE)
910       png_error(ps->pwrite, "invalid store call");
911
912    pb = voidcast(png_store_buffer*, malloc(sizeof *pb));
913
914    if (pb == NULL)
915       png_error(ps->pwrite, "store new: OOM");
916
917    *pb = ps->new;
918    ps->new.prev = pb;
919    ps->writepos = 0;
920 }
921
922 static void
923 store_freefile(png_store_file **ppf)
924 {
925    if (*ppf != NULL)
926    {
927       store_freefile(&(*ppf)->next);
928
929       store_freebuffer(&(*ppf)->data);
930       (*ppf)->datacount = 0;
931       if ((*ppf)->palette != NULL)
932       {
933          free((*ppf)->palette);
934          (*ppf)->palette = NULL;
935          (*ppf)->npalette = 0;
936       }
937       free(*ppf);
938       *ppf = NULL;
939    }
940 }
941
942 /* Main interface to file storeage, after writing a new PNG file (see the API
943  * below) call store_storefile to store the result with the given name and id.
944  */
945 static void
946 store_storefile(png_store *ps, png_uint_32 id)
947 {
948    png_store_file *pf = voidcast(png_store_file*, malloc(sizeof *pf));
949    if (pf == NULL)
950       png_error(ps->pwrite, "storefile: OOM");
951    safecat(pf->name, sizeof pf->name, 0, ps->wname);
952    pf->id = id;
953    pf->data = ps->new;
954    pf->datacount = ps->writepos;
955    ps->new.prev = NULL;
956    ps->writepos = 0;
957    pf->palette = ps->palette;
958    pf->npalette = ps->npalette;
959    ps->palette = 0;
960    ps->npalette = 0;
961
962    /* And save it. */
963    pf->next = ps->saved;
964    ps->saved = pf;
965 }
966
967 /* Generate an error message (in the given buffer) */
968 static size_t
969 store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize,
970    size_t pos, const char *msg)
971 {
972    if (pp != NULL && pp == ps->pread)
973    {
974       /* Reading a file */
975       pos = safecat(buffer, bufsize, pos, "read: ");
976
977       if (ps->current != NULL)
978       {
979          pos = safecat(buffer, bufsize, pos, ps->current->name);
980          pos = safecat(buffer, bufsize, pos, sep);
981       }
982    }
983
984    else if (pp != NULL && pp == ps->pwrite)
985    {
986       /* Writing a file */
987       pos = safecat(buffer, bufsize, pos, "write: ");
988       pos = safecat(buffer, bufsize, pos, ps->wname);
989       pos = safecat(buffer, bufsize, pos, sep);
990    }
991
992    else
993    {
994       /* Neither reading nor writing (or a memory error in struct delete) */
995       pos = safecat(buffer, bufsize, pos, "pngvalid: ");
996    }
997
998    if (ps->test[0] != 0)
999    {
1000       pos = safecat(buffer, bufsize, pos, ps->test);
1001       pos = safecat(buffer, bufsize, pos, sep);
1002    }
1003    pos = safecat(buffer, bufsize, pos, msg);
1004    return pos;
1005 }
1006
1007 /* Verbose output to the error stream: */
1008 static void
1009 store_verbose(png_store *ps, png_const_structp pp, png_const_charp prefix,
1010    png_const_charp message)
1011 {
1012    char buffer[512];
1013
1014    if (prefix)
1015       fputs(prefix, stderr);
1016
1017    (void)store_message(ps, pp, buffer, sizeof buffer, 0, message);
1018    fputs(buffer, stderr);
1019    fputc('\n', stderr);
1020 }
1021
1022 /* Log an error or warning - the relevant count is always incremented. */
1023 static void
1024 store_log(png_store* ps, png_const_structp pp, png_const_charp message,
1025    int is_error)
1026 {
1027    /* The warning is copied to the error buffer if there are no errors and it is
1028     * the first warning.  The error is copied to the error buffer if it is the
1029     * first error (overwriting any prior warnings).
1030     */
1031    if (is_error ? (ps->nerrors)++ == 0 :
1032        (ps->nwarnings)++ == 0 && ps->nerrors == 0)
1033       store_message(ps, pp, ps->error, sizeof ps->error, 0, message);
1034
1035    if (ps->verbose)
1036       store_verbose(ps, pp, is_error ? "error: " : "warning: ", message);
1037 }
1038
1039 #ifdef PNG_READ_SUPPORTED
1040 /* Internal error function, called with a png_store but no libpng stuff. */
1041 static void
1042 internal_error(png_store *ps, png_const_charp message)
1043 {
1044    store_log(ps, NULL, message, 1 /* error */);
1045
1046    /* And finally throw an exception. */
1047    {
1048       struct exception_context *the_exception_context = &ps->exception_context;
1049       Throw ps;
1050    }
1051 }
1052 #endif /* PNG_READ_SUPPORTED */
1053
1054 /* Functions to use as PNG callbacks. */
1055 static void PNGCBAPI
1056 store_error(png_structp ppIn, png_const_charp message) /* PNG_NORETURN */
1057 {
1058    png_const_structp pp = ppIn;
1059    png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
1060
1061    if (!ps->expect_error)
1062       store_log(ps, pp, message, 1 /* error */);
1063
1064    /* And finally throw an exception. */
1065    {
1066       struct exception_context *the_exception_context = &ps->exception_context;
1067       Throw ps;
1068    }
1069 }
1070
1071 static void PNGCBAPI
1072 store_warning(png_structp ppIn, png_const_charp message)
1073 {
1074    png_const_structp pp = ppIn;
1075    png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
1076
1077    if (!ps->expect_warning)
1078       store_log(ps, pp, message, 0 /* warning */);
1079    else
1080       ps->saw_warning = 1;
1081 }
1082
1083 /* These somewhat odd functions are used when reading an image to ensure that
1084  * the buffer is big enough, the png_structp is for errors.
1085  */
1086 /* Return a single row from the correct image. */
1087 static png_bytep
1088 store_image_row(const png_store* ps, png_const_structp pp, int nImage,
1089    png_uint_32 y)
1090 {
1091    png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2;
1092
1093    if (ps->image == NULL)
1094       png_error(pp, "no allocated image");
1095
1096    if (coffset + ps->cb_row + 3 > ps->cb_image)
1097       png_error(pp, "image too small");
1098
1099    return ps->image + coffset;
1100 }
1101
1102 static void
1103 store_image_free(png_store *ps, png_const_structp pp)
1104 {
1105    if (ps->image != NULL)
1106    {
1107       png_bytep image = ps->image;
1108
1109       if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
1110       {
1111          if (pp != NULL)
1112             png_error(pp, "png_store image overwrite (1)");
1113          else
1114             store_log(ps, NULL, "png_store image overwrite (2)", 1);
1115       }
1116
1117       ps->image = NULL;
1118       ps->cb_image = 0;
1119       --image;
1120       free(image);
1121    }
1122 }
1123
1124 static void
1125 store_ensure_image(png_store *ps, png_const_structp pp, int nImages,
1126    png_size_t cbRow, png_uint_32 cRows)
1127 {
1128    png_size_t cb = nImages * cRows * (cbRow + 5);
1129
1130    if (ps->cb_image < cb)
1131    {
1132       png_bytep image;
1133
1134       store_image_free(ps, pp);
1135
1136       /* The buffer is deliberately mis-aligned. */
1137       image = voidcast(png_bytep, malloc(cb+2));
1138       if (image == NULL)
1139       {
1140          /* Called from the startup - ignore the error for the moment. */
1141          if (pp == NULL)
1142             return;
1143
1144          png_error(pp, "OOM allocating image buffer");
1145       }
1146
1147       /* These magic tags are used to detect overwrites above. */
1148       ++image;
1149       image[-1] = 0xed;
1150       image[cb] = 0xfe;
1151
1152       ps->image = image;
1153       ps->cb_image = cb;
1154    }
1155
1156    /* We have an adequate sized image; lay out the rows.  There are 2 bytes at
1157     * the start and three at the end of each (this ensures that the row
1158     * alignment starts out odd - 2+1 and changes for larger images on each row.)
1159     */
1160    ps->cb_row = cbRow;
1161    ps->image_h = cRows;
1162
1163    /* For error checking, the whole buffer is set to 10110010 (0xb2 - 178).
1164     * This deliberately doesn't match the bits in the size test image which are
1165     * outside the image; these are set to 0xff (all 1).  To make the row
1166     * comparison work in the 'size' test case the size rows are pre-initialized
1167     * to the same value prior to calling 'standard_row'.
1168     */
1169    memset(ps->image, 178, cb);
1170
1171    /* Then put in the marks. */
1172    while (--nImages >= 0)
1173    {
1174       png_uint_32 y;
1175
1176       for (y=0; y<cRows; ++y)
1177       {
1178          png_bytep row = store_image_row(ps, pp, nImages, y);
1179
1180          /* The markers: */
1181          row[-2] = 190;
1182          row[-1] = 239;
1183          row[cbRow] = 222;
1184          row[cbRow+1] = 173;
1185          row[cbRow+2] = 17;
1186       }
1187    }
1188 }
1189
1190 #ifdef PNG_READ_SUPPORTED
1191 static void
1192 store_image_check(const png_store* ps, png_const_structp pp, int iImage)
1193 {
1194    png_const_bytep image = ps->image;
1195
1196    if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
1197       png_error(pp, "image overwrite");
1198    else
1199    {
1200       png_size_t cbRow = ps->cb_row;
1201       png_uint_32 rows = ps->image_h;
1202
1203       image += iImage * (cbRow+5) * ps->image_h;
1204
1205       image += 2; /* skip image first row markers */
1206
1207       while (rows-- > 0)
1208       {
1209          if (image[-2] != 190 || image[-1] != 239)
1210             png_error(pp, "row start overwritten");
1211
1212          if (image[cbRow] != 222 || image[cbRow+1] != 173 ||
1213             image[cbRow+2] != 17)
1214             png_error(pp, "row end overwritten");
1215
1216          image += cbRow+5;
1217       }
1218    }
1219 }
1220 #endif /* PNG_READ_SUPPORTED */
1221
1222 static void PNGCBAPI
1223 store_write(png_structp ppIn, png_bytep pb, png_size_t st)
1224 {
1225    png_const_structp pp = ppIn;
1226    png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
1227
1228    if (ps->pwrite != pp)
1229       png_error(pp, "store state damaged");
1230
1231    while (st > 0)
1232    {
1233       size_t cb;
1234
1235       if (ps->writepos >= STORE_BUFFER_SIZE)
1236          store_storenew(ps);
1237
1238       cb = st;
1239
1240       if (cb > STORE_BUFFER_SIZE - ps->writepos)
1241          cb = STORE_BUFFER_SIZE - ps->writepos;
1242
1243       memcpy(ps->new.buffer + ps->writepos, pb, cb);
1244       pb += cb;
1245       st -= cb;
1246       ps->writepos += cb;
1247    }
1248 }
1249
1250 static void PNGCBAPI
1251 store_flush(png_structp ppIn)
1252 {
1253    UNUSED(ppIn) /*DOES NOTHING*/
1254 }
1255
1256 #ifdef PNG_READ_SUPPORTED
1257 static size_t
1258 store_read_buffer_size(png_store *ps)
1259 {
1260    /* Return the bytes available for read in the current buffer. */
1261    if (ps->next != &ps->current->data)
1262       return STORE_BUFFER_SIZE;
1263
1264    return ps->current->datacount;
1265 }
1266
1267 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
1268 /* Return total bytes available for read. */
1269 static size_t
1270 store_read_buffer_avail(png_store *ps)
1271 {
1272    if (ps->current != NULL && ps->next != NULL)
1273    {
1274       png_store_buffer *next = &ps->current->data;
1275       size_t cbAvail = ps->current->datacount;
1276
1277       while (next != ps->next && next != NULL)
1278       {
1279          next = next->prev;
1280          cbAvail += STORE_BUFFER_SIZE;
1281       }
1282
1283       if (next != ps->next)
1284          png_error(ps->pread, "buffer read error");
1285
1286       if (cbAvail > ps->readpos)
1287          return cbAvail - ps->readpos;
1288    }
1289
1290    return 0;
1291 }
1292 #endif
1293
1294 static int
1295 store_read_buffer_next(png_store *ps)
1296 {
1297    png_store_buffer *pbOld = ps->next;
1298    png_store_buffer *pbNew = &ps->current->data;
1299    if (pbOld != pbNew)
1300    {
1301       while (pbNew != NULL && pbNew->prev != pbOld)
1302          pbNew = pbNew->prev;
1303
1304       if (pbNew != NULL)
1305       {
1306          ps->next = pbNew;
1307          ps->readpos = 0;
1308          return 1;
1309       }
1310
1311       png_error(ps->pread, "buffer lost");
1312    }
1313
1314    return 0; /* EOF or error */
1315 }
1316
1317 /* Need separate implementation and callback to allow use of the same code
1318  * during progressive read, where the io_ptr is set internally by libpng.
1319  */
1320 static void
1321 store_read_imp(png_store *ps, png_bytep pb, png_size_t st)
1322 {
1323    if (ps->current == NULL || ps->next == NULL)
1324       png_error(ps->pread, "store state damaged");
1325
1326    while (st > 0)
1327    {
1328       size_t cbAvail = store_read_buffer_size(ps) - ps->readpos;
1329
1330       if (cbAvail > 0)
1331       {
1332          if (cbAvail > st) cbAvail = st;
1333          memcpy(pb, ps->next->buffer + ps->readpos, cbAvail);
1334          st -= cbAvail;
1335          pb += cbAvail;
1336          ps->readpos += cbAvail;
1337       }
1338
1339       else if (!store_read_buffer_next(ps))
1340          png_error(ps->pread, "read beyond end of file");
1341    }
1342 }
1343
1344 static void PNGCBAPI
1345 store_read(png_structp ppIn, png_bytep pb, png_size_t st)
1346 {
1347    png_const_structp pp = ppIn;
1348    png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
1349
1350    if (ps == NULL || ps->pread != pp)
1351       png_error(pp, "bad store read call");
1352
1353    store_read_imp(ps, pb, st);
1354 }
1355
1356 static void
1357 store_progressive_read(png_store *ps, png_structp pp, png_infop pi)
1358 {
1359    /* Notice that a call to store_read will cause this function to fail because
1360     * readpos will be set.
1361     */
1362    if (ps->pread != pp || ps->current == NULL || ps->next == NULL)
1363       png_error(pp, "store state damaged (progressive)");
1364
1365    do
1366    {
1367       if (ps->readpos != 0)
1368          png_error(pp, "store_read called during progressive read");
1369
1370       png_process_data(pp, pi, ps->next->buffer, store_read_buffer_size(ps));
1371    }
1372    while (store_read_buffer_next(ps));
1373 }
1374 #endif /* PNG_READ_SUPPORTED */
1375
1376 /* The caller must fill this in: */
1377 static store_palette_entry *
1378 store_write_palette(png_store *ps, int npalette)
1379 {
1380    if (ps->pwrite == NULL)
1381       store_log(ps, NULL, "attempt to write palette without write stream", 1);
1382
1383    if (ps->palette != NULL)
1384       png_error(ps->pwrite, "multiple store_write_palette calls");
1385
1386    /* This function can only return NULL if called with '0'! */
1387    if (npalette > 0)
1388    {
1389       ps->palette = voidcast(store_palette_entry*, malloc(npalette *
1390          sizeof *ps->palette));
1391
1392       if (ps->palette == NULL)
1393          png_error(ps->pwrite, "store new palette: OOM");
1394
1395       ps->npalette = npalette;
1396    }
1397
1398    return ps->palette;
1399 }
1400
1401 #ifdef PNG_READ_SUPPORTED
1402 static store_palette_entry *
1403 store_current_palette(png_store *ps, int *npalette)
1404 {
1405    /* This is an internal error (the call has been made outside a read
1406     * operation.)
1407     */
1408    if (ps->current == NULL)
1409    {
1410       store_log(ps, ps->pread, "no current stream for palette", 1);
1411       return NULL;
1412    }
1413
1414    /* The result may be null if there is no palette. */
1415    *npalette = ps->current->npalette;
1416    return ps->current->palette;
1417 }
1418 #endif /* PNG_READ_SUPPORTED */
1419
1420 /***************************** MEMORY MANAGEMENT*** ***************************/
1421 #ifdef PNG_USER_MEM_SUPPORTED
1422 /* A store_memory is simply the header for an allocated block of memory.  The
1423  * pointer returned to libpng is just after the end of the header block, the
1424  * allocated memory is followed by a second copy of the 'mark'.
1425  */
1426 typedef struct store_memory
1427 {
1428    store_pool          *pool;    /* Originating pool */
1429    struct store_memory *next;    /* Singly linked list */
1430    png_alloc_size_t     size;    /* Size of memory allocated */
1431    png_byte             mark[4]; /* ID marker */
1432 } store_memory;
1433
1434 /* Handle a fatal error in memory allocation.  This calls png_error if the
1435  * libpng struct is non-NULL, else it outputs a message and returns.  This means
1436  * that a memory problem while libpng is running will abort (png_error) the
1437  * handling of particular file while one in cleanup (after the destroy of the
1438  * struct has returned) will simply keep going and free (or attempt to free)
1439  * all the memory.
1440  */
1441 static void
1442 store_pool_error(png_store *ps, png_const_structp pp, const char *msg)
1443 {
1444    if (pp != NULL)
1445       png_error(pp, msg);
1446
1447    /* Else we have to do it ourselves.  png_error eventually calls store_log,
1448     * above.  store_log accepts a NULL png_structp - it just changes what gets
1449     * output by store_message.
1450     */
1451    store_log(ps, pp, msg, 1 /* error */);
1452 }
1453
1454 static void
1455 store_memory_free(png_const_structp pp, store_pool *pool, store_memory *memory)
1456 {
1457    /* Note that pp may be NULL (see store_pool_delete below), the caller has
1458     * found 'memory' in pool->list *and* unlinked this entry, so this is a valid
1459     * pointer (for sure), but the contents may have been trashed.
1460     */
1461    if (memory->pool != pool)
1462       store_pool_error(pool->store, pp, "memory corrupted (pool)");
1463
1464    else if (memcmp(memory->mark, pool->mark, sizeof memory->mark) != 0)
1465       store_pool_error(pool->store, pp, "memory corrupted (start)");
1466
1467    /* It should be safe to read the size field now. */
1468    else
1469    {
1470       png_alloc_size_t cb = memory->size;
1471
1472       if (cb > pool->max)
1473          store_pool_error(pool->store, pp, "memory corrupted (size)");
1474
1475       else if (memcmp((png_bytep)(memory+1)+cb, pool->mark, sizeof pool->mark)
1476          != 0)
1477          store_pool_error(pool->store, pp, "memory corrupted (end)");
1478
1479       /* Finally give the library a chance to find problems too: */
1480       else
1481          {
1482          pool->current -= cb;
1483          free(memory);
1484          }
1485    }
1486 }
1487
1488 static void
1489 store_pool_delete(png_store *ps, store_pool *pool)
1490 {
1491    if (pool->list != NULL)
1492    {
1493       fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
1494          pool == &ps->read_memory_pool ? "read" : "write",
1495          pool == &ps->read_memory_pool ? (ps->current != NULL ?
1496             ps->current->name : "unknown file") : ps->wname);
1497       ++ps->nerrors;
1498
1499       do
1500       {
1501          store_memory *next = pool->list;
1502          pool->list = next->next;
1503          next->next = NULL;
1504
1505          fprintf(stderr, "\t%lu bytes @ %p\n",
1506              (unsigned long)next->size, (const void*)(next+1));
1507          /* The NULL means this will always return, even if the memory is
1508           * corrupted.
1509           */
1510          store_memory_free(NULL, pool, next);
1511       }
1512       while (pool->list != NULL);
1513    }
1514
1515    /* And reset the other fields too for the next time. */
1516    if (pool->max > pool->max_max) pool->max_max = pool->max;
1517    pool->max = 0;
1518    if (pool->current != 0) /* unexpected internal error */
1519       fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
1520          ps->test, pool == &ps->read_memory_pool ? "read" : "write",
1521          pool == &ps->read_memory_pool ? (ps->current != NULL ?
1522             ps->current->name : "unknown file") : ps->wname);
1523    pool->current = 0;
1524
1525    if (pool->limit > pool->max_limit)
1526       pool->max_limit = pool->limit;
1527
1528    pool->limit = 0;
1529
1530    if (pool->total > pool->max_total)
1531       pool->max_total = pool->total;
1532
1533    pool->total = 0;
1534
1535    /* Get a new mark too. */
1536    store_pool_mark(pool->mark);
1537 }
1538
1539 /* The memory callbacks: */
1540 static png_voidp PNGCBAPI
1541 store_malloc(png_structp ppIn, png_alloc_size_t cb)
1542 {
1543    png_const_structp pp = ppIn;
1544    store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
1545    store_memory *new = voidcast(store_memory*, malloc(cb + (sizeof *new) +
1546       (sizeof pool->mark)));
1547
1548    if (new != NULL)
1549    {
1550       if (cb > pool->max)
1551          pool->max = cb;
1552
1553       pool->current += cb;
1554
1555       if (pool->current > pool->limit)
1556          pool->limit = pool->current;
1557
1558       pool->total += cb;
1559
1560       new->size = cb;
1561       memcpy(new->mark, pool->mark, sizeof new->mark);
1562       memcpy((png_byte*)(new+1) + cb, pool->mark, sizeof pool->mark);
1563       new->pool = pool;
1564       new->next = pool->list;
1565       pool->list = new;
1566       ++new;
1567    }
1568
1569    else
1570    {
1571       /* NOTE: the PNG user malloc function cannot use the png_ptr it is passed
1572        * other than to retrieve the allocation pointer!  libpng calls the
1573        * store_malloc callback in two basic cases:
1574        *
1575        * 1) From png_malloc; png_malloc will do a png_error itself if NULL is
1576        *    returned.
1577        * 2) From png_struct or png_info structure creation; png_malloc is
1578        *    to return so cleanup can be performed.
1579        *
1580        * To handle this store_malloc can log a message, but can't do anything
1581        * else.
1582        */
1583       store_log(pool->store, pp, "out of memory", 1 /* is_error */);
1584    }
1585
1586    return new;
1587 }
1588
1589 static void PNGCBAPI
1590 store_free(png_structp ppIn, png_voidp memory)
1591 {
1592    png_const_structp pp = ppIn;
1593    store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
1594    store_memory *this = voidcast(store_memory*, memory), **test;
1595
1596    /* Because libpng calls store_free with a dummy png_struct when deleting
1597     * png_struct or png_info via png_destroy_struct_2 it is necessary to check
1598     * the passed in png_structp to ensure it is valid, and not pass it to
1599     * png_error if it is not.
1600     */
1601    if (pp != pool->store->pread && pp != pool->store->pwrite)
1602       pp = NULL;
1603
1604    /* First check that this 'memory' really is valid memory - it must be in the
1605     * pool list.  If it is, use the shared memory_free function to free it.
1606     */
1607    --this;
1608    for (test = &pool->list; *test != this; test = &(*test)->next)
1609    {
1610       if (*test == NULL)
1611       {
1612          store_pool_error(pool->store, pp, "bad pointer to free");
1613          return;
1614       }
1615    }
1616
1617    /* Unlink this entry, *test == this. */
1618    *test = this->next;
1619    this->next = NULL;
1620    store_memory_free(pp, pool, this);
1621 }
1622 #endif /* PNG_USER_MEM_SUPPORTED */
1623
1624 /* Setup functions. */
1625 /* Cleanup when aborting a write or after storing the new file. */
1626 static void
1627 store_write_reset(png_store *ps)
1628 {
1629    if (ps->pwrite != NULL)
1630    {
1631       anon_context(ps);
1632
1633       Try
1634          png_destroy_write_struct(&ps->pwrite, &ps->piwrite);
1635
1636       Catch_anonymous
1637       {
1638          /* memory corruption: continue. */
1639       }
1640
1641       ps->pwrite = NULL;
1642       ps->piwrite = NULL;
1643    }
1644
1645    /* And make sure that all the memory has been freed - this will output
1646     * spurious errors in the case of memory corruption above, but this is safe.
1647     */
1648 #  ifdef PNG_USER_MEM_SUPPORTED
1649       store_pool_delete(ps, &ps->write_memory_pool);
1650 #  endif
1651
1652    store_freenew(ps);
1653 }
1654
1655 /* The following is the main write function, it returns a png_struct and,
1656  * optionally, a png_info suitable for writiing a new PNG file.  Use
1657  * store_storefile above to record this file after it has been written.  The
1658  * returned libpng structures as destroyed by store_write_reset above.
1659  */
1660 static png_structp
1661 set_store_for_write(png_store *ps, png_infopp ppi, const char *name)
1662 {
1663    anon_context(ps);
1664
1665    Try
1666    {
1667       if (ps->pwrite != NULL)
1668          png_error(ps->pwrite, "write store already in use");
1669
1670       store_write_reset(ps);
1671       safecat(ps->wname, sizeof ps->wname, 0, name);
1672
1673       /* Don't do the slow memory checks if doing a speed test, also if user
1674        * memory is not supported we can't do it anyway.
1675        */
1676 #     ifdef PNG_USER_MEM_SUPPORTED
1677          if (!ps->speed)
1678             ps->pwrite = png_create_write_struct_2(PNG_LIBPNG_VER_STRING,
1679                ps, store_error, store_warning, &ps->write_memory_pool,
1680                store_malloc, store_free);
1681
1682          else
1683 #     endif
1684          ps->pwrite = png_create_write_struct(PNG_LIBPNG_VER_STRING,
1685             ps, store_error, store_warning);
1686
1687       png_set_write_fn(ps->pwrite, ps, store_write, store_flush);
1688
1689 #     ifdef PNG_SET_OPTION_SUPPORTED
1690          {
1691             int opt;
1692             for (opt=0; opt<ps->noptions; ++opt)
1693                if (png_set_option(ps->pwrite, ps->options[opt].option,
1694                   ps->options[opt].setting) == PNG_OPTION_INVALID)
1695                   png_error(ps->pwrite, "png option invalid");
1696          }
1697 #     endif
1698
1699       if (ppi != NULL)
1700          *ppi = ps->piwrite = png_create_info_struct(ps->pwrite);
1701    }
1702
1703    Catch_anonymous
1704       return NULL;
1705
1706    return ps->pwrite;
1707 }
1708
1709 /* Cleanup when finished reading (either due to error or in the success case).
1710  * This routine exists even when there is no read support to make the code
1711  * tidier (avoid a mass of ifdefs) and so easier to maintain.
1712  */
1713 static void
1714 store_read_reset(png_store *ps)
1715 {
1716 #  ifdef PNG_READ_SUPPORTED
1717       if (ps->pread != NULL)
1718       {
1719          anon_context(ps);
1720
1721          Try
1722             png_destroy_read_struct(&ps->pread, &ps->piread, NULL);
1723
1724          Catch_anonymous
1725          {
1726             /* error already output: continue */
1727          }
1728
1729          ps->pread = NULL;
1730          ps->piread = NULL;
1731       }
1732 #  endif
1733
1734 #  ifdef PNG_USER_MEM_SUPPORTED
1735       /* Always do this to be safe. */
1736       store_pool_delete(ps, &ps->read_memory_pool);
1737 #  endif
1738
1739    ps->current = NULL;
1740    ps->next = NULL;
1741    ps->readpos = 0;
1742    ps->validated = 0;
1743 }
1744
1745 #ifdef PNG_READ_SUPPORTED
1746 static void
1747 store_read_set(png_store *ps, png_uint_32 id)
1748 {
1749    png_store_file *pf = ps->saved;
1750
1751    while (pf != NULL)
1752    {
1753       if (pf->id == id)
1754       {
1755          ps->current = pf;
1756          ps->next = NULL;
1757          store_read_buffer_next(ps);
1758          return;
1759       }
1760
1761       pf = pf->next;
1762    }
1763
1764    {
1765       size_t pos;
1766       char msg[FILE_NAME_SIZE+64];
1767
1768       pos = standard_name_from_id(msg, sizeof msg, 0, id);
1769       pos = safecat(msg, sizeof msg, pos, ": file not found");
1770       png_error(ps->pread, msg);
1771    }
1772 }
1773
1774 /* The main interface for reading a saved file - pass the id number of the file
1775  * to retrieve.  Ids must be unique or the earlier file will be hidden.  The API
1776  * returns a png_struct and, optionally, a png_info.  Both of these will be
1777  * destroyed by store_read_reset above.
1778  */
1779 static png_structp
1780 set_store_for_read(png_store *ps, png_infopp ppi, png_uint_32 id,
1781    const char *name)
1782 {
1783    /* Set the name for png_error */
1784    safecat(ps->test, sizeof ps->test, 0, name);
1785
1786    if (ps->pread != NULL)
1787       png_error(ps->pread, "read store already in use");
1788
1789    store_read_reset(ps);
1790
1791    /* Both the create APIs can return NULL if used in their default mode
1792     * (because there is no other way of handling an error because the jmp_buf
1793     * by default is stored in png_struct and that has not been allocated!)
1794     * However, given that store_error works correctly in these circumstances
1795     * we don't ever expect NULL in this program.
1796     */
1797 #  ifdef PNG_USER_MEM_SUPPORTED
1798       if (!ps->speed)
1799          ps->pread = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, ps,
1800              store_error, store_warning, &ps->read_memory_pool, store_malloc,
1801              store_free);
1802
1803       else
1804 #  endif
1805    ps->pread = png_create_read_struct(PNG_LIBPNG_VER_STRING, ps, store_error,
1806       store_warning);
1807
1808    if (ps->pread == NULL)
1809    {
1810       struct exception_context *the_exception_context = &ps->exception_context;
1811
1812       store_log(ps, NULL, "png_create_read_struct returned NULL (unexpected)",
1813          1 /*error*/);
1814
1815       Throw ps;
1816    }
1817
1818 #  ifdef PNG_SET_OPTION_SUPPORTED
1819       {
1820          int opt;
1821          for (opt=0; opt<ps->noptions; ++opt)
1822             if (png_set_option(ps->pread, ps->options[opt].option,
1823                ps->options[opt].setting) == PNG_OPTION_INVALID)
1824                   png_error(ps->pread, "png option invalid");
1825       }
1826 #  endif
1827
1828    store_read_set(ps, id);
1829
1830    if (ppi != NULL)
1831       *ppi = ps->piread = png_create_info_struct(ps->pread);
1832
1833    return ps->pread;
1834 }
1835 #endif /* PNG_READ_SUPPORTED */
1836
1837 /* The overall cleanup of a store simply calls the above then removes all the
1838  * saved files.  This does not delete the store itself.
1839  */
1840 static void
1841 store_delete(png_store *ps)
1842 {
1843    store_write_reset(ps);
1844    store_read_reset(ps);
1845    store_freefile(&ps->saved);
1846    store_image_free(ps, NULL);
1847 }
1848
1849 /*********************** PNG FILE MODIFICATION ON READ ************************/
1850 /* Files may be modified on read.  The following structure contains a complete
1851  * png_store together with extra members to handle modification and a special
1852  * read callback for libpng.  To use this the 'modifications' field must be set
1853  * to a list of png_modification structures that actually perform the
1854  * modification, otherwise a png_modifier is functionally equivalent to a
1855  * png_store.  There is a special read function, set_modifier_for_read, which
1856  * replaces set_store_for_read.
1857  */
1858 typedef enum modifier_state
1859 {
1860    modifier_start,                        /* Initial value */
1861    modifier_signature,                    /* Have a signature */
1862    modifier_IHDR                          /* Have an IHDR */
1863 } modifier_state;
1864
1865 typedef struct CIE_color
1866 {
1867    /* A single CIE tristimulus value, representing the unique response of a
1868     * standard observer to a variety of light spectra.  The observer recognizes
1869     * all spectra that produce this response as the same color, therefore this
1870     * is effectively a description of a color.
1871     */
1872    double X, Y, Z;
1873 } CIE_color;
1874
1875 typedef struct color_encoding
1876 {
1877    /* A description of an (R,G,B) encoding of color (as defined above); this
1878     * includes the actual colors of the (R,G,B) triples (1,0,0), (0,1,0) and
1879     * (0,0,1) plus an encoding value that is used to encode the linear
1880     * components R, G and B to give the actual values R^gamma, G^gamma and
1881     * B^gamma that are stored.
1882     */
1883    double    gamma;            /* Encoding (file) gamma of space */
1884    CIE_color red, green, blue; /* End points */
1885 } color_encoding;
1886
1887 #ifdef PNG_READ_SUPPORTED
1888 #if defined PNG_READ_TRANSFORMS_SUPPORTED && defined PNG_READ_cHRM_SUPPORTED
1889 static double
1890 chromaticity_x(CIE_color c)
1891 {
1892    return c.X / (c.X + c.Y + c.Z);
1893 }
1894
1895 static double
1896 chromaticity_y(CIE_color c)
1897 {
1898    return c.Y / (c.X + c.Y + c.Z);
1899 }
1900
1901 static CIE_color
1902 white_point(const color_encoding *encoding)
1903 {
1904    CIE_color white;
1905
1906    white.X = encoding->red.X + encoding->green.X + encoding->blue.X;
1907    white.Y = encoding->red.Y + encoding->green.Y + encoding->blue.Y;
1908    white.Z = encoding->red.Z + encoding->green.Z + encoding->blue.Z;
1909
1910    return white;
1911 }
1912 #endif /* READ_TRANSFORMS && READ_cHRM */
1913
1914 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
1915 static void
1916 normalize_color_encoding(color_encoding *encoding)
1917 {
1918    const double whiteY = encoding->red.Y + encoding->green.Y +
1919       encoding->blue.Y;
1920
1921    if (whiteY != 1)
1922    {
1923       encoding->red.X /= whiteY;
1924       encoding->red.Y /= whiteY;
1925       encoding->red.Z /= whiteY;
1926       encoding->green.X /= whiteY;
1927       encoding->green.Y /= whiteY;
1928       encoding->green.Z /= whiteY;
1929       encoding->blue.X /= whiteY;
1930       encoding->blue.Y /= whiteY;
1931       encoding->blue.Z /= whiteY;
1932    }
1933 }
1934 #endif
1935
1936 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
1937 static size_t
1938 safecat_color_encoding(char *buffer, size_t bufsize, size_t pos,
1939    const color_encoding *e, double encoding_gamma)
1940 {
1941    if (e != 0)
1942    {
1943       if (encoding_gamma != 0)
1944          pos = safecat(buffer, bufsize, pos, "(");
1945       pos = safecat(buffer, bufsize, pos, "R(");
1946       pos = safecatd(buffer, bufsize, pos, e->red.X, 4);
1947       pos = safecat(buffer, bufsize, pos, ",");
1948       pos = safecatd(buffer, bufsize, pos, e->red.Y, 4);
1949       pos = safecat(buffer, bufsize, pos, ",");
1950       pos = safecatd(buffer, bufsize, pos, e->red.Z, 4);
1951       pos = safecat(buffer, bufsize, pos, "),G(");
1952       pos = safecatd(buffer, bufsize, pos, e->green.X, 4);
1953       pos = safecat(buffer, bufsize, pos, ",");
1954       pos = safecatd(buffer, bufsize, pos, e->green.Y, 4);
1955       pos = safecat(buffer, bufsize, pos, ",");
1956       pos = safecatd(buffer, bufsize, pos, e->green.Z, 4);
1957       pos = safecat(buffer, bufsize, pos, "),B(");
1958       pos = safecatd(buffer, bufsize, pos, e->blue.X, 4);
1959       pos = safecat(buffer, bufsize, pos, ",");
1960       pos = safecatd(buffer, bufsize, pos, e->blue.Y, 4);
1961       pos = safecat(buffer, bufsize, pos, ",");
1962       pos = safecatd(buffer, bufsize, pos, e->blue.Z, 4);
1963       pos = safecat(buffer, bufsize, pos, ")");
1964       if (encoding_gamma != 0)
1965          pos = safecat(buffer, bufsize, pos, ")");
1966    }
1967
1968    if (encoding_gamma != 0)
1969    {
1970       pos = safecat(buffer, bufsize, pos, "^");
1971       pos = safecatd(buffer, bufsize, pos, encoding_gamma, 5);
1972    }
1973
1974    return pos;
1975 }
1976 #endif /* READ_TRANSFORMS */
1977 #endif /* PNG_READ_SUPPORTED */
1978
1979 typedef struct png_modifier
1980 {
1981    png_store               this;             /* I am a png_store */
1982    struct png_modification *modifications;   /* Changes to make */
1983
1984    modifier_state           state;           /* My state */
1985
1986    /* Information from IHDR: */
1987    png_byte                 bit_depth;       /* From IHDR */
1988    png_byte                 colour_type;     /* From IHDR */
1989
1990    /* While handling PLTE, IDAT and IEND these chunks may be pended to allow
1991     * other chunks to be inserted.
1992     */
1993    png_uint_32              pending_len;
1994    png_uint_32              pending_chunk;
1995
1996    /* Test values */
1997    double                   *gammas;
1998    unsigned int              ngammas;
1999    unsigned int              ngamma_tests;     /* Number of gamma tests to run*/
2000    double                    current_gamma;    /* 0 if not set */
2001    const color_encoding *encodings;
2002    unsigned int              nencodings;
2003    const color_encoding *current_encoding; /* If an encoding has been set */
2004    unsigned int              encoding_counter; /* For iteration */
2005    int                       encoding_ignored; /* Something overwrote it */
2006
2007    /* Control variables used to iterate through possible encodings, the
2008     * following must be set to 0 and tested by the function that uses the
2009     * png_modifier because the modifier only sets it to 1 (true.)
2010     */
2011    unsigned int              repeat :1;   /* Repeat this transform test. */
2012    unsigned int              test_uses_encoding :1;
2013
2014    /* Lowest sbit to test (pre-1.7 libpng fails for sbit < 8) */
2015    png_byte                 sbitlow;
2016
2017    /* Error control - these are the limits on errors accepted by the gamma tests
2018     * below.
2019     */
2020    double                   maxout8;  /* Maximum output value error */
2021    double                   maxabs8;  /* Absolute sample error 0..1 */
2022    double                   maxcalc8; /* Absolute sample error 0..1 */
2023    double                   maxpc8;   /* Percentage sample error 0..100% */
2024    double                   maxout16; /* Maximum output value error */
2025    double                   maxabs16; /* Absolute sample error 0..1 */
2026    double                   maxcalc16;/* Absolute sample error 0..1 */
2027    double                   maxcalcG; /* Absolute sample error 0..1 */
2028    double                   maxpc16;  /* Percentage sample error 0..100% */
2029
2030    /* This is set by transforms that need to allow a higher limit, it is an
2031     * internal check on pngvalid to ensure that the calculated error limits are
2032     * not ridiculous; without this it is too easy to make a mistake in pngvalid
2033     * that allows any value through.
2034     *
2035     * NOTE: this is not checked in release builds.
2036     */
2037    double                   limit;    /* limit on error values, normally 4E-3 */
2038
2039    /* Log limits - values above this are logged, but not necessarily
2040     * warned.
2041     */
2042    double                   log8;     /* Absolute error in 8 bits to log */
2043    double                   log16;    /* Absolute error in 16 bits to log */
2044
2045    /* Logged 8 and 16 bit errors ('output' values): */
2046    double                   error_gray_2;
2047    double                   error_gray_4;
2048    double                   error_gray_8;
2049    double                   error_gray_16;
2050    double                   error_color_8;
2051    double                   error_color_16;
2052    double                   error_indexed;
2053
2054    /* Flags: */
2055    /* Whether to call png_read_update_info, not png_read_start_image, and how
2056     * many times to call it.
2057     */
2058    int                      use_update_info;
2059
2060    /* Whether or not to interlace. */
2061    int                      interlace_type :9; /* int, but must store '1' */
2062
2063    /* Run the standard tests? */
2064    unsigned int             test_standard :1;
2065
2066    /* Run the odd-sized image and interlace read/write tests? */
2067    unsigned int             test_size :1;
2068
2069    /* Run tests on reading with a combination of transforms, */
2070    unsigned int             test_transform :1;
2071    unsigned int             test_tRNS :1; /* Includes tRNS images */
2072
2073    /* When to use the use_input_precision option, this controls the gamma
2074     * validation code checks.  If set any value that is within the transformed
2075     * range input-.5 to input+.5 will be accepted, otherwise the value must be
2076     * within the normal limits.  It should not be necessary to set this; the
2077     * result should always be exact within the permitted error limits.
2078     */
2079    unsigned int             use_input_precision :1;
2080    unsigned int             use_input_precision_sbit :1;
2081    unsigned int             use_input_precision_16to8 :1;
2082
2083    /* If set assume that the calculation bit depth is set by the input
2084     * precision, not the output precision.
2085     */
2086    unsigned int             calculations_use_input_precision :1;
2087
2088    /* If set assume that the calculations are done in 16 bits even if the sample
2089     * depth is 8 bits.
2090     */
2091    unsigned int             assume_16_bit_calculations :1;
2092
2093    /* Which gamma tests to run: */
2094    unsigned int             test_gamma_threshold :1;
2095    unsigned int             test_gamma_transform :1; /* main tests */
2096    unsigned int             test_gamma_sbit :1;
2097    unsigned int             test_gamma_scale16 :1;
2098    unsigned int             test_gamma_background :1;
2099    unsigned int             test_gamma_alpha_mode :1;
2100    unsigned int             test_gamma_expand16 :1;
2101    unsigned int             test_exhaustive :1;
2102
2103    /* Whether or not to run the low-bit-depth grayscale tests.  This fails on
2104     * gamma images in some cases because of gross inaccuracies in the grayscale
2105     * gamma handling for low bit depth.
2106     */
2107    unsigned int             test_lbg :1;
2108    unsigned int             test_lbg_gamma_threshold :1;
2109    unsigned int             test_lbg_gamma_transform :1;
2110    unsigned int             test_lbg_gamma_sbit :1;
2111    unsigned int             test_lbg_gamma_composition :1;
2112
2113    unsigned int             log :1;   /* Log max error */
2114
2115    /* Buffer information, the buffer size limits the size of the chunks that can
2116     * be modified - they must fit (including header and CRC) into the buffer!
2117     */
2118    size_t                   flush;           /* Count of bytes to flush */
2119    size_t                   buffer_count;    /* Bytes in buffer */
2120    size_t                   buffer_position; /* Position in buffer */
2121    png_byte                 buffer[1024];
2122 } png_modifier;
2123
2124 /* This returns true if the test should be stopped now because it has already
2125  * failed and it is running silently.
2126   */
2127 static int fail(png_modifier *pm)
2128 {
2129    return !pm->log && !pm->this.verbose && (pm->this.nerrors > 0 ||
2130        (pm->this.treat_warnings_as_errors && pm->this.nwarnings > 0));
2131 }
2132
2133 static void
2134 modifier_init(png_modifier *pm)
2135 {
2136    memset(pm, 0, sizeof *pm);
2137    store_init(&pm->this);
2138    pm->modifications = NULL;
2139    pm->state = modifier_start;
2140    pm->sbitlow = 1U;
2141    pm->ngammas = 0;
2142    pm->ngamma_tests = 0;
2143    pm->gammas = 0;
2144    pm->current_gamma = 0;
2145    pm->encodings = 0;
2146    pm->nencodings = 0;
2147    pm->current_encoding = 0;
2148    pm->encoding_counter = 0;
2149    pm->encoding_ignored = 0;
2150    pm->repeat = 0;
2151    pm->test_uses_encoding = 0;
2152    pm->maxout8 = pm->maxpc8 = pm->maxabs8 = pm->maxcalc8 = 0;
2153    pm->maxout16 = pm->maxpc16 = pm->maxabs16 = pm->maxcalc16 = 0;
2154    pm->maxcalcG = 0;
2155    pm->limit = 4E-3;
2156    pm->log8 = pm->log16 = 0; /* Means 'off' */
2157    pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = 0;
2158    pm->error_gray_16 = pm->error_color_8 = pm->error_color_16 = 0;
2159    pm->error_indexed = 0;
2160    pm->use_update_info = 0;
2161    pm->interlace_type = PNG_INTERLACE_NONE;
2162    pm->test_standard = 0;
2163    pm->test_size = 0;
2164    pm->test_transform = 0;
2165 #  ifdef PNG_WRITE_tRNS_SUPPORTED
2166       pm->test_tRNS = 1;
2167 #  else
2168       pm->test_tRNS = 0;
2169 #  endif
2170    pm->use_input_precision = 0;
2171    pm->use_input_precision_sbit = 0;
2172    pm->use_input_precision_16to8 = 0;
2173    pm->calculations_use_input_precision = 0;
2174    pm->assume_16_bit_calculations = 0;
2175    pm->test_gamma_threshold = 0;
2176    pm->test_gamma_transform = 0;
2177    pm->test_gamma_sbit = 0;
2178    pm->test_gamma_scale16 = 0;
2179    pm->test_gamma_background = 0;
2180    pm->test_gamma_alpha_mode = 0;
2181    pm->test_gamma_expand16 = 0;
2182    pm->test_lbg = 1;
2183    pm->test_lbg_gamma_threshold = 1;
2184    pm->test_lbg_gamma_transform = 1;
2185    pm->test_lbg_gamma_sbit = 1;
2186    pm->test_lbg_gamma_composition = 1;
2187    pm->test_exhaustive = 0;
2188    pm->log = 0;
2189
2190    /* Rely on the memset for all the other fields - there are no pointers */
2191 }
2192
2193 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
2194
2195 /* This controls use of checks that explicitly know how libpng digitizes the
2196  * samples in calculations; setting this circumvents simple error limit checking
2197  * in the rgb_to_gray check, replacing it with an exact copy of the libpng 1.5
2198  * algorithm.
2199  */
2200 #define DIGITIZE PNG_LIBPNG_VER < 10700
2201
2202 /* If pm->calculations_use_input_precision is set then operations will happen
2203  * with the precision of the input, not the precision of the output depth.
2204  *
2205  * If pm->assume_16_bit_calculations is set then even 8 bit calculations use 16
2206  * bit precision.  This only affects those of the following limits that pertain
2207  * to a calculation - not a digitization operation - unless the following API is
2208  * called directly.
2209  */
2210 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
2211 #if DIGITIZE
2212 static double digitize(double value, int depth, int do_round)
2213 {
2214    /* 'value' is in the range 0 to 1, the result is the same value rounded to a
2215     * multiple of the digitization factor - 8 or 16 bits depending on both the
2216     * sample depth and the 'assume' setting.  Digitization is normally by
2217     * rounding and 'do_round' should be 1, if it is 0 the digitized value will
2218     * be truncated.
2219     */
2220    const unsigned int digitization_factor = (1U << depth) -1;
2221
2222    /* Limiting the range is done as a convenience to the caller - it's easier to
2223     * do it once here than every time at the call site.
2224     */
2225    if (value <= 0)
2226       value = 0;
2227
2228    else if (value >= 1)
2229       value = 1;
2230
2231    value *= digitization_factor;
2232    if (do_round) value += .5;
2233    return floor(value)/digitization_factor;
2234 }
2235 #endif
2236 #endif /* RGB_TO_GRAY */
2237
2238 #ifdef PNG_READ_GAMMA_SUPPORTED
2239 static double abserr(const png_modifier *pm, int in_depth, int out_depth)
2240 {
2241    /* Absolute error permitted in linear values - affected by the bit depth of
2242     * the calculations.
2243     */
2244    if (pm->assume_16_bit_calculations ||
2245       (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
2246       return pm->maxabs16;
2247    else
2248       return pm->maxabs8;
2249 }
2250
2251 static double calcerr(const png_modifier *pm, int in_depth, int out_depth)
2252 {
2253    /* Error in the linear composition arithmetic - only relevant when
2254     * composition actually happens (0 < alpha < 1).
2255     */
2256    if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
2257       return pm->maxcalc16;
2258    else if (pm->assume_16_bit_calculations)
2259       return pm->maxcalcG;
2260    else
2261       return pm->maxcalc8;
2262 }
2263
2264 static double pcerr(const png_modifier *pm, int in_depth, int out_depth)
2265 {
2266    /* Percentage error permitted in the linear values.  Note that the specified
2267     * value is a percentage but this routine returns a simple number.
2268     */
2269    if (pm->assume_16_bit_calculations ||
2270       (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
2271       return pm->maxpc16 * .01;
2272    else
2273       return pm->maxpc8 * .01;
2274 }
2275
2276 /* Output error - the error in the encoded value.  This is determined by the
2277  * digitization of the output so can be +/-0.5 in the actual output value.  In
2278  * the expand_16 case with the current code in libpng the expand happens after
2279  * all the calculations are done in 8 bit arithmetic, so even though the output
2280  * depth is 16 the output error is determined by the 8 bit calculation.
2281  *
2282  * This limit is not determined by the bit depth of internal calculations.
2283  *
2284  * The specified parameter does *not* include the base .5 digitization error but
2285  * it is added here.
2286  */
2287 static double outerr(const png_modifier *pm, int in_depth, int out_depth)
2288 {
2289    /* There is a serious error in the 2 and 4 bit grayscale transform because
2290     * the gamma table value (8 bits) is simply shifted, not rounded, so the
2291     * error in 4 bit grayscale gamma is up to the value below.  This is a hack
2292     * to allow pngvalid to succeed:
2293     *
2294     * TODO: fix this in libpng
2295     */
2296    if (out_depth == 2)
2297       return .73182-.5;
2298
2299    if (out_depth == 4)
2300       return .90644-.5;
2301
2302    if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
2303       return pm->maxout16;
2304
2305    /* This is the case where the value was calculated at 8-bit precision then
2306     * scaled to 16 bits.
2307     */
2308    else if (out_depth == 16)
2309       return pm->maxout8 * 257;
2310
2311    else
2312       return pm->maxout8;
2313 }
2314
2315 /* This does the same thing as the above however it returns the value to log,
2316  * rather than raising a warning.  This is useful for debugging to track down
2317  * exactly what set of parameters cause high error values.
2318  */
2319 static double outlog(const png_modifier *pm, int in_depth, int out_depth)
2320 {
2321    /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535)
2322     * and so must be adjusted for low bit depth grayscale:
2323     */
2324    if (out_depth <= 8)
2325    {
2326       if (pm->log8 == 0) /* switched off */
2327          return 256;
2328
2329       if (out_depth < 8)
2330          return pm->log8 / 255 * ((1<<out_depth)-1);
2331
2332       return pm->log8;
2333    }
2334
2335    if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
2336    {
2337       if (pm->log16 == 0)
2338          return 65536;
2339
2340       return pm->log16;
2341    }
2342
2343    /* This is the case where the value was calculated at 8-bit precision then
2344     * scaled to 16 bits.
2345     */
2346    if (pm->log8 == 0)
2347       return 65536;
2348
2349    return pm->log8 * 257;
2350 }
2351
2352 /* This complements the above by providing the appropriate quantization for the
2353  * final value.  Normally this would just be quantization to an integral value,
2354  * but in the 8 bit calculation case it's actually quantization to a multiple of
2355  * 257!
2356  */
2357 static int output_quantization_factor(const png_modifier *pm, int in_depth,
2358    int out_depth)
2359 {
2360    if (out_depth == 16 && in_depth != 16 &&
2361       pm->calculations_use_input_precision)
2362       return 257;
2363    else
2364       return 1;
2365 }
2366 #endif /* PNG_READ_GAMMA_SUPPORTED */
2367
2368 /* One modification structure must be provided for each chunk to be modified (in
2369  * fact more than one can be provided if multiple separate changes are desired
2370  * for a single chunk.)  Modifications include adding a new chunk when a
2371  * suitable chunk does not exist.
2372  *
2373  * The caller of modify_fn will reset the CRC of the chunk and record 'modified'
2374  * or 'added' as appropriate if the modify_fn returns 1 (true).  If the
2375  * modify_fn is NULL the chunk is simply removed.
2376  */
2377 typedef struct png_modification
2378 {
2379    struct png_modification *next;
2380    png_uint_32              chunk;
2381
2382    /* If the following is NULL all matching chunks will be removed: */
2383    int                    (*modify_fn)(struct png_modifier *pm,
2384                                struct png_modification *me, int add);
2385
2386    /* If the following is set to PLTE, IDAT or IEND and the chunk has not been
2387     * found and modified (and there is a modify_fn) the modify_fn will be called
2388     * to add the chunk before the relevant chunk.
2389     */
2390    png_uint_32              add;
2391    unsigned int             modified :1;     /* Chunk was modified */
2392    unsigned int             added    :1;     /* Chunk was added */
2393    unsigned int             removed  :1;     /* Chunk was removed */
2394 } png_modification;
2395
2396 static void
2397 modification_reset(png_modification *pmm)
2398 {
2399    if (pmm != NULL)
2400    {
2401       pmm->modified = 0;
2402       pmm->added = 0;
2403       pmm->removed = 0;
2404       modification_reset(pmm->next);
2405    }
2406 }
2407
2408 static void
2409 modification_init(png_modification *pmm)
2410 {
2411    memset(pmm, 0, sizeof *pmm);
2412    pmm->next = NULL;
2413    pmm->chunk = 0;
2414    pmm->modify_fn = NULL;
2415    pmm->add = 0;
2416    modification_reset(pmm);
2417 }
2418
2419 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
2420 static void
2421 modifier_current_encoding(const png_modifier *pm, color_encoding *ce)
2422 {
2423    if (pm->current_encoding != 0)
2424       *ce = *pm->current_encoding;
2425
2426    else
2427       memset(ce, 0, sizeof *ce);
2428
2429    ce->gamma = pm->current_gamma;
2430 }
2431 #endif
2432
2433 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
2434 static size_t
2435 safecat_current_encoding(char *buffer, size_t bufsize, size_t pos,
2436    const png_modifier *pm)
2437 {
2438    pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding,
2439       pm->current_gamma);
2440
2441    if (pm->encoding_ignored)
2442       pos = safecat(buffer, bufsize, pos, "[overridden]");
2443
2444    return pos;
2445 }
2446 #endif
2447
2448 /* Iterate through the usefully testable color encodings.  An encoding is one
2449  * of:
2450  *
2451  * 1) Nothing (no color space, no gamma).
2452  * 2) Just a gamma value from the gamma array (including 1.0)
2453  * 3) A color space from the encodings array with the corresponding gamma.
2454  * 4) The same, but with gamma 1.0 (only really useful with 16 bit calculations)
2455  *
2456  * The iterator selects these in turn, the randomizer selects one at random,
2457  * which is used depends on the setting of the 'test_exhaustive' flag.  Notice
2458  * that this function changes the colour space encoding so it must only be
2459  * called on completion of the previous test.  This is what 'modifier_reset'
2460  * does, below.
2461  *
2462  * After the function has been called the 'repeat' flag will still be set; the
2463  * caller of modifier_reset must reset it at the start of each run of the test!
2464  */
2465 static unsigned int
2466 modifier_total_encodings(const png_modifier *pm)
2467 {
2468    return 1 +                 /* (1) nothing */
2469       pm->ngammas +           /* (2) gamma values to test */
2470       pm->nencodings +        /* (3) total number of encodings */
2471       /* The following test only works after the first time through the
2472        * png_modifier code because 'bit_depth' is set when the IHDR is read.
2473        * modifier_reset, below, preserves the setting until after it has called
2474        * the iterate function (also below.)
2475        *
2476        * For this reason do not rely on this function outside a call to
2477        * modifier_reset.
2478        */
2479       ((pm->bit_depth == 16 || pm->assume_16_bit_calculations) ?
2480          pm->nencodings : 0); /* (4) encodings with gamma == 1.0 */
2481 }
2482
2483 static void
2484 modifier_encoding_iterate(png_modifier *pm)
2485 {
2486    if (!pm->repeat && /* Else something needs the current encoding again. */
2487       pm->test_uses_encoding) /* Some transform is encoding dependent */
2488    {
2489       if (pm->test_exhaustive)
2490       {
2491          if (++pm->encoding_counter >= modifier_total_encodings(pm))
2492             pm->encoding_counter = 0; /* This will stop the repeat */
2493       }
2494
2495       else
2496       {
2497          /* Not exhaustive - choose an encoding at random; generate a number in
2498           * the range 1..(max-1), so the result is always non-zero:
2499           */
2500          if (pm->encoding_counter == 0)
2501             pm->encoding_counter = random_mod(modifier_total_encodings(pm)-1)+1;
2502          else
2503             pm->encoding_counter = 0;
2504       }
2505
2506       if (pm->encoding_counter > 0)
2507          pm->repeat = 1;
2508    }
2509
2510    else if (!pm->repeat)
2511       pm->encoding_counter = 0;
2512 }
2513
2514 static void
2515 modifier_reset(png_modifier *pm)
2516 {
2517    store_read_reset(&pm->this);
2518    pm->limit = 4E-3;
2519    pm->pending_len = pm->pending_chunk = 0;
2520    pm->flush = pm->buffer_count = pm->buffer_position = 0;
2521    pm->modifications = NULL;
2522    pm->state = modifier_start;
2523    modifier_encoding_iterate(pm);
2524    /* The following must be set in the next run.  In particular
2525     * test_uses_encodings must be set in the _ini function of each transform
2526     * that looks at the encodings.  (Not the 'add' function!)
2527     */
2528    pm->test_uses_encoding = 0;
2529    pm->current_gamma = 0;
2530    pm->current_encoding = 0;
2531    pm->encoding_ignored = 0;
2532    /* These only become value after IHDR is read: */
2533    pm->bit_depth = pm->colour_type = 0;
2534 }
2535
2536 /* The following must be called before anything else to get the encoding set up
2537  * on the modifier.  In particular it must be called before the transform init
2538  * functions are called.
2539  */
2540 static void
2541 modifier_set_encoding(png_modifier *pm)
2542 {
2543    /* Set the encoding to the one specified by the current encoding counter,
2544     * first clear out all the settings - this corresponds to an encoding_counter
2545     * of 0.
2546     */
2547    pm->current_gamma = 0;
2548    pm->current_encoding = 0;
2549    pm->encoding_ignored = 0; /* not ignored yet - happens in _ini functions. */
2550
2551    /* Now, if required, set the gamma and encoding fields. */
2552    if (pm->encoding_counter > 0)
2553    {
2554       /* The gammas[] array is an array of screen gammas, not encoding gammas,
2555        * so we need the inverse:
2556        */
2557       if (pm->encoding_counter <= pm->ngammas)
2558          pm->current_gamma = 1/pm->gammas[pm->encoding_counter-1];
2559
2560       else
2561       {
2562          unsigned int i = pm->encoding_counter - pm->ngammas;
2563
2564          if (i >= pm->nencodings)
2565          {
2566             i %= pm->nencodings;
2567             pm->current_gamma = 1; /* Linear, only in the 16 bit case */
2568          }
2569
2570          else
2571             pm->current_gamma = pm->encodings[i].gamma;
2572
2573          pm->current_encoding = pm->encodings + i;
2574       }
2575    }
2576 }
2577
2578 /* Enquiry functions to find out what is set.  Notice that there is an implicit
2579  * assumption below that the first encoding in the list is the one for sRGB.
2580  */
2581 static int
2582 modifier_color_encoding_is_sRGB(const png_modifier *pm)
2583 {
2584    return pm->current_encoding != 0 && pm->current_encoding == pm->encodings &&
2585       pm->current_encoding->gamma == pm->current_gamma;
2586 }
2587
2588 static int
2589 modifier_color_encoding_is_set(const png_modifier *pm)
2590 {
2591    return pm->current_gamma != 0;
2592 }
2593
2594 /* Convenience macros. */
2595 #define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d))
2596 #define CHUNK_IHDR CHUNK(73,72,68,82)
2597 #define CHUNK_PLTE CHUNK(80,76,84,69)
2598 #define CHUNK_IDAT CHUNK(73,68,65,84)
2599 #define CHUNK_IEND CHUNK(73,69,78,68)
2600 #define CHUNK_cHRM CHUNK(99,72,82,77)
2601 #define CHUNK_gAMA CHUNK(103,65,77,65)
2602 #define CHUNK_sBIT CHUNK(115,66,73,84)
2603 #define CHUNK_sRGB CHUNK(115,82,71,66)
2604
2605 /* The guts of modification are performed during a read. */
2606 static void
2607 modifier_crc(png_bytep buffer)
2608 {
2609    /* Recalculate the chunk CRC - a complete chunk must be in
2610     * the buffer, at the start.
2611     */
2612    uInt datalen = png_get_uint_32(buffer);
2613    uLong crc = crc32(0, buffer+4, datalen+4);
2614    /* The cast to png_uint_32 is safe because a crc32 is always a 32 bit value.
2615     */
2616    png_save_uint_32(buffer+datalen+8, (png_uint_32)crc);
2617 }
2618
2619 static void
2620 modifier_setbuffer(png_modifier *pm)
2621 {
2622    modifier_crc(pm->buffer);
2623    pm->buffer_count = png_get_uint_32(pm->buffer)+12;
2624    pm->buffer_position = 0;
2625 }
2626
2627 /* Separate the callback into the actual implementation (which is passed the
2628  * png_modifier explicitly) and the callback, which gets the modifier from the
2629  * png_struct.
2630  */
2631 static void
2632 modifier_read_imp(png_modifier *pm, png_bytep pb, png_size_t st)
2633 {
2634    while (st > 0)
2635    {
2636       size_t cb;
2637       png_uint_32 len, chunk;
2638       png_modification *mod;
2639
2640       if (pm->buffer_position >= pm->buffer_count) switch (pm->state)
2641       {
2642          static png_byte sign[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
2643          case modifier_start:
2644             store_read_imp(&pm->this, pm->buffer, 8); /* size of signature. */
2645             pm->buffer_count = 8;
2646             pm->buffer_position = 0;
2647
2648             if (memcmp(pm->buffer, sign, 8) != 0)
2649                png_error(pm->this.pread, "invalid PNG file signature");
2650             pm->state = modifier_signature;
2651             break;
2652
2653          case modifier_signature:
2654             store_read_imp(&pm->this, pm->buffer, 13+12); /* size of IHDR */
2655             pm->buffer_count = 13+12;
2656             pm->buffer_position = 0;
2657
2658             if (png_get_uint_32(pm->buffer) != 13 ||
2659                 png_get_uint_32(pm->buffer+4) != CHUNK_IHDR)
2660                png_error(pm->this.pread, "invalid IHDR");
2661
2662             /* Check the list of modifiers for modifications to the IHDR. */
2663             mod = pm->modifications;
2664             while (mod != NULL)
2665             {
2666                if (mod->chunk == CHUNK_IHDR && mod->modify_fn &&
2667                    (*mod->modify_fn)(pm, mod, 0))
2668                   {
2669                   mod->modified = 1;
2670                   modifier_setbuffer(pm);
2671                   }
2672
2673                /* Ignore removal or add if IHDR! */
2674                mod = mod->next;
2675             }
2676
2677             /* Cache information from the IHDR (the modified one.) */
2678             pm->bit_depth = pm->buffer[8+8];
2679             pm->colour_type = pm->buffer[8+8+1];
2680
2681             pm->state = modifier_IHDR;
2682             pm->flush = 0;
2683             break;
2684
2685          case modifier_IHDR:
2686          default:
2687             /* Read a new chunk and process it until we see PLTE, IDAT or
2688              * IEND.  'flush' indicates that there is still some data to
2689              * output from the preceding chunk.
2690              */
2691             if ((cb = pm->flush) > 0)
2692             {
2693                if (cb > st) cb = st;
2694                pm->flush -= cb;
2695                store_read_imp(&pm->this, pb, cb);
2696                pb += cb;
2697                st -= cb;
2698                if (st == 0) return;
2699             }
2700
2701             /* No more bytes to flush, read a header, or handle a pending
2702              * chunk.
2703              */
2704             if (pm->pending_chunk != 0)
2705             {
2706                png_save_uint_32(pm->buffer, pm->pending_len);
2707                png_save_uint_32(pm->buffer+4, pm->pending_chunk);
2708                pm->pending_len = 0;
2709                pm->pending_chunk = 0;
2710             }
2711             else
2712                store_read_imp(&pm->this, pm->buffer, 8);
2713
2714             pm->buffer_count = 8;
2715             pm->buffer_position = 0;
2716
2717             /* Check for something to modify or a terminator chunk. */
2718             len = png_get_uint_32(pm->buffer);
2719             chunk = png_get_uint_32(pm->buffer+4);
2720
2721             /* Terminators first, they may have to be delayed for added
2722              * chunks
2723              */
2724             if (chunk == CHUNK_PLTE || chunk == CHUNK_IDAT ||
2725                 chunk == CHUNK_IEND)
2726             {
2727                mod = pm->modifications;
2728
2729                while (mod != NULL)
2730                {
2731                   if ((mod->add == chunk ||
2732                       (mod->add == CHUNK_PLTE && chunk == CHUNK_IDAT)) &&
2733                       mod->modify_fn != NULL && !mod->modified && !mod->added)
2734                   {
2735                      /* Regardless of what the modify function does do not run
2736                       * this again.
2737                       */
2738                      mod->added = 1;
2739
2740                      if ((*mod->modify_fn)(pm, mod, 1 /*add*/))
2741                      {
2742                         /* Reset the CRC on a new chunk */
2743                         if (pm->buffer_count > 0)
2744                            modifier_setbuffer(pm);
2745
2746                         else
2747                            {
2748                            pm->buffer_position = 0;
2749                            mod->removed = 1;
2750                            }
2751
2752                         /* The buffer has been filled with something (we assume)
2753                          * so output this.  Pend the current chunk.
2754                          */
2755                         pm->pending_len = len;
2756                         pm->pending_chunk = chunk;
2757                         break; /* out of while */
2758                      }
2759                   }
2760
2761                   mod = mod->next;
2762                }
2763
2764                /* Don't do any further processing if the buffer was modified -
2765                 * otherwise the code will end up modifying a chunk that was
2766                 * just added.
2767                 */
2768                if (mod != NULL)
2769                   break; /* out of switch */
2770             }
2771
2772             /* If we get to here then this chunk may need to be modified.  To
2773              * do this it must be less than 1024 bytes in total size, otherwise
2774              * it just gets flushed.
2775              */
2776             if (len+12 <= sizeof pm->buffer)
2777             {
2778                store_read_imp(&pm->this, pm->buffer+pm->buffer_count,
2779                    len+12-pm->buffer_count);
2780                pm->buffer_count = len+12;
2781
2782                /* Check for a modification, else leave it be. */
2783                mod = pm->modifications;
2784                while (mod != NULL)
2785                {
2786                   if (mod->chunk == chunk)
2787                   {
2788                      if (mod->modify_fn == NULL)
2789                      {
2790                         /* Remove this chunk */
2791                         pm->buffer_count = pm->buffer_position = 0;
2792                         mod->removed = 1;
2793                         break; /* Terminate the while loop */
2794                      }
2795
2796                      else if ((*mod->modify_fn)(pm, mod, 0))
2797                      {
2798                         mod->modified = 1;
2799                         /* The chunk may have been removed: */
2800                         if (pm->buffer_count == 0)
2801                         {
2802                            pm->buffer_position = 0;
2803                            break;
2804                         }
2805                         modifier_setbuffer(pm);
2806                      }
2807                   }
2808
2809                   mod = mod->next;
2810                }
2811             }
2812
2813             else
2814                pm->flush = len+12 - pm->buffer_count; /* data + crc */
2815
2816             /* Take the data from the buffer (if there is any). */
2817             break;
2818       }
2819
2820       /* Here to read from the modifier buffer (not directly from
2821        * the store, as in the flush case above.)
2822        */
2823       cb = pm->buffer_count - pm->buffer_position;
2824
2825       if (cb > st)
2826          cb = st;
2827
2828       memcpy(pb, pm->buffer + pm->buffer_position, cb);
2829       st -= cb;
2830       pb += cb;
2831       pm->buffer_position += cb;
2832    }
2833 }
2834
2835 /* The callback: */
2836 static void PNGCBAPI
2837 modifier_read(png_structp ppIn, png_bytep pb, png_size_t st)
2838 {
2839    png_const_structp pp = ppIn;
2840    png_modifier *pm = voidcast(png_modifier*, png_get_io_ptr(pp));
2841
2842    if (pm == NULL || pm->this.pread != pp)
2843       png_error(pp, "bad modifier_read call");
2844
2845    modifier_read_imp(pm, pb, st);
2846 }
2847
2848 /* Like store_progressive_read but the data is getting changed as we go so we
2849  * need a local buffer.
2850  */
2851 static void
2852 modifier_progressive_read(png_modifier *pm, png_structp pp, png_infop pi)
2853 {
2854    if (pm->this.pread != pp || pm->this.current == NULL ||
2855        pm->this.next == NULL)
2856       png_error(pp, "store state damaged (progressive)");
2857
2858    /* This is another Horowitz and Hill random noise generator.  In this case
2859     * the aim is to stress the progressive reader with truly horrible variable
2860     * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers
2861     * is generated.  We could probably just count from 1 to 32767 and get as
2862     * good a result.
2863     */
2864    for (;;)
2865    {
2866       static png_uint_32 noise = 1;
2867       png_size_t cb, cbAvail;
2868       png_byte buffer[512];
2869
2870       /* Generate 15 more bits of stuff: */
2871       noise = (noise << 9) | ((noise ^ (noise >> (9-5))) & 0x1ff);
2872       cb = noise & 0x1ff;
2873
2874       /* Check that this number of bytes are available (in the current buffer.)
2875        * (This doesn't quite work - the modifier might delete a chunk; unlikely
2876        * but possible, it doesn't happen at present because the modifier only
2877        * adds chunks to standard images.)
2878        */
2879       cbAvail = store_read_buffer_avail(&pm->this);
2880       if (pm->buffer_count > pm->buffer_position)
2881          cbAvail += pm->buffer_count - pm->buffer_position;
2882
2883       if (cb > cbAvail)
2884       {
2885          /* Check for EOF: */
2886          if (cbAvail == 0)
2887             break;
2888
2889          cb = cbAvail;
2890       }
2891
2892       modifier_read_imp(pm, buffer, cb);
2893       png_process_data(pp, pi, buffer, cb);
2894    }
2895
2896    /* Check the invariants at the end (if this fails it's a problem in this
2897     * file!)
2898     */
2899    if (pm->buffer_count > pm->buffer_position ||
2900        pm->this.next != &pm->this.current->data ||
2901        pm->this.readpos < pm->this.current->datacount)
2902       png_error(pp, "progressive read implementation error");
2903 }
2904
2905 /* Set up a modifier. */
2906 static png_structp
2907 set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id,
2908     const char *name)
2909 {
2910    /* Do this first so that the modifier fields are cleared even if an error
2911     * happens allocating the png_struct.  No allocation is done here so no
2912     * cleanup is required.
2913     */
2914    pm->state = modifier_start;
2915    pm->bit_depth = 0;
2916    pm->colour_type = 255;
2917
2918    pm->pending_len = 0;
2919    pm->pending_chunk = 0;
2920    pm->flush = 0;
2921    pm->buffer_count = 0;
2922    pm->buffer_position = 0;
2923
2924    return set_store_for_read(&pm->this, ppi, id, name);
2925 }
2926
2927
2928 /******************************** MODIFICATIONS *******************************/
2929 /* Standard modifications to add chunks.  These do not require the _SUPPORTED
2930  * macros because the chunks can be there regardless of whether this specific
2931  * libpng supports them.
2932  */
2933 typedef struct gama_modification
2934 {
2935    png_modification this;
2936    png_fixed_point  gamma;
2937 } gama_modification;
2938
2939 static int
2940 gama_modify(png_modifier *pm, png_modification *me, int add)
2941 {
2942    UNUSED(add)
2943    /* This simply dumps the given gamma value into the buffer. */
2944    png_save_uint_32(pm->buffer, 4);
2945    png_save_uint_32(pm->buffer+4, CHUNK_gAMA);
2946    png_save_uint_32(pm->buffer+8, ((gama_modification*)me)->gamma);
2947    return 1;
2948 }
2949
2950 static void
2951 gama_modification_init(gama_modification *me, png_modifier *pm, double gammad)
2952 {
2953    double g;
2954
2955    modification_init(&me->this);
2956    me->this.chunk = CHUNK_gAMA;
2957    me->this.modify_fn = gama_modify;
2958    me->this.add = CHUNK_PLTE;
2959    g = fix(gammad);
2960    me->gamma = (png_fixed_point)g;
2961    me->this.next = pm->modifications;
2962    pm->modifications = &me->this;
2963 }
2964
2965 typedef struct chrm_modification
2966 {
2967    png_modification          this;
2968    const color_encoding *encoding;
2969    png_fixed_point           wx, wy, rx, ry, gx, gy, bx, by;
2970 } chrm_modification;
2971
2972 static int
2973 chrm_modify(png_modifier *pm, png_modification *me, int add)
2974 {
2975    UNUSED(add)
2976    /* As with gAMA this just adds the required cHRM chunk to the buffer. */
2977    png_save_uint_32(pm->buffer   , 32);
2978    png_save_uint_32(pm->buffer+ 4, CHUNK_cHRM);
2979    png_save_uint_32(pm->buffer+ 8, ((chrm_modification*)me)->wx);
2980    png_save_uint_32(pm->buffer+12, ((chrm_modification*)me)->wy);
2981    png_save_uint_32(pm->buffer+16, ((chrm_modification*)me)->rx);
2982    png_save_uint_32(pm->buffer+20, ((chrm_modification*)me)->ry);
2983    png_save_uint_32(pm->buffer+24, ((chrm_modification*)me)->gx);
2984    png_save_uint_32(pm->buffer+28, ((chrm_modification*)me)->gy);
2985    png_save_uint_32(pm->buffer+32, ((chrm_modification*)me)->bx);
2986    png_save_uint_32(pm->buffer+36, ((chrm_modification*)me)->by);
2987    return 1;
2988 }
2989
2990 static void
2991 chrm_modification_init(chrm_modification *me, png_modifier *pm,
2992    const color_encoding *encoding)
2993 {
2994    CIE_color white = white_point(encoding);
2995
2996    /* Original end points: */
2997    me->encoding = encoding;
2998
2999    /* Chromaticities (in fixed point): */
3000    me->wx = fix(chromaticity_x(white));
3001    me->wy = fix(chromaticity_y(white));
3002
3003    me->rx = fix(chromaticity_x(encoding->red));
3004    me->ry = fix(chromaticity_y(encoding->red));
3005    me->gx = fix(chromaticity_x(encoding->green));
3006    me->gy = fix(chromaticity_y(encoding->green));
3007    me->bx = fix(chromaticity_x(encoding->blue));
3008    me->by = fix(chromaticity_y(encoding->blue));
3009
3010    modification_init(&me->this);
3011    me->this.chunk = CHUNK_cHRM;
3012    me->this.modify_fn = chrm_modify;
3013    me->this.add = CHUNK_PLTE;
3014    me->this.next = pm->modifications;
3015    pm->modifications = &me->this;
3016 }
3017
3018 typedef struct srgb_modification
3019 {
3020    png_modification this;
3021    png_byte         intent;
3022 } srgb_modification;
3023
3024 static int
3025 srgb_modify(png_modifier *pm, png_modification *me, int add)
3026 {
3027    UNUSED(add)
3028    /* As above, ignore add and just make a new chunk */
3029    png_save_uint_32(pm->buffer, 1);
3030    png_save_uint_32(pm->buffer+4, CHUNK_sRGB);
3031    pm->buffer[8] = ((srgb_modification*)me)->intent;
3032    return 1;
3033 }
3034
3035 static void
3036 srgb_modification_init(srgb_modification *me, png_modifier *pm, png_byte intent)
3037 {
3038    modification_init(&me->this);
3039    me->this.chunk = CHUNK_sBIT;
3040
3041    if (intent <= 3) /* if valid, else *delete* sRGB chunks */
3042    {
3043       me->this.modify_fn = srgb_modify;
3044       me->this.add = CHUNK_PLTE;
3045       me->intent = intent;
3046    }
3047
3048    else
3049    {
3050       me->this.modify_fn = 0;
3051       me->this.add = 0;
3052       me->intent = 0;
3053    }
3054
3055    me->this.next = pm->modifications;
3056    pm->modifications = &me->this;
3057 }
3058
3059 #ifdef PNG_READ_GAMMA_SUPPORTED
3060 typedef struct sbit_modification
3061 {
3062    png_modification this;
3063    png_byte         sbit;
3064 } sbit_modification;
3065
3066 static int
3067 sbit_modify(png_modifier *pm, png_modification *me, int add)
3068 {
3069    png_byte sbit = ((sbit_modification*)me)->sbit;
3070    if (pm->bit_depth > sbit)
3071    {
3072       int cb = 0;
3073       switch (pm->colour_type)
3074       {
3075          case 0:
3076             cb = 1;
3077             break;
3078
3079          case 2:
3080          case 3:
3081             cb = 3;
3082             break;
3083
3084          case 4:
3085             cb = 2;
3086             break;
3087
3088          case 6:
3089             cb = 4;
3090             break;
3091
3092          default:
3093             png_error(pm->this.pread,
3094                "unexpected colour type in sBIT modification");
3095       }
3096
3097       png_save_uint_32(pm->buffer, cb);
3098       png_save_uint_32(pm->buffer+4, CHUNK_sBIT);
3099
3100       while (cb > 0)
3101          (pm->buffer+8)[--cb] = sbit;
3102
3103       return 1;
3104    }
3105    else if (!add)
3106    {
3107       /* Remove the sBIT chunk */
3108       pm->buffer_count = pm->buffer_position = 0;
3109       return 1;
3110    }
3111    else
3112       return 0; /* do nothing */
3113 }
3114
3115 static void
3116 sbit_modification_init(sbit_modification *me, png_modifier *pm, png_byte sbit)
3117 {
3118    modification_init(&me->this);
3119    me->this.chunk = CHUNK_sBIT;
3120    me->this.modify_fn = sbit_modify;
3121    me->this.add = CHUNK_PLTE;
3122    me->sbit = sbit;
3123    me->this.next = pm->modifications;
3124    pm->modifications = &me->this;
3125 }
3126 #endif /* PNG_READ_GAMMA_SUPPORTED */
3127 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
3128
3129 /***************************** STANDARD PNG FILES *****************************/
3130 /* Standard files - write and save standard files. */
3131 /* There are two basic forms of standard images.  Those which attempt to have
3132  * all the possible pixel values (not possible for 16bpp images, but a range of
3133  * values are produced) and those which have a range of image sizes.  The former
3134  * are used for testing transforms, in particular gamma correction and bit
3135  * reduction and increase.  The latter are reserved for testing the behavior of
3136  * libpng with respect to 'odd' image sizes - particularly small images where
3137  * rows become 1 byte and interlace passes disappear.
3138  *
3139  * The first, most useful, set are the 'transform' images, the second set of
3140  * small images are the 'size' images.
3141  *
3142  * The transform files are constructed with rows which fit into a 1024 byte row
3143  * buffer.  This makes allocation easier below.  Further regardless of the file
3144  * format every row has 128 pixels (giving 1024 bytes for 64bpp formats).
3145  *
3146  * Files are stored with no gAMA or sBIT chunks, with a PLTE only when needed
3147  * and with an ID derived from the colour type, bit depth and interlace type
3148  * as above (FILEID).  The width (128) and height (variable) are not stored in
3149  * the FILEID - instead the fields are set to 0, indicating a transform file.
3150  *
3151  * The size files ar constructed with rows a maximum of 128 bytes wide, allowing
3152  * a maximum width of 16 pixels (for the 64bpp case.)  They also have a maximum
3153  * height of 16 rows.  The width and height are stored in the FILEID and, being
3154  * non-zero, indicate a size file.
3155  *
3156  * Because the PNG filter code is typically the largest CPU consumer within
3157  * libpng itself there is a tendency to attempt to optimize it.  This results in
3158  * special case code which needs to be validated.  To cause this to happen the
3159  * 'size' images are made to use each possible filter, in so far as this is
3160  * possible for smaller images.
3161  *
3162  * For palette image (colour type 3) multiple transform images are stored with
3163  * the same bit depth to allow testing of more colour combinations -
3164  * particularly important for testing the gamma code because libpng uses a
3165  * different code path for palette images.  For size images a single palette is
3166  * used.
3167  */
3168
3169 /* Make a 'standard' palette.  Because there are only 256 entries in a palette
3170  * (maximum) this actually makes a random palette in the hope that enough tests
3171  * will catch enough errors.  (Note that the same palette isn't produced every
3172  * time for the same test - it depends on what previous tests have been run -
3173  * but a given set of arguments to pngvalid will always produce the same palette
3174  * at the same test!  This is why pseudo-random number generators are useful for
3175  * testing.)
3176  *
3177  * The store must be open for write when this is called, otherwise an internal
3178  * error will occur.  This routine contains its own magic number seed, so the
3179  * palettes generated don't change if there are intervening errors (changing the
3180  * calls to the store_mark seed.)
3181  */
3182 static store_palette_entry *
3183 make_standard_palette(png_store* ps, int npalette, int do_tRNS)
3184 {
3185    static png_uint_32 palette_seed[2] = { 0x87654321, 9 };
3186
3187    int i = 0;
3188    png_byte values[256][4];
3189
3190    /* Always put in black and white plus the six primary and secondary colors.
3191     */
3192    for (; i<8; ++i)
3193    {
3194       values[i][1] = (png_byte)((i&1) ? 255U : 0U);
3195       values[i][2] = (png_byte)((i&2) ? 255U : 0U);
3196       values[i][3] = (png_byte)((i&4) ? 255U : 0U);
3197    }
3198
3199    /* Then add 62 grays (one quarter of the remaining 256 slots). */
3200    {
3201       int j = 0;
3202       png_byte random_bytes[4];
3203       png_byte need[256];
3204
3205       need[0] = 0; /*got black*/
3206       memset(need+1, 1, (sizeof need)-2); /*need these*/
3207       need[255] = 0; /*but not white*/
3208
3209       while (i<70)
3210       {
3211          png_byte b;
3212
3213          if (j==0)
3214          {
3215             make_four_random_bytes(palette_seed, random_bytes);
3216             j = 4;
3217          }
3218
3219          b = random_bytes[--j];
3220          if (need[b])
3221          {
3222             values[i][1] = b;
3223             values[i][2] = b;
3224             values[i++][3] = b;
3225          }
3226       }
3227    }
3228
3229    /* Finally add 192 colors at random - don't worry about matches to things we
3230     * already have, chance is less than 1/65536.  Don't worry about grays,
3231     * chance is the same, so we get a duplicate or extra gray less than 1 time
3232     * in 170.
3233     */
3234    for (; i<256; ++i)
3235       make_four_random_bytes(palette_seed, values[i]);
3236
3237    /* Fill in the alpha values in the first byte.  Just use all possible values
3238     * (0..255) in an apparently random order:
3239     */
3240    {
3241       store_palette_entry *palette;
3242       png_byte selector[4];
3243
3244       make_four_random_bytes(palette_seed, selector);
3245
3246       if (do_tRNS)
3247          for (i=0; i<256; ++i)
3248             values[i][0] = (png_byte)(i ^ selector[0]);
3249
3250       else
3251          for (i=0; i<256; ++i)
3252             values[i][0] = 255; /* no transparency/tRNS chunk */
3253
3254       /* 'values' contains 256 ARGB values, but we only need 'npalette'.
3255        * 'npalette' will always be a power of 2: 2, 4, 16 or 256.  In the low
3256        * bit depth cases select colors at random, else it is difficult to have
3257        * a set of low bit depth palette test with any chance of a reasonable
3258        * range of colors.  Do this by randomly permuting values into the low
3259        * 'npalette' entries using an XOR mask generated here.  This also
3260        * permutes the npalette == 256 case in a potentially useful way (there is
3261        * no relationship between palette index and the color value therein!)
3262        */
3263       palette = store_write_palette(ps, npalette);
3264
3265       for (i=0; i<npalette; ++i)
3266       {
3267          palette[i].alpha = values[i ^ selector[1]][0];
3268          palette[i].red   = values[i ^ selector[1]][1];
3269          palette[i].green = values[i ^ selector[1]][2];
3270          palette[i].blue  = values[i ^ selector[1]][3];
3271       }
3272
3273       return palette;
3274    }
3275 }
3276
3277 /* Initialize a standard palette on a write stream.  The 'do_tRNS' argument
3278  * indicates whether or not to also set the tRNS chunk.
3279  */
3280 /* TODO: the png_structp here can probably be 'const' in the future */
3281 static void
3282 init_standard_palette(png_store *ps, png_structp pp, png_infop pi, int npalette,
3283    int do_tRNS)
3284 {
3285    store_palette_entry *ppal = make_standard_palette(ps, npalette, do_tRNS);
3286
3287    {
3288       int i;
3289       png_color palette[256];
3290
3291       /* Set all entries to detect overread errors. */
3292       for (i=0; i<npalette; ++i)
3293       {
3294          palette[i].red = ppal[i].red;
3295          palette[i].green = ppal[i].green;
3296          palette[i].blue = ppal[i].blue;
3297       }
3298
3299       /* Just in case fill in the rest with detectable values: */
3300       for (; i<256; ++i)
3301          palette[i].red = palette[i].green = palette[i].blue = 42;
3302
3303       png_set_PLTE(pp, pi, palette, npalette);
3304    }
3305
3306    if (do_tRNS)
3307    {
3308       int i, j;
3309       png_byte tRNS[256];
3310
3311       /* Set all the entries, but skip trailing opaque entries */
3312       for (i=j=0; i<npalette; ++i)
3313          if ((tRNS[i] = ppal[i].alpha) < 255)
3314             j = i+1;
3315
3316       /* Fill in the remainder with a detectable value: */
3317       for (; i<256; ++i)
3318          tRNS[i] = 24;
3319
3320 #     ifdef PNG_WRITE_tRNS_SUPPORTED
3321          if (j > 0)
3322             png_set_tRNS(pp, pi, tRNS, j, 0/*color*/);
3323 #     endif
3324    }
3325 }
3326
3327 #ifdef PNG_WRITE_tRNS_SUPPORTED
3328 static void
3329 set_random_tRNS(png_structp pp, png_infop pi, const png_byte colour_type,
3330    const int bit_depth)
3331 {
3332    /* To make this useful the tRNS color needs to match at least one pixel.
3333     * Random values are fine for gray, including the 16-bit case where we know
3334     * that the test image contains all the gray values.  For RGB we need more
3335     * method as only 65536 different RGB values are generated.
3336     */
3337    png_color_16 tRNS;
3338    const png_uint_16 mask = (png_uint_16)((1U << bit_depth)-1);
3339
3340    R8(tRNS); /* makes unset fields random */
3341
3342    if (colour_type & 2/*RGB*/)
3343    {
3344       if (bit_depth == 8)
3345       {
3346          R16(tRNS.red);
3347          R16(tRNS.green);
3348          tRNS.blue = tRNS.red ^ tRNS.green;
3349          tRNS.red &= mask;
3350          tRNS.green &= mask;
3351          tRNS.blue &= mask;
3352       }
3353
3354       else /* bit_depth == 16 */
3355       {
3356          R16(tRNS.red);
3357          tRNS.green = (png_uint_16)(tRNS.red * 257);
3358          tRNS.blue = (png_uint_16)(tRNS.green * 17);
3359       }
3360    }
3361
3362    else
3363    {
3364       R16(tRNS.gray);
3365       tRNS.gray &= mask;
3366    }
3367
3368    png_set_tRNS(pp, pi, NULL, 0, &tRNS);
3369 }
3370 #endif
3371
3372 /* The number of passes is related to the interlace type. There was no libpng
3373  * API to determine this prior to 1.5, so we need an inquiry function:
3374  */
3375 static int
3376 npasses_from_interlace_type(png_const_structp pp, int interlace_type)
3377 {
3378    switch (interlace_type)
3379    {
3380    default:
3381       png_error(pp, "invalid interlace type");
3382
3383    case PNG_INTERLACE_NONE:
3384       return 1;
3385
3386    case PNG_INTERLACE_ADAM7:
3387       return PNG_INTERLACE_ADAM7_PASSES;
3388    }
3389 }
3390
3391 static unsigned int
3392 bit_size(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
3393 {
3394    switch (colour_type)
3395    {
3396       default: png_error(pp, "invalid color type");
3397
3398       case 0:  return bit_depth;
3399
3400       case 2:  return 3*bit_depth;
3401
3402       case 3:  return bit_depth;
3403
3404       case 4:  return 2*bit_depth;
3405
3406       case 6:  return 4*bit_depth;
3407    }
3408 }
3409
3410 #define TRANSFORM_WIDTH  128U
3411 #define TRANSFORM_ROWMAX (TRANSFORM_WIDTH*8U)
3412 #define SIZE_ROWMAX (16*8U) /* 16 pixels, max 8 bytes each - 128 bytes */
3413 #define STANDARD_ROWMAX TRANSFORM_ROWMAX /* The larger of the two */
3414 #define SIZE_HEIGHTMAX 16 /* Maximum range of size images */
3415
3416 static size_t
3417 transform_rowsize(png_const_structp pp, png_byte colour_type,
3418    png_byte bit_depth)
3419 {
3420    return (TRANSFORM_WIDTH * bit_size(pp, colour_type, bit_depth)) / 8;
3421 }
3422
3423 /* transform_width(pp, colour_type, bit_depth) current returns the same number
3424  * every time, so just use a macro:
3425  */
3426 #define transform_width(pp, colour_type, bit_depth) TRANSFORM_WIDTH
3427
3428 static png_uint_32
3429 transform_height(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
3430 {
3431    switch (bit_size(pp, colour_type, bit_depth))
3432    {
3433       case 1:
3434       case 2:
3435       case 4:
3436          return 1;   /* Total of 128 pixels */
3437
3438       case 8:
3439          return 2;   /* Total of 256 pixels/bytes */
3440
3441       case 16:
3442          return 512; /* Total of 65536 pixels */
3443
3444       case 24:
3445       case 32:
3446          return 512; /* 65536 pixels */
3447
3448       case 48:
3449       case 64:
3450          return 2048;/* 4 x 65536 pixels. */
3451 #        define TRANSFORM_HEIGHTMAX 2048
3452
3453       default:
3454          return 0;   /* Error, will be caught later */
3455    }
3456 }
3457
3458 #ifdef PNG_READ_SUPPORTED
3459 /* The following can only be defined here, now we have the definitions
3460  * of the transform image sizes.
3461  */
3462 static png_uint_32
3463 standard_width(png_const_structp pp, png_uint_32 id)
3464 {
3465    png_uint_32 width = WIDTH_FROM_ID(id);
3466    UNUSED(pp)
3467
3468    if (width == 0)
3469       width = transform_width(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
3470
3471    return width;
3472 }
3473
3474 static png_uint_32
3475 standard_height(png_const_structp pp, png_uint_32 id)
3476 {
3477    png_uint_32 height = HEIGHT_FROM_ID(id);
3478
3479    if (height == 0)
3480       height = transform_height(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
3481
3482    return height;
3483 }
3484
3485 static png_uint_32
3486 standard_rowsize(png_const_structp pp, png_uint_32 id)
3487 {
3488    png_uint_32 width = standard_width(pp, id);
3489
3490    /* This won't overflow: */
3491    width *= bit_size(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
3492    return (width + 7) / 8;
3493 }
3494 #endif /* PNG_READ_SUPPORTED */
3495
3496 static void
3497 transform_row(png_const_structp pp, png_byte buffer[TRANSFORM_ROWMAX],
3498    png_byte colour_type, png_byte bit_depth, png_uint_32 y)
3499 {
3500    png_uint_32 v = y << 7;
3501    png_uint_32 i = 0;
3502
3503    switch (bit_size(pp, colour_type, bit_depth))
3504    {
3505       case 1:
3506          while (i<128/8) buffer[i] = (png_byte)(v & 0xff), v += 17, ++i;
3507          return;
3508
3509       case 2:
3510          while (i<128/4) buffer[i] = (png_byte)(v & 0xff), v += 33, ++i;
3511          return;
3512
3513       case 4:
3514          while (i<128/2) buffer[i] = (png_byte)(v & 0xff), v += 65, ++i;
3515          return;
3516
3517       case 8:
3518          /* 256 bytes total, 128 bytes in each row set as follows: */
3519          while (i<128) buffer[i] = (png_byte)(v & 0xff), ++v, ++i;
3520          return;
3521
3522       case 16:
3523          /* Generate all 65536 pixel values in order, which includes the 8 bit
3524           * GA case as well as the 16 bit G case.
3525           */
3526          while (i<128)
3527          {
3528             buffer[2*i] = (png_byte)((v>>8) & 0xff);
3529             buffer[2*i+1] = (png_byte)(v & 0xff);
3530             ++v;
3531             ++i;
3532          }
3533
3534          return;
3535
3536       case 24:
3537          /* 65535 pixels, but rotate the values. */
3538          while (i<128)
3539          {
3540             /* Three bytes per pixel, r, g, b, make b by r^g */
3541             buffer[3*i+0] = (png_byte)((v >> 8) & 0xff);
3542             buffer[3*i+1] = (png_byte)(v & 0xff);
3543             buffer[3*i+2] = (png_byte)(((v >> 8) ^ v) & 0xff);
3544             ++v;
3545             ++i;
3546          }
3547
3548          return;
3549
3550       case 32:
3551          /* 65535 pixels, r, g, b, a; just replicate */
3552          while (i<128)
3553          {
3554             buffer[4*i+0] = (png_byte)((v >> 8) & 0xff);
3555             buffer[4*i+1] = (png_byte)(v & 0xff);
3556             buffer[4*i+2] = (png_byte)((v >> 8) & 0xff);
3557             buffer[4*i+3] = (png_byte)(v & 0xff);
3558             ++v;
3559             ++i;
3560          }
3561
3562          return;
3563
3564       case 48:
3565          /* y is maximum 2047, giving 4x65536 pixels, make 'r' increase by 1 at
3566           * each pixel, g increase by 257 (0x101) and 'b' by 0x1111:
3567           */
3568          while (i<128)
3569          {
3570             png_uint_32 t = v++;
3571             buffer[6*i+0] = (png_byte)((t >> 8) & 0xff);
3572             buffer[6*i+1] = (png_byte)(t & 0xff);
3573             t *= 257;
3574             buffer[6*i+2] = (png_byte)((t >> 8) & 0xff);
3575             buffer[6*i+3] = (png_byte)(t & 0xff);
3576             t *= 17;
3577             buffer[6*i+4] = (png_byte)((t >> 8) & 0xff);
3578             buffer[6*i+5] = (png_byte)(t & 0xff);
3579             ++i;
3580          }
3581
3582          return;
3583
3584       case 64:
3585          /* As above in the 32 bit case. */
3586          while (i<128)
3587          {
3588             png_uint_32 t = v++;
3589             buffer[8*i+0] = (png_byte)((t >> 8) & 0xff);
3590             buffer[8*i+1] = (png_byte)(t & 0xff);
3591             buffer[8*i+4] = (png_byte)((t >> 8) & 0xff);
3592             buffer[8*i+5] = (png_byte)(t & 0xff);
3593             t *= 257;
3594             buffer[8*i+2] = (png_byte)((t >> 8) & 0xff);
3595             buffer[8*i+3] = (png_byte)(t & 0xff);
3596             buffer[8*i+6] = (png_byte)((t >> 8) & 0xff);
3597             buffer[8*i+7] = (png_byte)(t & 0xff);
3598             ++i;
3599          }
3600          return;
3601
3602       default:
3603          break;
3604    }
3605
3606    png_error(pp, "internal error");
3607 }
3608
3609 /* This is just to do the right cast - could be changed to a function to check
3610  * 'bd' but there isn't much point.
3611  */
3612 #define DEPTH(bd) ((png_byte)(1U << (bd)))
3613
3614 /* This is just a helper for compiling on minimal systems with no write
3615  * interlacing support.  If there is no write interlacing we can't generate test
3616  * cases with interlace:
3617  */
3618 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
3619 #  define INTERLACE_LAST PNG_INTERLACE_LAST
3620 #  define check_interlace_type(type) ((void)(type))
3621 #  define set_write_interlace_handling(pp,type) png_set_interlace_handling(pp)
3622 #  define do_own_interlace 0
3623 #elif PNG_LIBPNG_VER < 10700
3624 #  define set_write_interlace_handling(pp,type) (1)
3625 static void
3626 check_interlace_type(int const interlace_type)
3627 {
3628    /* Prior to 1.7.0 libpng does not support the write of an interlaced image
3629     * unless PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the
3630     * code here does the pixel interlace itself, so:
3631     */
3632    if (interlace_type != PNG_INTERLACE_NONE)
3633    {
3634       /* This is an internal error - --interlace tests should be skipped, not
3635        * attempted.
3636        */
3637       fprintf(stderr, "pngvalid: no interlace support\n");
3638       exit(99);
3639    }
3640 }
3641 #  define INTERLACE_LAST (PNG_INTERLACE_NONE+1)
3642 #  define do_own_interlace 0
3643 #else /* libpng 1.7+ */
3644 #  define set_write_interlace_handling(pp,type)\
3645       npasses_from_interlace_type(pp,type)
3646 #  define check_interlace_type(type) ((void)(type))
3647 #  define INTERLACE_LAST PNG_INTERLACE_LAST
3648 #  define do_own_interlace 1
3649 #endif /* WRITE_INTERLACING tests */
3650
3651 #define CAN_WRITE_INTERLACE\
3652    PNG_LIBPNG_VER >= 10700 || defined PNG_WRITE_INTERLACING_SUPPORTED
3653
3654 /* Do the same thing for read interlacing; this controls whether read tests do
3655  * their own de-interlace or use libpng.
3656  */
3657 #ifdef PNG_READ_INTERLACING_SUPPORTED
3658 #  define do_read_interlace 0
3659 #else /* no libpng read interlace support */
3660 #  define do_read_interlace 1
3661 #endif
3662 /* The following two routines use the PNG interlace support macros from
3663  * png.h to interlace or deinterlace rows.
3664  */
3665 static void
3666 interlace_row(png_bytep buffer, png_const_bytep imageRow,
3667    unsigned int pixel_size, png_uint_32 w, int pass, int littleendian)
3668 {
3669    png_uint_32 xin, xout, xstep;
3670
3671    /* Note that this can, trivially, be optimized to a memcpy on pass 7, the
3672     * code is presented this way to make it easier to understand.  In practice
3673     * consult the code in the libpng source to see other ways of doing this.
3674     *
3675     * It is OK for buffer and imageRow to be identical, because 'xin' moves
3676     * faster than 'xout' and we copy up.
3677     */
3678    xin = PNG_PASS_START_COL(pass);
3679    xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
3680
3681    for (xout=0; xin<w; xin+=xstep)
3682    {
3683       pixel_copy(buffer, xout, imageRow, xin, pixel_size, littleendian);
3684       ++xout;
3685    }
3686 }
3687
3688 #ifdef PNG_READ_SUPPORTED
3689 static void
3690 deinterlace_row(png_bytep buffer, png_const_bytep row,
3691    unsigned int pixel_size, png_uint_32 w, int pass, int littleendian)
3692 {
3693    /* The inverse of the above, 'row' is part of row 'y' of the output image,
3694     * in 'buffer'.  The image is 'w' wide and this is pass 'pass', distribute
3695     * the pixels of row into buffer and return the number written (to allow
3696     * this to be checked).
3697     */
3698    png_uint_32 xin, xout, xstep;
3699
3700    xout = PNG_PASS_START_COL(pass);
3701    xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
3702
3703    for (xin=0; xout<w; xout+=xstep)
3704    {
3705       pixel_copy(buffer, xout, row, xin, pixel_size, littleendian);
3706       ++xin;
3707    }
3708 }
3709 #endif /* PNG_READ_SUPPORTED */
3710
3711 /* Make a standardized image given an image colour type, bit depth and
3712  * interlace type.  The standard images have a very restricted range of
3713  * rows and heights and are used for testing transforms rather than image
3714  * layout details.  See make_size_images below for a way to make images
3715  * that test odd sizes along with the libpng interlace handling.
3716  */
3717 #ifdef PNG_WRITE_FILTER_SUPPORTED
3718 static void
3719 choose_random_filter(png_structp pp, int start)
3720 {
3721    /* Choose filters randomly except that on the very first row ensure that
3722     * there is at least one previous row filter.
3723     */
3724    int filters = PNG_ALL_FILTERS & random_mod(256U);
3725
3726    /* There may be no filters; skip the setting. */
3727    if (filters != 0)
3728    {
3729       if (start && filters < PNG_FILTER_UP)
3730          filters |= PNG_FILTER_UP;
3731
3732       png_set_filter(pp, 0/*method*/, filters);
3733    }
3734 }
3735 #else /* !WRITE_FILTER */
3736 #  define choose_random_filter(pp, start) ((void)0)
3737 #endif /* !WRITE_FILTER */
3738
3739 static void
3740 make_transform_image(png_store* const ps, png_byte const colour_type,
3741     png_byte const bit_depth, unsigned int palette_number,
3742     int interlace_type, png_const_charp name)
3743 {
3744    context(ps, fault);
3745
3746    check_interlace_type(interlace_type);
3747
3748    Try
3749    {
3750       png_infop pi;
3751       png_structp pp = set_store_for_write(ps, &pi, name);
3752       png_uint_32 h, w;
3753
3754       /* In the event of a problem return control to the Catch statement below
3755        * to do the clean up - it is not possible to 'return' directly from a Try
3756        * block.
3757        */
3758       if (pp == NULL)
3759          Throw ps;
3760
3761       w = transform_width(pp, colour_type, bit_depth);
3762       h = transform_height(pp, colour_type, bit_depth);
3763
3764       png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
3765          PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
3766
3767 #ifdef PNG_TEXT_SUPPORTED
3768 #  if defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED)
3769 #     define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_zTXt
3770 #  else
3771 #     define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_NONE
3772 #  endif
3773       {
3774          static char key[] = "image name"; /* must be writeable */
3775          size_t pos;
3776          png_text text;
3777          char copy[FILE_NAME_SIZE];
3778
3779          /* Use a compressed text string to test the correct interaction of text
3780           * compression and IDAT compression.
3781           */
3782          text.compression = TEXT_COMPRESSION;
3783          text.key = key;
3784          /* Yuck: the text must be writable! */
3785          pos = safecat(copy, sizeof copy, 0, ps->wname);
3786          text.text = copy;
3787          text.text_length = pos;
3788          text.itxt_length = 0;
3789          text.lang = 0;
3790          text.lang_key = 0;
3791
3792          png_set_text(pp, pi, &text, 1);
3793       }
3794 #endif
3795
3796       if (colour_type == 3) /* palette */
3797          init_standard_palette(ps, pp, pi, 1U << bit_depth, 1/*do tRNS*/);
3798
3799 #     ifdef PNG_WRITE_tRNS_SUPPORTED
3800          else if (palette_number)
3801             set_random_tRNS(pp, pi, colour_type, bit_depth);
3802 #     endif
3803
3804       png_write_info(pp, pi);
3805
3806       if (png_get_rowbytes(pp, pi) !=
3807           transform_rowsize(pp, colour_type, bit_depth))
3808          png_error(pp, "transform row size incorrect");
3809
3810       else
3811       {
3812          /* Somewhat confusingly this must be called *after* png_write_info
3813           * because if it is called before, the information in *pp has not been
3814           * updated to reflect the interlaced image.
3815           */
3816          int npasses = set_write_interlace_handling(pp, interlace_type);
3817          int pass;
3818
3819          if (npasses != npasses_from_interlace_type(pp, interlace_type))
3820             png_error(pp, "write: png_set_interlace_handling failed");
3821
3822          for (pass=0; pass<npasses; ++pass)
3823          {
3824             png_uint_32 y;
3825
3826             /* do_own_interlace is a pre-defined boolean (a #define) which is
3827              * set if we have to work out the interlaced rows here.
3828              */
3829             for (y=0; y<h; ++y)
3830             {
3831                png_byte buffer[TRANSFORM_ROWMAX];
3832
3833                transform_row(pp, buffer, colour_type, bit_depth, y);
3834
3835 #              if do_own_interlace
3836                   /* If do_own_interlace *and* the image is interlaced we need a
3837                    * reduced interlace row; this may be reduced to empty.
3838                    */
3839                   if (interlace_type == PNG_INTERLACE_ADAM7)
3840                   {
3841                      /* The row must not be written if it doesn't exist, notice
3842                       * that there are two conditions here, either the row isn't
3843                       * ever in the pass or the row would be but isn't wide
3844                       * enough to contribute any pixels.  In fact the wPass test
3845                       * can be used to skip the whole y loop in this case.
3846                       */
3847                      if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
3848                          PNG_PASS_COLS(w, pass) > 0)
3849                         interlace_row(buffer, buffer,
3850                               bit_size(pp, colour_type, bit_depth), w, pass,
3851                               0/*data always bigendian*/);
3852                      else
3853                         continue;
3854                   }
3855 #              endif /* do_own_interlace */
3856
3857                choose_random_filter(pp, pass == 0 && y == 0);
3858                png_write_row(pp, buffer);
3859             }
3860          }
3861       }
3862
3863 #ifdef PNG_TEXT_SUPPORTED
3864       {
3865          static char key[] = "end marker";
3866          static char comment[] = "end";
3867          png_text text;
3868
3869          /* Use a compressed text string to test the correct interaction of text
3870           * compression and IDAT compression.
3871           */
3872          text.compression = TEXT_COMPRESSION;
3873          text.key = key;
3874          text.text = comment;
3875          text.text_length = (sizeof comment)-1;
3876          text.itxt_length = 0;
3877          text.lang = 0;
3878          text.lang_key = 0;
3879
3880          png_set_text(pp, pi, &text, 1);
3881       }
3882 #endif
3883
3884       png_write_end(pp, pi);
3885
3886       /* And store this under the appropriate id, then clean up. */
3887       store_storefile(ps, FILEID(colour_type, bit_depth, palette_number,
3888          interlace_type, 0, 0, 0));
3889
3890       store_write_reset(ps);
3891    }
3892
3893    Catch(fault)
3894    {
3895       /* Use the png_store returned by the exception. This may help the compiler
3896        * because 'ps' is not used in this branch of the setjmp.  Note that fault
3897        * and ps will always be the same value.
3898        */
3899       store_write_reset(fault);
3900    }
3901 }
3902
3903 static void
3904 make_transform_images(png_modifier *pm)
3905 {
3906    png_byte colour_type = 0;
3907    png_byte bit_depth = 0;
3908    unsigned int palette_number = 0;
3909
3910    /* This is in case of errors. */
3911    safecat(pm->this.test, sizeof pm->this.test, 0, "make standard images");
3912
3913    /* Use next_format to enumerate all the combinations we test, including
3914     * generating multiple low bit depth palette images. Non-A images (palette
3915     * and direct) are created with and without tRNS chunks.
3916     */
3917    while (next_format(&colour_type, &bit_depth, &palette_number, 1, 1))
3918    {
3919       int interlace_type;
3920
3921       for (interlace_type = PNG_INTERLACE_NONE;
3922            interlace_type < INTERLACE_LAST; ++interlace_type)
3923       {
3924          char name[FILE_NAME_SIZE];
3925
3926          standard_name(name, sizeof name, 0, colour_type, bit_depth,
3927             palette_number, interlace_type, 0, 0, do_own_interlace);
3928          make_transform_image(&pm->this, colour_type, bit_depth, palette_number,
3929             interlace_type, name);
3930       }
3931    }
3932 }
3933
3934 /* Build a single row for the 'size' test images; this fills in only the
3935  * first bit_width bits of the sample row.
3936  */
3937 static void
3938 size_row(png_byte buffer[SIZE_ROWMAX], png_uint_32 bit_width, png_uint_32 y)
3939 {
3940    /* height is in the range 1 to 16, so: */
3941    y = ((y & 1) << 7) + ((y & 2) << 6) + ((y & 4) << 5) + ((y & 8) << 4);
3942    /* the following ensures bits are set in small images: */
3943    y ^= 0xA5;
3944
3945    while (bit_width >= 8)
3946       *buffer++ = (png_byte)y++, bit_width -= 8;
3947
3948    /* There may be up to 7 remaining bits, these go in the most significant
3949     * bits of the byte.
3950     */
3951    if (bit_width > 0)
3952    {
3953       png_uint_32 mask = (1U<<(8-bit_width))-1;
3954       *buffer = (png_byte)((*buffer & mask) | (y & ~mask));
3955    }
3956 }
3957
3958 static void
3959 make_size_image(png_store* const ps, png_byte const colour_type,
3960     png_byte const bit_depth, int const interlace_type,
3961     png_uint_32 const w, png_uint_32 const h,
3962     int const do_interlace)
3963 {
3964    context(ps, fault);
3965
3966    check_interlace_type(interlace_type);
3967
3968    Try
3969    {
3970       png_infop pi;
3971       png_structp pp;
3972       unsigned int pixel_size;
3973
3974       /* Make a name and get an appropriate id for the store: */
3975       char name[FILE_NAME_SIZE];
3976       const png_uint_32 id = FILEID(colour_type, bit_depth, 0/*palette*/,
3977          interlace_type, w, h, do_interlace);
3978
3979       standard_name_from_id(name, sizeof name, 0, id);
3980       pp = set_store_for_write(ps, &pi, name);
3981
3982       /* In the event of a problem return control to the Catch statement below
3983        * to do the clean up - it is not possible to 'return' directly from a Try
3984        * block.
3985        */
3986       if (pp == NULL)
3987          Throw ps;
3988
3989       png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
3990          PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
3991
3992 #ifdef PNG_TEXT_SUPPORTED
3993       {
3994          static char key[] = "image name"; /* must be writeable */
3995          size_t pos;
3996          png_text text;
3997          char copy[FILE_NAME_SIZE];
3998
3999          /* Use a compressed text string to test the correct interaction of text
4000           * compression and IDAT compression.
4001           */
4002          text.compression = TEXT_COMPRESSION;
4003          text.key = key;
4004          /* Yuck: the text must be writable! */
4005          pos = safecat(copy, sizeof copy, 0, ps->wname);
4006          text.text = copy;
4007          text.text_length = pos;
4008          text.itxt_length = 0;
4009          text.lang = 0;
4010          text.lang_key = 0;
4011
4012          png_set_text(pp, pi, &text, 1);
4013       }
4014 #endif
4015
4016       if (colour_type == 3) /* palette */
4017          init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
4018
4019       png_write_info(pp, pi);
4020
4021       /* Calculate the bit size, divide by 8 to get the byte size - this won't
4022        * overflow because we know the w values are all small enough even for
4023        * a system where 'unsigned int' is only 16 bits.
4024        */
4025       pixel_size = bit_size(pp, colour_type, bit_depth);
4026       if (png_get_rowbytes(pp, pi) != ((w * pixel_size) + 7) / 8)
4027          png_error(pp, "size row size incorrect");
4028
4029       else
4030       {
4031          int npasses = npasses_from_interlace_type(pp, interlace_type);
4032          png_uint_32 y;
4033          int pass;
4034          png_byte image[16][SIZE_ROWMAX];
4035
4036          /* To help consistent error detection make the parts of this buffer
4037           * that aren't set below all '1':
4038           */
4039          memset(image, 0xff, sizeof image);
4040
4041          if (!do_interlace &&
4042              npasses != set_write_interlace_handling(pp, interlace_type))
4043             png_error(pp, "write: png_set_interlace_handling failed");
4044
4045          /* Prepare the whole image first to avoid making it 7 times: */
4046          for (y=0; y<h; ++y)
4047             size_row(image[y], w * pixel_size, y);
4048
4049          for (pass=0; pass<npasses; ++pass)
4050          {
4051             /* The following two are for checking the macros: */
4052             const png_uint_32 wPass = PNG_PASS_COLS(w, pass);
4053
4054             /* If do_interlace is set we don't call png_write_row for every
4055              * row because some of them are empty.  In fact, for a 1x1 image,
4056              * most of them are empty!
4057              */
4058             for (y=0; y<h; ++y)
4059             {
4060                png_const_bytep row = image[y];
4061                png_byte tempRow[SIZE_ROWMAX];
4062
4063                /* If do_interlace *and* the image is interlaced we
4064                 * need a reduced interlace row; this may be reduced
4065                 * to empty.
4066                 */
4067                if (do_interlace && interlace_type == PNG_INTERLACE_ADAM7)
4068                {
4069                   /* The row must not be written if it doesn't exist, notice
4070                    * that there are two conditions here, either the row isn't
4071                    * ever in the pass or the row would be but isn't wide
4072                    * enough to contribute any pixels.  In fact the wPass test
4073                    * can be used to skip the whole y loop in this case.
4074                    */
4075                   if (PNG_ROW_IN_INTERLACE_PASS(y, pass) && wPass > 0)
4076                   {
4077                      /* Set to all 1's for error detection (libpng tends to
4078                       * set unset things to 0).
4079                       */
4080                      memset(tempRow, 0xff, sizeof tempRow);
4081                      interlace_row(tempRow, row, pixel_size, w, pass,
4082                            0/*data always bigendian*/);
4083                      row = tempRow;
4084                   }
4085                   else
4086                      continue;
4087                }
4088
4089 #           ifdef PNG_WRITE_FILTER_SUPPORTED
4090                /* Only get to here if the row has some pixels in it, set the
4091                 * filters to 'all' for the very first row and thereafter to a
4092                 * single filter.  It isn't well documented, but png_set_filter
4093                 * does accept a filter number (per the spec) as well as a bit
4094                 * mask.
4095                 *
4096                 * The code now uses filters at random, except that on the first
4097                 * row of an image it ensures that a previous row filter is in
4098                 * the set so that libpng allocates the row buffer.
4099                 */
4100                {
4101                   int filters = 8 << random_mod(PNG_FILTER_VALUE_LAST);
4102
4103                   if (pass == 0 && y == 0 &&
4104                       (filters < PNG_FILTER_UP || w == 1U))
4105                      filters |= PNG_FILTER_UP;
4106
4107                   png_set_filter(pp, 0/*method*/, filters);
4108                }
4109 #           endif
4110
4111                png_write_row(pp, row);
4112             }
4113          }
4114       }
4115
4116 #ifdef PNG_TEXT_SUPPORTED
4117       {
4118          static char key[] = "end marker";
4119          static char comment[] = "end";
4120          png_text text;
4121
4122          /* Use a compressed text string to test the correct interaction of text
4123           * compression and IDAT compression.
4124           */
4125          text.compression = TEXT_COMPRESSION;
4126          text.key = key;
4127          text.text = comment;
4128          text.text_length = (sizeof comment)-1;
4129          text.itxt_length = 0;
4130          text.lang = 0;
4131          text.lang_key = 0;
4132
4133          png_set_text(pp, pi, &text, 1);
4134       }
4135 #endif
4136
4137       png_write_end(pp, pi);
4138
4139       /* And store this under the appropriate id, then clean up. */
4140       store_storefile(ps, id);
4141
4142       store_write_reset(ps);
4143    }
4144
4145    Catch(fault)
4146    {
4147       /* Use the png_store returned by the exception. This may help the compiler
4148        * because 'ps' is not used in this branch of the setjmp.  Note that fault
4149        * and ps will always be the same value.
4150        */
4151       store_write_reset(fault);
4152    }
4153 }
4154
4155 static void
4156 make_size(png_store* const ps, png_byte const colour_type, int bdlo,
4157     int const bdhi)
4158 {
4159    for (; bdlo <= bdhi; ++bdlo)
4160    {
4161       png_uint_32 width;
4162
4163       for (width = 1; width <= 16; ++width)
4164       {
4165          png_uint_32 height;
4166
4167          for (height = 1; height <= 16; ++height)
4168          {
4169             /* The four combinations of DIY interlace and interlace or not -
4170              * no interlace + DIY should be identical to no interlace with
4171              * libpng doing it.
4172              */
4173             make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
4174                width, height, 0);
4175             make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
4176                width, height, 1);
4177 #        ifdef PNG_WRITE_INTERLACING_SUPPORTED
4178             make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
4179                width, height, 0);
4180 #        endif
4181 #        if CAN_WRITE_INTERLACE
4182             /* 1.7.0 removes the hack that prevented app write of an interlaced
4183              * image if WRITE_INTERLACE was not supported
4184              */
4185             make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
4186                width, height, 1);
4187 #        endif
4188          }
4189       }
4190    }
4191 }
4192
4193 static void
4194 make_size_images(png_store *ps)
4195 {
4196    /* This is in case of errors. */
4197    safecat(ps->test, sizeof ps->test, 0, "make size images");
4198
4199    /* Arguments are colour_type, low bit depth, high bit depth
4200     */
4201    make_size(ps, 0, 0, WRITE_BDHI);
4202    make_size(ps, 2, 3, WRITE_BDHI);
4203    make_size(ps, 3, 0, 3 /*palette: max 8 bits*/);
4204    make_size(ps, 4, 3, WRITE_BDHI);
4205    make_size(ps, 6, 3, WRITE_BDHI);
4206 }
4207
4208 #ifdef PNG_READ_SUPPORTED
4209 /* Return a row based on image id and 'y' for checking: */
4210 static void
4211 standard_row(png_const_structp pp, png_byte std[STANDARD_ROWMAX],
4212    png_uint_32 id, png_uint_32 y)
4213 {
4214    if (WIDTH_FROM_ID(id) == 0)
4215       transform_row(pp, std, COL_FROM_ID(id), DEPTH_FROM_ID(id), y);
4216    else
4217       size_row(std, WIDTH_FROM_ID(id) * bit_size(pp, COL_FROM_ID(id),
4218          DEPTH_FROM_ID(id)), y);
4219 }
4220 #endif /* PNG_READ_SUPPORTED */
4221
4222 /* Tests - individual test cases */
4223 /* Like 'make_standard' but errors are deliberately introduced into the calls
4224  * to ensure that they get detected - it should not be possible to write an
4225  * invalid image with libpng!
4226  */
4227 /* TODO: the 'set' functions can probably all be made to take a
4228  * png_const_structp rather than a modifiable one.
4229  */
4230 #ifdef PNG_WARNINGS_SUPPORTED
4231 static void
4232 sBIT0_error_fn(png_structp pp, png_infop pi)
4233 {
4234    /* 0 is invalid... */
4235    png_color_8 bad;
4236    bad.red = bad.green = bad.blue = bad.gray = bad.alpha = 0;
4237    png_set_sBIT(pp, pi, &bad);
4238 }
4239
4240 static void
4241 sBIT_error_fn(png_structp pp, png_infop pi)
4242 {
4243    png_byte bit_depth;
4244    png_color_8 bad;
4245
4246    if (png_get_color_type(pp, pi) == PNG_COLOR_TYPE_PALETTE)
4247       bit_depth = 8;
4248
4249    else
4250       bit_depth = png_get_bit_depth(pp, pi);
4251
4252    /* Now we know the bit depth we can easily generate an invalid sBIT entry */
4253    bad.red = bad.green = bad.blue = bad.gray = bad.alpha =
4254       (png_byte)(bit_depth+1);
4255    png_set_sBIT(pp, pi, &bad);
4256 }
4257
4258 static const struct
4259 {
4260    void          (*fn)(png_structp, png_infop);
4261    const char *msg;
4262    unsigned int    warning :1; /* the error is a warning... */
4263 } error_test[] =
4264     {
4265        /* no warnings makes these errors undetectable prior to 1.7.0 */
4266        { sBIT0_error_fn, "sBIT(0): failed to detect error",
4267          PNG_LIBPNG_VER < 10700 },
4268
4269        { sBIT_error_fn, "sBIT(too big): failed to detect error",
4270          PNG_LIBPNG_VER < 10700 },
4271     };
4272
4273 static void
4274 make_error(png_store* const ps, png_byte const colour_type,
4275     png_byte bit_depth, int interlace_type, int test, png_const_charp name)
4276 {
4277    context(ps, fault);
4278
4279    check_interlace_type(interlace_type);
4280
4281    Try
4282    {
4283       png_infop pi;
4284       const png_structp pp = set_store_for_write(ps, &pi, name);
4285       png_uint_32 w, h;
4286       gnu_volatile(pp)
4287
4288       if (pp == NULL)
4289          Throw ps;
4290
4291       w = transform_width(pp, colour_type, bit_depth);
4292       gnu_volatile(w)
4293       h = transform_height(pp, colour_type, bit_depth);
4294       gnu_volatile(h)
4295       png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
4296             PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
4297
4298       if (colour_type == 3) /* palette */
4299          init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
4300
4301       /* Time for a few errors; these are in various optional chunks, the
4302        * standard tests test the standard chunks pretty well.
4303        */
4304 #     define exception__prev exception_prev_1
4305 #     define exception__env exception_env_1
4306       Try
4307       {
4308          gnu_volatile(exception__prev)
4309
4310          /* Expect this to throw: */
4311          ps->expect_error = !error_test[test].warning;
4312          ps->expect_warning = error_test[test].warning;
4313          ps->saw_warning = 0;
4314          error_test[test].fn(pp, pi);
4315
4316          /* Normally the error is only detected here: */
4317          png_write_info(pp, pi);
4318
4319          /* And handle the case where it was only a warning: */
4320          if (ps->expect_warning && ps->saw_warning)
4321             Throw ps;
4322
4323          /* If we get here there is a problem, we have success - no error or
4324           * no warning - when we shouldn't have success.  Log an error.
4325           */
4326          store_log(ps, pp, error_test[test].msg, 1 /*error*/);
4327       }
4328
4329       Catch (fault)
4330       { /* expected exit */
4331       }
4332 #undef exception__prev
4333 #undef exception__env
4334
4335       /* And clear these flags */
4336       ps->expect_warning = 0;
4337
4338       if (ps->expect_error)
4339          ps->expect_error = 0;
4340
4341       else
4342       {
4343          /* Now write the whole image, just to make sure that the detected, or
4344           * undetected, errro has not created problems inside libpng.  This
4345           * doesn't work if there was a png_error in png_write_info because that
4346           * can abort before PLTE was written.
4347           */
4348          if (png_get_rowbytes(pp, pi) !=
4349              transform_rowsize(pp, colour_type, bit_depth))
4350             png_error(pp, "row size incorrect");
4351
4352          else
4353          {
4354             int npasses = set_write_interlace_handling(pp, interlace_type);
4355             int pass;
4356
4357             if (npasses != npasses_from_interlace_type(pp, interlace_type))
4358                png_error(pp, "write: png_set_interlace_handling failed");
4359
4360             for (pass=0; pass<npasses; ++pass)
4361             {
4362                png_uint_32 y;
4363
4364                for (y=0; y<h; ++y)
4365                {
4366                   png_byte buffer[TRANSFORM_ROWMAX];
4367
4368                   transform_row(pp, buffer, colour_type, bit_depth, y);
4369
4370 #                 if do_own_interlace
4371                      /* If do_own_interlace *and* the image is interlaced we
4372                       * need a reduced interlace row; this may be reduced to
4373                       * empty.
4374                       */
4375                      if (interlace_type == PNG_INTERLACE_ADAM7)
4376                      {
4377                         /* The row must not be written if it doesn't exist,
4378                          * notice that there are two conditions here, either the
4379                          * row isn't ever in the pass or the row would be but
4380                          * isn't wide enough to contribute any pixels.  In fact
4381                          * the wPass test can be used to skip the whole y loop
4382                          * in this case.
4383                          */
4384                         if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
4385                             PNG_PASS_COLS(w, pass) > 0)
4386                            interlace_row(buffer, buffer,
4387                                  bit_size(pp, colour_type, bit_depth), w, pass,
4388                                  0/*data always bigendian*/);
4389                         else
4390                            continue;
4391                      }
4392 #                 endif /* do_own_interlace */
4393
4394                   png_write_row(pp, buffer);
4395                }
4396             }
4397          } /* image writing */
4398
4399          png_write_end(pp, pi);
4400       }
4401
4402       /* The following deletes the file that was just written. */
4403       store_write_reset(ps);
4404    }
4405
4406    Catch(fault)
4407    {
4408       store_write_reset(fault);
4409    }
4410 }
4411
4412 static int
4413 make_errors(png_modifier* const pm, png_byte const colour_type,
4414     int bdlo, int const bdhi)
4415 {
4416    for (; bdlo <= bdhi; ++bdlo)
4417    {
4418       int interlace_type;
4419
4420       for (interlace_type = PNG_INTERLACE_NONE;
4421            interlace_type < INTERLACE_LAST; ++interlace_type)
4422       {
4423          unsigned int test;
4424          char name[FILE_NAME_SIZE];
4425
4426          standard_name(name, sizeof name, 0, colour_type, 1<<bdlo, 0,
4427             interlace_type, 0, 0, do_own_interlace);
4428
4429          for (test=0; test<ARRAY_SIZE(error_test); ++test)
4430          {
4431             make_error(&pm->this, colour_type, DEPTH(bdlo), interlace_type,
4432                test, name);
4433
4434             if (fail(pm))
4435                return 0;
4436          }
4437       }
4438    }
4439
4440    return 1; /* keep going */
4441 }
4442 #endif /* PNG_WARNINGS_SUPPORTED */
4443
4444 static void
4445 perform_error_test(png_modifier *pm)
4446 {
4447 #ifdef PNG_WARNINGS_SUPPORTED /* else there are no cases that work! */
4448    /* Need to do this here because we just write in this test. */
4449    safecat(pm->this.test, sizeof pm->this.test, 0, "error test");
4450
4451    if (!make_errors(pm, 0, 0, WRITE_BDHI))
4452       return;
4453
4454    if (!make_errors(pm, 2, 3, WRITE_BDHI))
4455       return;
4456
4457    if (!make_errors(pm, 3, 0, 3))
4458       return;
4459
4460    if (!make_errors(pm, 4, 3, WRITE_BDHI))
4461       return;
4462
4463    if (!make_errors(pm, 6, 3, WRITE_BDHI))
4464       return;
4465 #else
4466    UNUSED(pm)
4467 #endif
4468 }
4469
4470 /* This is just to validate the internal PNG formatting code - if this fails
4471  * then the warning messages the library outputs will probably be garbage.
4472  */
4473 static void
4474 perform_formatting_test(png_store *ps)
4475 {
4476 #ifdef PNG_TIME_RFC1123_SUPPORTED
4477    /* The handle into the formatting code is the RFC1123 support; this test does
4478     * nothing if that is compiled out.
4479     */
4480    context(ps, fault);
4481
4482    Try
4483    {
4484       png_const_charp correct = "29 Aug 2079 13:53:60 +0000";
4485       png_const_charp result;
4486 #     if PNG_LIBPNG_VER >= 10600
4487          char timestring[29];
4488 #     endif
4489       png_structp pp;
4490       png_time pt;
4491
4492       pp = set_store_for_write(ps, NULL, "libpng formatting test");
4493
4494       if (pp == NULL)
4495          Throw ps;
4496
4497
4498       /* Arbitrary settings: */
4499       pt.year = 2079;
4500       pt.month = 8;
4501       pt.day = 29;
4502       pt.hour = 13;
4503       pt.minute = 53;
4504       pt.second = 60; /* a leap second */
4505
4506 #     if PNG_LIBPNG_VER < 10600
4507          result = png_convert_to_rfc1123(pp, &pt);
4508 #     else
4509          if (png_convert_to_rfc1123_buffer(timestring, &pt))
4510             result = timestring;
4511
4512          else
4513             result = NULL;
4514 #     endif
4515
4516       if (result == NULL)
4517          png_error(pp, "png_convert_to_rfc1123 failed");
4518
4519       if (strcmp(result, correct) != 0)
4520       {
4521          size_t pos = 0;
4522          char msg[128];
4523
4524          pos = safecat(msg, sizeof msg, pos, "png_convert_to_rfc1123(");
4525          pos = safecat(msg, sizeof msg, pos, correct);
4526          pos = safecat(msg, sizeof msg, pos, ") returned: '");
4527          pos = safecat(msg, sizeof msg, pos, result);
4528          pos = safecat(msg, sizeof msg, pos, "'");
4529
4530          png_error(pp, msg);
4531       }
4532
4533       store_write_reset(ps);
4534    }
4535
4536    Catch(fault)
4537    {
4538       store_write_reset(fault);
4539    }
4540 #else
4541    UNUSED(ps)
4542 #endif
4543 }
4544
4545 #ifdef PNG_READ_SUPPORTED
4546 /* Because we want to use the same code in both the progressive reader and the
4547  * sequential reader it is necessary to deal with the fact that the progressive
4548  * reader callbacks only have one parameter (png_get_progressive_ptr()), so this
4549  * must contain all the test parameters and all the local variables directly
4550  * accessible to the sequential reader implementation.
4551  *
4552  * The technique adopted is to reinvent part of what Dijkstra termed a
4553  * 'display'; an array of pointers to the stack frames of enclosing functions so
4554  * that a nested function definition can access the local (C auto) variables of
4555  * the functions that contain its definition.  In fact C provides the first
4556  * pointer (the local variables - the stack frame pointer) and the last (the
4557  * global variables - the BCPL global vector typically implemented as global
4558  * addresses), this code requires one more pointer to make the display - the
4559  * local variables (and function call parameters) of the function that actually
4560  * invokes either the progressive or sequential reader.
4561  *
4562  * Perhaps confusingly this technique is confounded with classes - the
4563  * 'standard_display' defined here is sub-classed as the 'gamma_display' below.
4564  * A gamma_display is a standard_display, taking advantage of the ANSI-C
4565  * requirement that the pointer to the first member of a structure must be the
4566  * same as the pointer to the structure.  This allows us to reuse standard_
4567  * functions in the gamma test code; something that could not be done with
4568  * nested functions!
4569  */
4570 typedef struct standard_display
4571 {
4572    png_store*  ps;             /* Test parameters (passed to the function) */
4573    png_byte    colour_type;
4574    png_byte    bit_depth;
4575    png_byte    red_sBIT;       /* Input data sBIT values. */
4576    png_byte    green_sBIT;
4577    png_byte    blue_sBIT;
4578    png_byte    alpha_sBIT;
4579    png_byte    interlace_type;
4580    png_byte    filler;         /* Output has a filler */
4581    png_uint_32 id;             /* Calculated file ID */
4582    png_uint_32 w;              /* Width of image */
4583    png_uint_32 h;              /* Height of image */
4584    int         npasses;        /* Number of interlaced passes */
4585    png_uint_32 pixel_size;     /* Width of one pixel in bits */
4586    png_uint_32 bit_width;      /* Width of output row in bits */
4587    size_t      cbRow;          /* Bytes in a row of the output image */
4588    int         do_interlace;   /* Do interlacing internally */
4589    int         littleendian;   /* App (row) data is little endian */
4590    int         is_transparent; /* Transparency information was present. */
4591    int         has_tRNS;       /* color type GRAY or RGB with a tRNS chunk. */
4592    int         speed;          /* Doing a speed test */
4593    int         use_update_info;/* Call update_info, not start_image */
4594    struct
4595    {
4596       png_uint_16 red;
4597       png_uint_16 green;
4598       png_uint_16 blue;
4599    }           transparent;    /* The transparent color, if set. */
4600    int         npalette;       /* Number of entries in the palette. */
4601    store_palette
4602                palette;
4603 } standard_display;
4604
4605 static void
4606 standard_display_init(standard_display *dp, png_store* ps, png_uint_32 id,
4607    int do_interlace, int use_update_info)
4608 {
4609    memset(dp, 0, sizeof *dp);
4610
4611    dp->ps = ps;
4612    dp->colour_type = COL_FROM_ID(id);
4613    dp->bit_depth = DEPTH_FROM_ID(id);
4614    if (dp->bit_depth < 1 || dp->bit_depth > 16)
4615       internal_error(ps, "internal: bad bit depth");
4616    if (dp->colour_type == 3)
4617       dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = 8;
4618    else
4619       dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT =
4620          dp->bit_depth;
4621    dp->interlace_type = INTERLACE_FROM_ID(id);
4622    check_interlace_type(dp->interlace_type);
4623    dp->id = id;
4624    /* All the rest are filled in after the read_info: */
4625    dp->w = 0;
4626    dp->h = 0;
4627    dp->npasses = 0;
4628    dp->pixel_size = 0;
4629    dp->bit_width = 0;
4630    dp->cbRow = 0;
4631    dp->do_interlace = do_interlace;
4632    dp->littleendian = 0;
4633    dp->is_transparent = 0;
4634    dp->speed = ps->speed;
4635    dp->use_update_info = use_update_info;
4636    dp->npalette = 0;
4637    /* Preset the transparent color to black: */
4638    memset(&dp->transparent, 0, sizeof dp->transparent);
4639    /* Preset the palette to full intensity/opaque througout: */
4640    memset(dp->palette, 0xff, sizeof dp->palette);
4641 }
4642
4643 /* Initialize the palette fields - this must be done later because the palette
4644  * comes from the particular png_store_file that is selected.
4645  */
4646 static void
4647 standard_palette_init(standard_display *dp)
4648 {
4649    store_palette_entry *palette = store_current_palette(dp->ps, &dp->npalette);
4650
4651    /* The remaining entries remain white/opaque. */
4652    if (dp->npalette > 0)
4653    {
4654       int i = dp->npalette;
4655       memcpy(dp->palette, palette, i * sizeof *palette);
4656
4657       /* Check for a non-opaque palette entry: */
4658       while (--i >= 0)
4659          if (palette[i].alpha < 255)
4660             break;
4661
4662 #     ifdef __GNUC__
4663          /* GCC can't handle the more obviously optimizable version. */
4664          if (i >= 0)
4665             dp->is_transparent = 1;
4666          else
4667             dp->is_transparent = 0;
4668 #     else
4669          dp->is_transparent = (i >= 0);
4670 #     endif
4671    }
4672 }
4673
4674 /* Utility to read the palette from the PNG file and convert it into
4675  * store_palette format.  This returns 1 if there is any transparency in the
4676  * palette (it does not check for a transparent colour in the non-palette case.)
4677  */
4678 static int
4679 read_palette(store_palette palette, int *npalette, png_const_structp pp,
4680    png_infop pi)
4681 {
4682    png_colorp pal;
4683    png_bytep trans_alpha;
4684    int num;
4685
4686    pal = 0;
4687    *npalette = -1;
4688
4689    if (png_get_PLTE(pp, pi, &pal, npalette) & PNG_INFO_PLTE)
4690    {
4691       int i = *npalette;
4692
4693       if (i <= 0 || i > 256)
4694          png_error(pp, "validate: invalid PLTE count");
4695
4696       while (--i >= 0)
4697       {
4698          palette[i].red = pal[i].red;
4699          palette[i].green = pal[i].green;
4700          palette[i].blue = pal[i].blue;
4701       }
4702
4703       /* Mark the remainder of the entries with a flag value (other than
4704        * white/opaque which is the flag value stored above.)
4705        */
4706       memset(palette + *npalette, 126, (256-*npalette) * sizeof *palette);
4707    }
4708
4709    else /* !png_get_PLTE */
4710    {
4711       if (*npalette != (-1))
4712          png_error(pp, "validate: invalid PLTE result");
4713       /* But there is no palette, so record this: */
4714       *npalette = 0;
4715       memset(palette, 113, sizeof (store_palette));
4716    }
4717
4718    trans_alpha = 0;
4719    num = 2; /* force error below */
4720    if ((png_get_tRNS(pp, pi, &trans_alpha, &num, 0) & PNG_INFO_tRNS) != 0 &&
4721       (trans_alpha != NULL || num != 1/*returns 1 for a transparent color*/) &&
4722       /* Oops, if a palette tRNS gets expanded png_read_update_info (at least so
4723        * far as 1.5.4) does not remove the trans_alpha pointer, only num_trans,
4724        * so in the above call we get a success, we get a pointer (who knows what
4725        * to) and we get num_trans == 0:
4726        */
4727       !(trans_alpha != NULL && num == 0)) /* TODO: fix this in libpng. */
4728    {
4729       int i;
4730
4731       /* Any of these are crash-worthy - given the implementation of
4732        * png_get_tRNS up to 1.5 an app won't crash if it just checks the
4733        * result above and fails to check that the variables it passed have
4734        * actually been filled in!  Note that if the app were to pass the
4735        * last, png_color_16p, variable too it couldn't rely on this.
4736        */
4737       if (trans_alpha == NULL || num <= 0 || num > 256 || num > *npalette)
4738          png_error(pp, "validate: unexpected png_get_tRNS (palette) result");
4739
4740       for (i=0; i<num; ++i)
4741          palette[i].alpha = trans_alpha[i];
4742
4743       for (num=*npalette; i<num; ++i)
4744          palette[i].alpha = 255;
4745
4746       for (; i<256; ++i)
4747          palette[i].alpha = 33; /* flag value */
4748
4749       return 1; /* transparency */
4750    }
4751
4752    else
4753    {
4754       /* No palette transparency - just set the alpha channel to opaque. */
4755       int i;
4756
4757       for (i=0, num=*npalette; i<num; ++i)
4758          palette[i].alpha = 255;
4759
4760       for (; i<256; ++i)
4761          palette[i].alpha = 55; /* flag value */
4762
4763       return 0; /* no transparency */
4764    }
4765 }
4766
4767 /* Utility to validate the palette if it should not have changed (the
4768  * non-transform case).
4769  */
4770 static void
4771 standard_palette_validate(standard_display *dp, png_const_structp pp,
4772    png_infop pi)
4773 {
4774    int npalette;
4775    store_palette palette;
4776
4777    if (read_palette(palette, &npalette, pp, pi) != dp->is_transparent)
4778       png_error(pp, "validate: palette transparency changed");
4779
4780    if (npalette != dp->npalette)
4781    {
4782       size_t pos = 0;
4783       char msg[64];
4784
4785       pos = safecat(msg, sizeof msg, pos, "validate: palette size changed: ");
4786       pos = safecatn(msg, sizeof msg, pos, dp->npalette);
4787       pos = safecat(msg, sizeof msg, pos, " -> ");
4788       pos = safecatn(msg, sizeof msg, pos, npalette);
4789       png_error(pp, msg);
4790    }
4791
4792    {
4793       int i = npalette; /* npalette is aliased */
4794
4795       while (--i >= 0)
4796          if (palette[i].red != dp->palette[i].red ||
4797             palette[i].green != dp->palette[i].green ||
4798             palette[i].blue != dp->palette[i].blue ||
4799             palette[i].alpha != dp->palette[i].alpha)
4800             png_error(pp, "validate: PLTE or tRNS chunk changed");
4801    }
4802 }
4803
4804 /* By passing a 'standard_display' the progressive callbacks can be used
4805  * directly by the sequential code, the functions suffixed "_imp" are the
4806  * implementations, the functions without the suffix are the callbacks.
4807  *
4808  * The code for the info callback is split into two because this callback calls
4809  * png_read_update_info or png_start_read_image and what gets called depends on
4810  * whether the info needs updating (we want to test both calls in pngvalid.)
4811  */
4812 static void
4813 standard_info_part1(standard_display *dp, png_structp pp, png_infop pi)
4814 {
4815    if (png_get_bit_depth(pp, pi) != dp->bit_depth)
4816       png_error(pp, "validate: bit depth changed");
4817
4818    if (png_get_color_type(pp, pi) != dp->colour_type)
4819       png_error(pp, "validate: color type changed");
4820
4821    if (png_get_filter_type(pp, pi) != PNG_FILTER_TYPE_BASE)
4822       png_error(pp, "validate: filter type changed");
4823
4824    if (png_get_interlace_type(pp, pi) != dp->interlace_type)
4825       png_error(pp, "validate: interlacing changed");
4826
4827    if (png_get_compression_type(pp, pi) != PNG_COMPRESSION_TYPE_BASE)
4828       png_error(pp, "validate: compression type changed");
4829
4830    dp->w = png_get_image_width(pp, pi);
4831
4832    if (dp->w != standard_width(pp, dp->id))
4833       png_error(pp, "validate: image width changed");
4834
4835    dp->h = png_get_image_height(pp, pi);
4836
4837    if (dp->h != standard_height(pp, dp->id))
4838       png_error(pp, "validate: image height changed");
4839
4840    /* Record (but don't check at present) the input sBIT according to the colour
4841     * type information.
4842     */
4843    {
4844       png_color_8p sBIT = 0;
4845
4846       if (png_get_sBIT(pp, pi, &sBIT) & PNG_INFO_sBIT)
4847       {
4848          int sBIT_invalid = 0;
4849
4850          if (sBIT == 0)
4851             png_error(pp, "validate: unexpected png_get_sBIT result");
4852
4853          if (dp->colour_type & PNG_COLOR_MASK_COLOR)
4854          {
4855             if (sBIT->red == 0 || sBIT->red > dp->bit_depth)
4856                sBIT_invalid = 1;
4857             else
4858                dp->red_sBIT = sBIT->red;
4859
4860             if (sBIT->green == 0 || sBIT->green > dp->bit_depth)
4861                sBIT_invalid = 1;
4862             else
4863                dp->green_sBIT = sBIT->green;
4864
4865             if (sBIT->blue == 0 || sBIT->blue > dp->bit_depth)
4866                sBIT_invalid = 1;
4867             else
4868                dp->blue_sBIT = sBIT->blue;
4869          }
4870
4871          else /* !COLOR */
4872          {
4873             if (sBIT->gray == 0 || sBIT->gray > dp->bit_depth)
4874                sBIT_invalid = 1;
4875             else
4876                dp->blue_sBIT = dp->green_sBIT = dp->red_sBIT = sBIT->gray;
4877          }
4878
4879          /* All 8 bits in tRNS for a palette image are significant - see the
4880           * spec.
4881           */
4882          if (dp->colour_type & PNG_COLOR_MASK_ALPHA)
4883          {
4884             if (sBIT->alpha == 0 || sBIT->alpha > dp->bit_depth)
4885                sBIT_invalid = 1;
4886             else
4887                dp->alpha_sBIT = sBIT->alpha;
4888          }
4889
4890          if (sBIT_invalid)
4891             png_error(pp, "validate: sBIT value out of range");
4892       }
4893    }
4894
4895    /* Important: this is validating the value *before* any transforms have been
4896     * put in place.  It doesn't matter for the standard tests, where there are
4897     * no transforms, but it does for other tests where rowbytes may change after
4898     * png_read_update_info.
4899     */
4900    if (png_get_rowbytes(pp, pi) != standard_rowsize(pp, dp->id))
4901       png_error(pp, "validate: row size changed");
4902
4903    /* Validate the colour type 3 palette (this can be present on other color
4904     * types.)
4905     */
4906    standard_palette_validate(dp, pp, pi);
4907
4908    /* In any case always check for a tranparent color (notice that the
4909     * colour type 3 case must not give a successful return on the get_tRNS call
4910     * with these arguments!)
4911     */
4912    {
4913       png_color_16p trans_color = 0;
4914
4915       if (png_get_tRNS(pp, pi, 0, 0, &trans_color) & PNG_INFO_tRNS)
4916       {
4917          if (trans_color == 0)
4918             png_error(pp, "validate: unexpected png_get_tRNS (color) result");
4919
4920          switch (dp->colour_type)
4921          {
4922          case 0:
4923             dp->transparent.red = dp->transparent.green = dp->transparent.blue =
4924                trans_color->gray;
4925             dp->has_tRNS = 1;
4926             break;
4927
4928          case 2:
4929             dp->transparent.red = trans_color->red;
4930             dp->transparent.green = trans_color->green;
4931             dp->transparent.blue = trans_color->blue;
4932             dp->has_tRNS = 1;
4933             break;
4934
4935          case 3:
4936             /* Not expected because it should result in the array case
4937              * above.
4938              */
4939             png_error(pp, "validate: unexpected png_get_tRNS result");
4940             break;
4941
4942          default:
4943             png_error(pp, "validate: invalid tRNS chunk with alpha image");
4944          }
4945       }
4946    }
4947
4948    /* Read the number of passes - expected to match the value used when
4949     * creating the image (interlaced or not).  This has the side effect of
4950     * turning on interlace handling (if do_interlace is not set.)
4951     */
4952    dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type);
4953    if (!dp->do_interlace)
4954    {
4955 #     ifdef PNG_READ_INTERLACING_SUPPORTED
4956          if (dp->npasses != png_set_interlace_handling(pp))
4957             png_error(pp, "validate: file changed interlace type");
4958 #     else /* !READ_INTERLACING */
4959          /* This should never happen: the relevant tests (!do_interlace) should
4960           * not be run.
4961           */
4962          if (dp->npasses > 1)
4963             png_error(pp, "validate: no libpng interlace support");
4964 #     endif /* !READ_INTERLACING */
4965    }
4966
4967    /* Caller calls png_read_update_info or png_start_read_image now, then calls
4968     * part2.
4969     */
4970 }
4971
4972 /* This must be called *after* the png_read_update_info call to get the correct
4973  * 'rowbytes' value, otherwise png_get_rowbytes will refer to the untransformed
4974  * image.
4975  */
4976 static void
4977 standard_info_part2(standard_display *dp, png_const_structp pp,
4978     png_const_infop pi, int nImages)
4979 {
4980    /* Record cbRow now that it can be found. */
4981    {
4982       png_byte ct = png_get_color_type(pp, pi);
4983       png_byte bd = png_get_bit_depth(pp, pi);
4984
4985       if (bd >= 8 && (ct == PNG_COLOR_TYPE_RGB || ct == PNG_COLOR_TYPE_GRAY) &&
4986           dp->filler)
4987           ct |= 4; /* handle filler as faked alpha channel */
4988
4989       dp->pixel_size = bit_size(pp, ct, bd);
4990    }
4991    dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
4992    dp->cbRow = png_get_rowbytes(pp, pi);
4993
4994    /* Validate the rowbytes here again. */
4995    if (dp->cbRow != (dp->bit_width+7)/8)
4996       png_error(pp, "bad png_get_rowbytes calculation");
4997
4998    /* Then ensure there is enough space for the output image(s). */
4999    store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
5000 }
5001
5002 static void
5003 standard_info_imp(standard_display *dp, png_structp pp, png_infop pi,
5004     int nImages)
5005 {
5006    /* Note that the validation routine has the side effect of turning on
5007     * interlace handling in the subsequent code.
5008     */
5009    standard_info_part1(dp, pp, pi);
5010
5011    /* And the info callback has to call this (or png_read_update_info - see
5012     * below in the png_modifier code for that variant.
5013     */
5014    if (dp->use_update_info)
5015    {
5016       /* For debugging the effect of multiple calls: */
5017       int i = dp->use_update_info;
5018       while (i-- > 0)
5019          png_read_update_info(pp, pi);
5020    }
5021
5022    else
5023       png_start_read_image(pp);
5024
5025    /* Validate the height, width and rowbytes plus ensure that sufficient buffer
5026     * exists for decoding the image.
5027     */
5028    standard_info_part2(dp, pp, pi, nImages);
5029 }
5030
5031 static void PNGCBAPI
5032 standard_info(png_structp pp, png_infop pi)
5033 {
5034    standard_display *dp = voidcast(standard_display*,
5035       png_get_progressive_ptr(pp));
5036
5037    /* Call with nImages==1 because the progressive reader can only produce one
5038     * image.
5039     */
5040    standard_info_imp(dp, pp, pi, 1 /*only one image*/);
5041 }
5042
5043 static void PNGCBAPI
5044 progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass)
5045 {
5046    png_const_structp pp = ppIn;
5047    const standard_display *dp = voidcast(standard_display*,
5048       png_get_progressive_ptr(pp));
5049
5050    /* When handling interlacing some rows will be absent in each pass, the
5051     * callback still gets called, but with a NULL pointer.  This is checked
5052     * in the 'else' clause below.  We need our own 'cbRow', but we can't call
5053     * png_get_rowbytes because we got no info structure.
5054     */
5055    if (new_row != NULL)
5056    {
5057       png_bytep row;
5058
5059       /* In the case where the reader doesn't do the interlace it gives
5060        * us the y in the sub-image:
5061        */
5062       if (dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7)
5063       {
5064 #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED
5065          /* Use this opportunity to validate the png 'current' APIs: */
5066          if (y != png_get_current_row_number(pp))
5067             png_error(pp, "png_get_current_row_number is broken");
5068
5069          if (pass != png_get_current_pass_number(pp))
5070             png_error(pp, "png_get_current_pass_number is broken");
5071 #endif /* USER_TRANSFORM_INFO */
5072
5073          y = PNG_ROW_FROM_PASS_ROW(y, pass);
5074       }
5075
5076       /* Validate this just in case. */
5077       if (y >= dp->h)
5078          png_error(pp, "invalid y to progressive row callback");
5079
5080       row = store_image_row(dp->ps, pp, 0, y);
5081
5082       /* Combine the new row into the old: */
5083 #ifdef PNG_READ_INTERLACING_SUPPORTED
5084       if (dp->do_interlace)
5085 #endif /* READ_INTERLACING */
5086       {
5087          if (dp->interlace_type == PNG_INTERLACE_ADAM7)
5088             deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass,
5089                   dp->littleendian);
5090          else
5091             row_copy(row, new_row, dp->pixel_size * dp->w, dp->littleendian);
5092       }
5093 #ifdef PNG_READ_INTERLACING_SUPPORTED
5094       else
5095          png_progressive_combine_row(pp, row, new_row);
5096 #endif /* PNG_READ_INTERLACING_SUPPORTED */
5097    }
5098
5099    else if (dp->interlace_type == PNG_INTERLACE_ADAM7 &&
5100        PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
5101        PNG_PASS_COLS(dp->w, pass) > 0)
5102       png_error(pp, "missing row in progressive de-interlacing");
5103 }
5104
5105 static void
5106 sequential_row(standard_display *dp, png_structp pp, png_infop pi,
5107     const int iImage, const int iDisplay)
5108 {
5109    const int         npasses = dp->npasses;
5110    const int         do_interlace = dp->do_interlace &&
5111       dp->interlace_type == PNG_INTERLACE_ADAM7;
5112    const png_uint_32 height = standard_height(pp, dp->id);
5113    const png_uint_32 width = standard_width(pp, dp->id);
5114    const png_store*  ps = dp->ps;
5115    int pass;
5116
5117    for (pass=0; pass<npasses; ++pass)
5118    {
5119       png_uint_32 y;
5120       png_uint_32 wPass = PNG_PASS_COLS(width, pass);
5121
5122       for (y=0; y<height; ++y)
5123       {
5124          if (do_interlace)
5125          {
5126             /* wPass may be zero or this row may not be in this pass.
5127              * png_read_row must not be called in either case.
5128              */
5129             if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass))
5130             {
5131                /* Read the row into a pair of temporary buffers, then do the
5132                 * merge here into the output rows.
5133                 */
5134                png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX];
5135
5136                /* The following aids (to some extent) error detection - we can
5137                 * see where png_read_row wrote.  Use opposite values in row and
5138                 * display to make this easier.  Don't use 0xff (which is used in
5139                 * the image write code to fill unused bits) or 0 (which is a
5140                 * likely value to overwrite unused bits with).
5141                 */
5142                memset(row, 0xc5, sizeof row);
5143                memset(display, 0x5c, sizeof display);
5144
5145                png_read_row(pp, row, display);
5146
5147                if (iImage >= 0)
5148                   deinterlace_row(store_image_row(ps, pp, iImage, y), row,
5149                      dp->pixel_size, dp->w, pass, dp->littleendian);
5150
5151                if (iDisplay >= 0)
5152                   deinterlace_row(store_image_row(ps, pp, iDisplay, y), display,
5153                      dp->pixel_size, dp->w, pass, dp->littleendian);
5154             }
5155          }
5156          else
5157             png_read_row(pp,
5158                iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL,
5159                iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL);
5160       }
5161    }
5162
5163    /* And finish the read operation (only really necessary if the caller wants
5164     * to find additional data in png_info from chunks after the last IDAT.)
5165     */
5166    png_read_end(pp, pi);
5167 }
5168
5169 #ifdef PNG_TEXT_SUPPORTED
5170 static void
5171 standard_check_text(png_const_structp pp, png_const_textp tp,
5172    png_const_charp keyword, png_const_charp text)
5173 {
5174    char msg[1024];
5175    size_t pos = safecat(msg, sizeof msg, 0, "text: ");
5176    size_t ok;
5177
5178    pos = safecat(msg, sizeof msg, pos, keyword);
5179    pos = safecat(msg, sizeof msg, pos, ": ");
5180    ok = pos;
5181
5182    if (tp->compression != TEXT_COMPRESSION)
5183    {
5184       char buf[64];
5185
5186       sprintf(buf, "compression [%d->%d], ", TEXT_COMPRESSION,
5187          tp->compression);
5188       pos = safecat(msg, sizeof msg, pos, buf);
5189    }
5190
5191    if (tp->key == NULL || strcmp(tp->key, keyword) != 0)
5192    {
5193       pos = safecat(msg, sizeof msg, pos, "keyword \"");
5194       if (tp->key != NULL)
5195       {
5196          pos = safecat(msg, sizeof msg, pos, tp->key);
5197          pos = safecat(msg, sizeof msg, pos, "\", ");
5198       }
5199
5200       else
5201          pos = safecat(msg, sizeof msg, pos, "null, ");
5202    }
5203
5204    if (tp->text == NULL)
5205       pos = safecat(msg, sizeof msg, pos, "text lost, ");
5206
5207    else
5208    {
5209       if (tp->text_length != strlen(text))
5210       {
5211          char buf[64];
5212          sprintf(buf, "text length changed[%lu->%lu], ",
5213             (unsigned long)strlen(text), (unsigned long)tp->text_length);
5214          pos = safecat(msg, sizeof msg, pos, buf);
5215       }
5216
5217       if (strcmp(tp->text, text) != 0)
5218       {
5219          pos = safecat(msg, sizeof msg, pos, "text becomes \"");
5220          pos = safecat(msg, sizeof msg, pos, tp->text);
5221          pos = safecat(msg, sizeof msg, pos, "\" (was \"");
5222          pos = safecat(msg, sizeof msg, pos, text);
5223          pos = safecat(msg, sizeof msg, pos, "\"), ");
5224       }
5225    }
5226
5227    if (tp->itxt_length != 0)
5228       pos = safecat(msg, sizeof msg, pos, "iTXt length set, ");
5229
5230    if (tp->lang != NULL)
5231    {
5232       pos = safecat(msg, sizeof msg, pos, "iTXt language \"");
5233       pos = safecat(msg, sizeof msg, pos, tp->lang);
5234       pos = safecat(msg, sizeof msg, pos, "\", ");
5235    }
5236
5237    if (tp->lang_key != NULL)
5238    {
5239       pos = safecat(msg, sizeof msg, pos, "iTXt keyword \"");
5240       pos = safecat(msg, sizeof msg, pos, tp->lang_key);
5241       pos = safecat(msg, sizeof msg, pos, "\", ");
5242    }
5243
5244    if (pos > ok)
5245    {
5246       msg[pos-2] = '\0'; /* Remove the ", " at the end */
5247       png_error(pp, msg);
5248    }
5249 }
5250
5251 static void
5252 standard_text_validate(standard_display *dp, png_const_structp pp,
5253    png_infop pi, int check_end)
5254 {
5255    png_textp tp = NULL;
5256    png_uint_32 num_text = png_get_text(pp, pi, &tp, NULL);
5257
5258    if (num_text == 2 && tp != NULL)
5259    {
5260       standard_check_text(pp, tp, "image name", dp->ps->current->name);
5261
5262       /* This exists because prior to 1.5.18 the progressive reader left the
5263        * png_struct z_stream unreset at the end of the image, so subsequent
5264        * attempts to use it simply returns Z_STREAM_END.
5265        */
5266       if (check_end)
5267          standard_check_text(pp, tp+1, "end marker", "end");
5268    }
5269
5270    else
5271    {
5272       char msg[64];
5273
5274       sprintf(msg, "expected two text items, got %lu",
5275          (unsigned long)num_text);
5276       png_error(pp, msg);
5277    }
5278 }
5279 #else
5280 #  define standard_text_validate(dp,pp,pi,check_end) ((void)0)
5281 #endif
5282
5283 static void
5284 standard_row_validate(standard_display *dp, png_const_structp pp,
5285    int iImage, int iDisplay, png_uint_32 y)
5286 {
5287    int where;
5288    png_byte std[STANDARD_ROWMAX];
5289
5290    /* The row must be pre-initialized to the magic number here for the size
5291     * tests to pass:
5292     */
5293    memset(std, 178, sizeof std);
5294    standard_row(pp, std, dp->id, y);
5295
5296    /* At the end both the 'row' and 'display' arrays should end up identical.
5297     * In earlier passes 'row' will be partially filled in, with only the pixels
5298     * that have been read so far, but 'display' will have those pixels
5299     * replicated to fill the unread pixels while reading an interlaced image.
5300     */
5301    if (iImage >= 0 &&
5302       (where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y),
5303             dp->bit_width)) != 0)
5304    {
5305       char msg[64];
5306       sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x",
5307          (unsigned long)y, where-1, std[where-1],
5308          store_image_row(dp->ps, pp, iImage, y)[where-1]);
5309       png_error(pp, msg);
5310    }
5311
5312    if (iDisplay >= 0 &&
5313       (where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y),
5314          dp->bit_width)) != 0)
5315    {
5316       char msg[64];
5317       sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x",
5318          (unsigned long)y, where-1, std[where-1],
5319          store_image_row(dp->ps, pp, iDisplay, y)[where-1]);
5320       png_error(pp, msg);
5321    }
5322 }
5323
5324 static void
5325 standard_image_validate(standard_display *dp, png_const_structp pp, int iImage,
5326     int iDisplay)
5327 {
5328    png_uint_32 y;
5329
5330    if (iImage >= 0)
5331       store_image_check(dp->ps, pp, iImage);
5332
5333    if (iDisplay >= 0)
5334       store_image_check(dp->ps, pp, iDisplay);
5335
5336    for (y=0; y<dp->h; ++y)
5337       standard_row_validate(dp, pp, iImage, iDisplay, y);
5338
5339    /* This avoids false positives if the validation code is never called! */
5340    dp->ps->validated = 1;
5341 }
5342
5343 static void PNGCBAPI
5344 standard_end(png_structp ppIn, png_infop pi)
5345 {
5346    png_const_structp pp = ppIn;
5347    standard_display *dp = voidcast(standard_display*,
5348       png_get_progressive_ptr(pp));
5349
5350    UNUSED(pi)
5351
5352    /* Validate the image - progressive reading only produces one variant for
5353     * interlaced images.
5354     */
5355    standard_text_validate(dp, pp, pi,
5356       PNG_LIBPNG_VER >= 10518/*check_end: see comments above*/);
5357    standard_image_validate(dp, pp, 0, -1);
5358 }
5359
5360 /* A single test run checking the standard image to ensure it is not damaged. */
5361 static void
5362 standard_test(png_store* const psIn, png_uint_32 const id,
5363    int do_interlace, int use_update_info)
5364 {
5365    standard_display d;
5366    context(psIn, fault);
5367
5368    /* Set up the display (stack frame) variables from the arguments to the
5369     * function and initialize the locals that are filled in later.
5370     */
5371    standard_display_init(&d, psIn, id, do_interlace, use_update_info);
5372
5373    /* Everything is protected by a Try/Catch.  The functions called also
5374     * typically have local Try/Catch blocks.
5375     */
5376    Try
5377    {
5378       png_structp pp;
5379       png_infop pi;
5380
5381       /* Get a png_struct for reading the image. This will throw an error if it
5382        * fails, so we don't need to check the result.
5383        */
5384       pp = set_store_for_read(d.ps, &pi, d.id,
5385          d.do_interlace ?  (d.ps->progressive ?
5386             "pngvalid progressive deinterlacer" :
5387             "pngvalid sequential deinterlacer") : (d.ps->progressive ?
5388                "progressive reader" : "sequential reader"));
5389
5390       /* Initialize the palette correctly from the png_store_file. */
5391       standard_palette_init(&d);
5392
5393       /* Introduce the correct read function. */
5394       if (d.ps->progressive)
5395       {
5396          png_set_progressive_read_fn(pp, &d, standard_info, progressive_row,
5397             standard_end);
5398
5399          /* Now feed data into the reader until we reach the end: */
5400          store_progressive_read(d.ps, pp, pi);
5401       }
5402       else
5403       {
5404          /* Note that this takes the store, not the display. */
5405          png_set_read_fn(pp, d.ps, store_read);
5406
5407          /* Check the header values: */
5408          png_read_info(pp, pi);
5409
5410          /* The code tests both versions of the images that the sequential
5411           * reader can produce.
5412           */
5413          standard_info_imp(&d, pp, pi, 2 /*images*/);
5414
5415          /* Need the total bytes in the image below; we can't get to this point
5416           * unless the PNG file values have been checked against the expected
5417           * values.
5418           */
5419          {
5420             sequential_row(&d, pp, pi, 0, 1);
5421
5422             /* After the last pass loop over the rows again to check that the
5423              * image is correct.
5424              */
5425             if (!d.speed)
5426             {
5427                standard_text_validate(&d, pp, pi, 1/*check_end*/);
5428                standard_image_validate(&d, pp, 0, 1);
5429             }
5430             else
5431                d.ps->validated = 1;
5432          }
5433       }
5434
5435       /* Check for validation. */
5436       if (!d.ps->validated)
5437          png_error(pp, "image read failed silently");
5438
5439       /* Successful completion. */
5440    }
5441
5442    Catch(fault)
5443       d.ps = fault; /* make sure this hasn't been clobbered. */
5444
5445    /* In either case clean up the store. */
5446    store_read_reset(d.ps);
5447 }
5448
5449 static int
5450 test_standard(png_modifier* const pm, png_byte const colour_type,
5451     int bdlo, int const bdhi)
5452 {
5453    for (; bdlo <= bdhi; ++bdlo)
5454    {
5455       int interlace_type;
5456
5457       for (interlace_type = PNG_INTERLACE_NONE;
5458            interlace_type < INTERLACE_LAST; ++interlace_type)
5459       {
5460          standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5461             interlace_type, 0, 0, 0), do_read_interlace, pm->use_update_info);
5462
5463          if (fail(pm))
5464             return 0;
5465       }
5466    }
5467
5468    return 1; /* keep going */
5469 }
5470
5471 static void
5472 perform_standard_test(png_modifier *pm)
5473 {
5474    /* Test each colour type over the valid range of bit depths (expressed as
5475     * log2(bit_depth) in turn, stop as soon as any error is detected.
5476     */
5477    if (!test_standard(pm, 0, 0, READ_BDHI))
5478       return;
5479
5480    if (!test_standard(pm, 2, 3, READ_BDHI))
5481       return;
5482
5483    if (!test_standard(pm, 3, 0, 3))
5484       return;
5485
5486    if (!test_standard(pm, 4, 3, READ_BDHI))
5487       return;
5488
5489    if (!test_standard(pm, 6, 3, READ_BDHI))
5490       return;
5491 }
5492
5493
5494 /********************************** SIZE TESTS ********************************/
5495 static int
5496 test_size(png_modifier* const pm, png_byte const colour_type,
5497     int bdlo, int const bdhi)
5498 {
5499    /* Run the tests on each combination.
5500     *
5501     * NOTE: on my 32 bit x86 each of the following blocks takes
5502     * a total of 3.5 seconds if done across every combo of bit depth
5503     * width and height.  This is a waste of time in practice, hence the
5504     * hinc and winc stuff:
5505     */
5506    static const png_byte hinc[] = {1, 3, 11, 1, 5};
5507    static const png_byte winc[] = {1, 9, 5, 7, 1};
5508    const int save_bdlo = bdlo;
5509
5510    for (; bdlo <= bdhi; ++bdlo)
5511    {
5512       png_uint_32 h, w;
5513
5514       for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo])
5515       {
5516          /* First test all the 'size' images against the sequential
5517           * reader using libpng to deinterlace (where required.)  This
5518           * validates the write side of libpng.  There are four possibilities
5519           * to validate.
5520           */
5521          standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5522             PNG_INTERLACE_NONE, w, h, 0), 0/*do_interlace*/,
5523             pm->use_update_info);
5524
5525          if (fail(pm))
5526             return 0;
5527
5528          standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5529             PNG_INTERLACE_NONE, w, h, 1), 0/*do_interlace*/,
5530             pm->use_update_info);
5531
5532          if (fail(pm))
5533             return 0;
5534
5535          /* Now validate the interlaced read side - do_interlace true,
5536           * in the progressive case this does actually make a difference
5537           * to the code used in the non-interlaced case too.
5538           */
5539          standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5540             PNG_INTERLACE_NONE, w, h, 0), 1/*do_interlace*/,
5541             pm->use_update_info);
5542
5543          if (fail(pm))
5544             return 0;
5545
5546 #     if CAN_WRITE_INTERLACE
5547          /* Validate the pngvalid code itself: */
5548          standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5549             PNG_INTERLACE_ADAM7, w, h, 1), 1/*do_interlace*/,
5550             pm->use_update_info);
5551
5552          if (fail(pm))
5553             return 0;
5554 #     endif
5555       }
5556    }
5557
5558    /* Now do the tests of libpng interlace handling, after we have made sure
5559     * that the pngvalid version works:
5560     */
5561    for (bdlo = save_bdlo; bdlo <= bdhi; ++bdlo)
5562    {
5563       png_uint_32 h, w;
5564
5565       for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo])
5566       {
5567 #     ifdef PNG_READ_INTERLACING_SUPPORTED
5568          /* Test with pngvalid generated interlaced images first; we have
5569           * already verify these are ok (unless pngvalid has self-consistent
5570           * read/write errors, which is unlikely), so this detects errors in the
5571           * read side first:
5572           */
5573 #     if CAN_WRITE_INTERLACE
5574          standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5575             PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/,
5576             pm->use_update_info);
5577
5578          if (fail(pm))
5579             return 0;
5580 #     endif
5581 #     endif /* READ_INTERLACING */
5582
5583 #     ifdef PNG_WRITE_INTERLACING_SUPPORTED
5584          /* Test the libpng write side against the pngvalid read side: */
5585          standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5586             PNG_INTERLACE_ADAM7, w, h, 0), 1/*do_interlace*/,
5587             pm->use_update_info);
5588
5589          if (fail(pm))
5590             return 0;
5591 #     endif
5592
5593 #     ifdef PNG_READ_INTERLACING_SUPPORTED
5594 #     ifdef PNG_WRITE_INTERLACING_SUPPORTED
5595          /* Test both together: */
5596          standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5597             PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/,
5598             pm->use_update_info);
5599
5600          if (fail(pm))
5601             return 0;
5602 #     endif
5603 #     endif /* READ_INTERLACING */
5604       }
5605    }
5606
5607    return 1; /* keep going */
5608 }
5609
5610 static void
5611 perform_size_test(png_modifier *pm)
5612 {
5613    /* Test each colour type over the valid range of bit depths (expressed as
5614     * log2(bit_depth) in turn, stop as soon as any error is detected.
5615     */
5616    if (!test_size(pm, 0, 0, READ_BDHI))
5617       return;
5618
5619    if (!test_size(pm, 2, 3, READ_BDHI))
5620       return;
5621
5622    /* For the moment don't do the palette test - it's a waste of time when
5623     * compared to the grayscale test.
5624     */
5625 #if 0
5626    if (!test_size(pm, 3, 0, 3))
5627       return;
5628 #endif
5629
5630    if (!test_size(pm, 4, 3, READ_BDHI))
5631       return;
5632
5633    if (!test_size(pm, 6, 3, READ_BDHI))
5634       return;
5635 }
5636
5637
5638 /******************************* TRANSFORM TESTS ******************************/
5639 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
5640 /* A set of tests to validate libpng image transforms.  The possibilities here
5641  * are legion because the transforms can be combined in a combinatorial
5642  * fashion.  To deal with this some measure of restraint is required, otherwise
5643  * the tests would take forever.
5644  */
5645 typedef struct image_pixel
5646 {
5647    /* A local (pngvalid) representation of a PNG pixel, in all its
5648     * various forms.
5649     */
5650    unsigned int red, green, blue, alpha; /* For non-palette images. */
5651    unsigned int palette_index;           /* For a palette image. */
5652    png_byte     colour_type;             /* As in the spec. */
5653    png_byte     bit_depth;               /* Defines bit size in row */
5654    png_byte     sample_depth;            /* Scale of samples */
5655    unsigned int have_tRNS :1;            /* tRNS chunk may need processing */
5656    unsigned int swap_rgb :1;             /* RGB swapped to BGR */
5657    unsigned int alpha_first :1;          /* Alpha at start, not end */
5658    unsigned int alpha_inverted :1;       /* Alpha channel inverted */
5659    unsigned int mono_inverted :1;        /* Gray channel inverted */
5660    unsigned int swap16 :1;               /* Byte swap 16-bit components */
5661    unsigned int littleendian :1;         /* High bits on right */
5662    unsigned int sig_bits :1;             /* Pixel shifted (sig bits only) */
5663
5664    /* For checking the code calculates double precision floating point values
5665     * along with an error value, accumulated from the transforms.  Because an
5666     * sBIT setting allows larger error bounds (indeed, by the spec, apparently
5667     * up to just less than +/-1 in the scaled value) the *lowest* sBIT for each
5668     * channel is stored.  This sBIT value is folded in to the stored error value
5669     * at the end of the application of the transforms to the pixel.
5670     *
5671     * If sig_bits is set above the red, green, blue and alpha values have been
5672     * scaled so they only contain the significant bits of the component values.
5673     */
5674    double   redf, greenf, bluef, alphaf;
5675    double   rede, greene, bluee, alphae;
5676    png_byte red_sBIT, green_sBIT, blue_sBIT, alpha_sBIT;
5677 } image_pixel;
5678
5679 /* Shared utility function, see below. */
5680 static void
5681 image_pixel_setf(image_pixel *this, unsigned int rMax, unsigned int gMax,
5682         unsigned int bMax, unsigned int aMax)
5683 {
5684    this->redf = this->red / (double)rMax;
5685    this->greenf = this->green / (double)gMax;
5686    this->bluef = this->blue / (double)bMax;
5687    this->alphaf = this->alpha / (double)aMax;
5688
5689    if (this->red < rMax)
5690       this->rede = this->redf * DBL_EPSILON;
5691    else
5692       this->rede = 0;
5693    if (this->green < gMax)
5694       this->greene = this->greenf * DBL_EPSILON;
5695    else
5696       this->greene = 0;
5697    if (this->blue < bMax)
5698       this->bluee = this->bluef * DBL_EPSILON;
5699    else
5700       this->bluee = 0;
5701    if (this->alpha < aMax)
5702       this->alphae = this->alphaf * DBL_EPSILON;
5703    else
5704       this->alphae = 0;
5705 }
5706
5707 /* Initialize the structure for the next pixel - call this before doing any
5708  * transforms and call it for each pixel since all the fields may need to be
5709  * reset.
5710  */
5711 static void
5712 image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type,
5713     png_byte bit_depth, png_uint_32 x, store_palette palette,
5714     const image_pixel *format /*from pngvalid transform of input*/)
5715 {
5716    const png_byte sample_depth = (png_byte)(colour_type ==
5717       PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth);
5718    const unsigned int max = (1U<<sample_depth)-1;
5719    const int swap16 = (format != 0 && format->swap16);
5720    const int littleendian = (format != 0 && format->littleendian);
5721    const int sig_bits = (format != 0 && format->sig_bits);
5722
5723    /* Initially just set everything to the same number and the alpha to opaque.
5724     * Note that this currently assumes a simple palette where entry x has colour
5725     * rgb(x,x,x)!
5726     */
5727    this->palette_index = this->red = this->green = this->blue =
5728       sample(row, colour_type, bit_depth, x, 0, swap16, littleendian);
5729    this->alpha = max;
5730    this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT =
5731       sample_depth;
5732
5733    /* Then override as appropriate: */
5734    if (colour_type == 3) /* palette */
5735    {
5736       /* This permits the caller to default to the sample value. */
5737       if (palette != 0)
5738       {
5739          const unsigned int i = this->palette_index;
5740
5741          this->red = palette[i].red;
5742          this->green = palette[i].green;
5743          this->blue = palette[i].blue;
5744          this->alpha = palette[i].alpha;
5745       }
5746    }
5747
5748    else /* not palette */
5749    {
5750       unsigned int i = 0;
5751
5752       if ((colour_type & 4) != 0 && format != 0 && format->alpha_first)
5753       {
5754          this->alpha = this->red;
5755          /* This handles the gray case for 'AG' pixels */
5756          this->palette_index = this->red = this->green = this->blue =
5757             sample(row, colour_type, bit_depth, x, 1, swap16, littleendian);
5758          i = 1;
5759       }
5760
5761       if (colour_type & 2)
5762       {
5763          /* Green is second for both BGR and RGB: */
5764          this->green = sample(row, colour_type, bit_depth, x, ++i, swap16,
5765                  littleendian);
5766
5767          if (format != 0 && format->swap_rgb) /* BGR */
5768              this->red = sample(row, colour_type, bit_depth, x, ++i, swap16,
5769                      littleendian);
5770          else
5771              this->blue = sample(row, colour_type, bit_depth, x, ++i, swap16,
5772                      littleendian);
5773       }
5774
5775       else /* grayscale */ if (format != 0 && format->mono_inverted)
5776          this->red = this->green = this->blue = this->red ^ max;
5777
5778       if ((colour_type & 4) != 0) /* alpha */
5779       {
5780          if (format == 0 || !format->alpha_first)
5781              this->alpha = sample(row, colour_type, bit_depth, x, ++i, swap16,
5782                      littleendian);
5783
5784          if (format != 0 && format->alpha_inverted)
5785             this->alpha ^= max;
5786       }
5787    }
5788
5789    /* Calculate the scaled values, these are simply the values divided by
5790     * 'max' and the error is initialized to the double precision epsilon value
5791     * from the header file.
5792     */
5793    image_pixel_setf(this,
5794       sig_bits ? (1U << format->red_sBIT)-1 : max,
5795       sig_bits ? (1U << format->green_sBIT)-1 : max,
5796       sig_bits ? (1U << format->blue_sBIT)-1 : max,
5797       sig_bits ? (1U << format->alpha_sBIT)-1 : max);
5798
5799    /* Store the input information for use in the transforms - these will
5800     * modify the information.
5801     */
5802    this->colour_type = colour_type;
5803    this->bit_depth = bit_depth;
5804    this->sample_depth = sample_depth;
5805    this->have_tRNS = 0;
5806    this->swap_rgb = 0;
5807    this->alpha_first = 0;
5808    this->alpha_inverted = 0;
5809    this->mono_inverted = 0;
5810    this->swap16 = 0;
5811    this->littleendian = 0;
5812    this->sig_bits = 0;
5813 }
5814
5815 #if defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_GRAY_TO_RGB_SUPPORTED\
5816    || defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_EXPAND_16_SUPPORTED\
5817    || defined PNG_READ_BACKGROUND_SUPPORTED
5818 /* Convert a palette image to an rgb image.  This necessarily converts the tRNS
5819  * chunk at the same time, because the tRNS will be in palette form.  The way
5820  * palette validation works means that the original palette is never updated,
5821  * instead the image_pixel value from the row contains the RGB of the
5822  * corresponding palette entry and *this* is updated.  Consequently this routine
5823  * only needs to change the colour type information.
5824  */
5825 static void
5826 image_pixel_convert_PLTE(image_pixel *this)
5827 {
5828    if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
5829    {
5830       if (this->have_tRNS)
5831       {
5832          this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
5833          this->have_tRNS = 0;
5834       }
5835       else
5836          this->colour_type = PNG_COLOR_TYPE_RGB;
5837
5838       /* The bit depth of the row changes at this point too (notice that this is
5839        * the row format, not the sample depth, which is separate.)
5840        */
5841       this->bit_depth = 8;
5842    }
5843 }
5844
5845 /* Add an alpha channel; this will import the tRNS information because tRNS is
5846  * not valid in an alpha image.  The bit depth will invariably be set to at
5847  * least 8 prior to 1.7.0.  Palette images will be converted to alpha (using
5848  * the above API).  With png_set_background the alpha channel is never expanded
5849  * but this routine is used by pngvalid to simplify code; 'for_background'
5850  * records this.
5851  */
5852 static void
5853 image_pixel_add_alpha(image_pixel *this, const standard_display *display,
5854    int for_background)
5855 {
5856    if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
5857       image_pixel_convert_PLTE(this);
5858
5859    if ((this->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
5860    {
5861       if (this->colour_type == PNG_COLOR_TYPE_GRAY)
5862       {
5863 #        if PNG_LIBPNG_VER < 10700
5864             if (!for_background && this->bit_depth < 8)
5865                this->bit_depth = this->sample_depth = 8;
5866 #        endif
5867
5868          if (this->have_tRNS)
5869          {
5870             /* After 1.7 the expansion of bit depth only happens if there is a
5871              * tRNS chunk to expand at this point.
5872              */
5873 #           if PNG_LIBPNG_VER >= 10700
5874                if (!for_background && this->bit_depth < 8)
5875                   this->bit_depth = this->sample_depth = 8;
5876 #           endif
5877
5878             this->have_tRNS = 0;
5879
5880             /* Check the input, original, channel value here against the
5881              * original tRNS gray chunk valie.
5882              */
5883             if (this->red == display->transparent.red)
5884                this->alphaf = 0;
5885             else
5886                this->alphaf = 1;
5887          }
5888          else
5889             this->alphaf = 1;
5890
5891          this->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
5892       }
5893
5894       else if (this->colour_type == PNG_COLOR_TYPE_RGB)
5895       {
5896          if (this->have_tRNS)
5897          {
5898             this->have_tRNS = 0;
5899
5900             /* Again, check the exact input values, not the current transformed
5901              * value!
5902              */
5903             if (this->red == display->transparent.red &&
5904                this->green == display->transparent.green &&
5905                this->blue == display->transparent.blue)
5906                this->alphaf = 0;
5907             else
5908                this->alphaf = 1;
5909          }
5910          else
5911             this->alphaf = 1;
5912
5913          this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
5914       }
5915
5916       /* The error in the alpha is zero and the sBIT value comes from the
5917        * original sBIT data (actually it will always be the original bit depth).
5918        */
5919       this->alphae = 0;
5920       this->alpha_sBIT = display->alpha_sBIT;
5921    }
5922 }
5923 #endif /* transforms that need image_pixel_add_alpha */
5924
5925 struct transform_display;
5926 typedef struct image_transform
5927 {
5928    /* The name of this transform: a string. */
5929    const char *name;
5930
5931    /* Each transform can be disabled from the command line: */
5932    int enable;
5933
5934    /* The global list of transforms; read only. */
5935    struct image_transform *const list;
5936
5937    /* The global count of the number of times this transform has been set on an
5938     * image.
5939     */
5940    unsigned int global_use;
5941
5942    /* The local count of the number of times this transform has been set. */
5943    unsigned int local_use;
5944
5945    /* The next transform in the list, each transform must call its own next
5946     * transform after it has processed the pixel successfully.
5947     */
5948    const struct image_transform *next;
5949
5950    /* A single transform for the image, expressed as a series of function
5951     * callbacks and some space for values.
5952     *
5953     * First a callback to add any required modifications to the png_modifier;
5954     * this gets called just before the modifier is set up for read.
5955     */
5956    void (*ini)(const struct image_transform *this,
5957       struct transform_display *that);
5958
5959    /* And a callback to set the transform on the current png_read_struct:
5960     */
5961    void (*set)(const struct image_transform *this,
5962       struct transform_display *that, png_structp pp, png_infop pi);
5963
5964    /* Then a transform that takes an input pixel in one PNG format or another
5965     * and modifies it by a pngvalid implementation of the transform (thus
5966     * duplicating the libpng intent without, we hope, duplicating the bugs
5967     * in the libpng implementation!)  The png_structp is solely to allow error
5968     * reporting via png_error and png_warning.
5969     */
5970    void (*mod)(const struct image_transform *this, image_pixel *that,
5971       png_const_structp pp, const struct transform_display *display);
5972
5973    /* Add this transform to the list and return true if the transform is
5974     * meaningful for this colour type and bit depth - if false then the
5975     * transform should have no effect on the image so there's not a lot of
5976     * point running it.
5977     */
5978    int (*add)(struct image_transform *this,
5979       const struct image_transform **that, png_byte colour_type,
5980       png_byte bit_depth);
5981 } image_transform;
5982
5983 typedef struct transform_display
5984 {
5985    standard_display this;
5986
5987    /* Parameters */
5988    png_modifier*              pm;
5989    const image_transform* transform_list;
5990    unsigned int max_gamma_8;
5991
5992    /* Local variables */
5993    png_byte output_colour_type;
5994    png_byte output_bit_depth;
5995    png_byte unpacked;
5996
5997    /* Modifications (not necessarily used.) */
5998    gama_modification gama_mod;
5999    chrm_modification chrm_mod;
6000    srgb_modification srgb_mod;
6001 } transform_display;
6002
6003 /* Set sRGB, cHRM and gAMA transforms as required by the current encoding. */
6004 static void
6005 transform_set_encoding(transform_display *this)
6006 {
6007    /* Set up the png_modifier '_current' fields then use these to determine how
6008     * to add appropriate chunks.
6009     */
6010    png_modifier *pm = this->pm;
6011
6012    modifier_set_encoding(pm);
6013
6014    if (modifier_color_encoding_is_set(pm))
6015    {
6016       if (modifier_color_encoding_is_sRGB(pm))
6017          srgb_modification_init(&this->srgb_mod, pm, PNG_sRGB_INTENT_ABSOLUTE);
6018
6019       else
6020       {
6021          /* Set gAMA and cHRM separately. */
6022          gama_modification_init(&this->gama_mod, pm, pm->current_gamma);
6023
6024          if (pm->current_encoding != 0)
6025             chrm_modification_init(&this->chrm_mod, pm, pm->current_encoding);
6026       }
6027    }
6028 }
6029
6030 /* Three functions to end the list: */
6031 static void
6032 image_transform_ini_end(const image_transform *this,
6033    transform_display *that)
6034 {
6035    UNUSED(this)
6036    UNUSED(that)
6037 }
6038
6039 static void
6040 image_transform_set_end(const image_transform *this,
6041    transform_display *that, png_structp pp, png_infop pi)
6042 {
6043    UNUSED(this)
6044    UNUSED(that)
6045    UNUSED(pp)
6046    UNUSED(pi)
6047 }
6048
6049 /* At the end of the list recalculate the output image pixel value from the
6050  * double precision values set up by the preceding 'mod' calls:
6051  */
6052 static unsigned int
6053 sample_scale(double sample_value, unsigned int scale)
6054 {
6055    sample_value = floor(sample_value * scale + .5);
6056
6057    /* Return NaN as 0: */
6058    if (!(sample_value > 0))
6059       sample_value = 0;
6060    else if (sample_value > scale)
6061       sample_value = scale;
6062
6063    return (unsigned int)sample_value;
6064 }
6065
6066 static void
6067 image_transform_mod_end(const image_transform *this, image_pixel *that,
6068     png_const_structp pp, const transform_display *display)
6069 {
6070    const unsigned int scale = (1U<<that->sample_depth)-1;
6071    const int sig_bits = that->sig_bits;
6072
6073    UNUSED(this)
6074    UNUSED(pp)
6075    UNUSED(display)
6076
6077    /* At the end recalculate the digitized red green and blue values according
6078     * to the current sample_depth of the pixel.
6079     *
6080     * The sample value is simply scaled to the maximum, checking for over
6081     * and underflow (which can both happen for some image transforms,
6082     * including simple size scaling, though libpng doesn't do that at present.
6083     */
6084    that->red = sample_scale(that->redf, scale);
6085
6086    /* This is a bit bogus; really the above calculation should use the red_sBIT
6087     * value, not sample_depth, but because libpng does png_set_shift by just
6088     * shifting the bits we get errors if we don't do it the same way.
6089     */
6090    if (sig_bits && that->red_sBIT < that->sample_depth)
6091       that->red >>= that->sample_depth - that->red_sBIT;
6092
6093    /* The error value is increased, at the end, according to the lowest sBIT
6094     * value seen.  Common sense tells us that the intermediate integer
6095     * representations are no more accurate than +/- 0.5 in the integral values,
6096     * the sBIT allows the implementation to be worse than this.  In addition the
6097     * PNG specification actually permits any error within the range (-1..+1),
6098     * but that is ignored here.  Instead the final digitized value is compared,
6099     * below to the digitized value of the error limits - this has the net effect
6100     * of allowing (almost) +/-1 in the output value.  It's difficult to see how
6101     * any algorithm that digitizes intermediate results can be more accurate.
6102     */
6103    that->rede += 1./(2*((1U<<that->red_sBIT)-1));
6104
6105    if (that->colour_type & PNG_COLOR_MASK_COLOR)
6106    {
6107       that->green = sample_scale(that->greenf, scale);
6108       if (sig_bits && that->green_sBIT < that->sample_depth)
6109          that->green >>= that->sample_depth - that->green_sBIT;
6110
6111       that->blue = sample_scale(that->bluef, scale);
6112       if (sig_bits && that->blue_sBIT < that->sample_depth)
6113          that->blue >>= that->sample_depth - that->blue_sBIT;
6114
6115       that->greene += 1./(2*((1U<<that->green_sBIT)-1));
6116       that->bluee += 1./(2*((1U<<that->blue_sBIT)-1));
6117    }
6118    else
6119    {
6120       that->blue = that->green = that->red;
6121       that->bluef = that->greenf = that->redf;
6122       that->bluee = that->greene = that->rede;
6123    }
6124
6125    if ((that->colour_type & PNG_COLOR_MASK_ALPHA) ||
6126       that->colour_type == PNG_COLOR_TYPE_PALETTE)
6127    {
6128       that->alpha = sample_scale(that->alphaf, scale);
6129       that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1));
6130    }
6131    else
6132    {
6133       that->alpha = scale; /* opaque */
6134       that->alphaf = 1;    /* Override this. */
6135       that->alphae = 0;    /* It's exact ;-) */
6136    }
6137
6138    if (sig_bits && that->alpha_sBIT < that->sample_depth)
6139       that->alpha >>= that->sample_depth - that->alpha_sBIT;
6140 }
6141
6142 /* Static 'end' structure: */
6143 static image_transform image_transform_end =
6144 {
6145    "(end)", /* name */
6146    1, /* enable */
6147    0, /* list */
6148    0, /* global_use */
6149    0, /* local_use */
6150    0, /* next */
6151    image_transform_ini_end,
6152    image_transform_set_end,
6153    image_transform_mod_end,
6154    0 /* never called, I want it to crash if it is! */
6155 };
6156
6157 /* Reader callbacks and implementations, where they differ from the standard
6158  * ones.
6159  */
6160 static void
6161 transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id,
6162     const image_transform *transform_list)
6163 {
6164    memset(dp, 0, sizeof *dp);
6165
6166    /* Standard fields */
6167    standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
6168       pm->use_update_info);
6169
6170    /* Parameter fields */
6171    dp->pm = pm;
6172    dp->transform_list = transform_list;
6173    dp->max_gamma_8 = 16;
6174
6175    /* Local variable fields */
6176    dp->output_colour_type = 255; /* invalid */
6177    dp->output_bit_depth = 255;  /* invalid */
6178    dp->unpacked = 0; /* not unpacked */
6179 }
6180
6181 static void
6182 transform_info_imp(transform_display *dp, png_structp pp, png_infop pi)
6183 {
6184    /* Reuse the standard stuff as appropriate. */
6185    standard_info_part1(&dp->this, pp, pi);
6186
6187    /* Now set the list of transforms. */
6188    dp->transform_list->set(dp->transform_list, dp, pp, pi);
6189
6190    /* Update the info structure for these transforms: */
6191    {
6192       int i = dp->this.use_update_info;
6193       /* Always do one call, even if use_update_info is 0. */
6194       do
6195          png_read_update_info(pp, pi);
6196       while (--i > 0);
6197    }
6198
6199    /* And get the output information into the standard_display */
6200    standard_info_part2(&dp->this, pp, pi, 1/*images*/);
6201
6202    /* Plus the extra stuff we need for the transform tests: */
6203    dp->output_colour_type = png_get_color_type(pp, pi);
6204    dp->output_bit_depth = png_get_bit_depth(pp, pi);
6205
6206    /* If png_set_filler is in action then fake the output color type to include
6207     * an alpha channel where appropriate.
6208     */
6209    if (dp->output_bit_depth >= 8 &&
6210        (dp->output_colour_type == PNG_COLOR_TYPE_RGB ||
6211         dp->output_colour_type == PNG_COLOR_TYPE_GRAY) && dp->this.filler)
6212        dp->output_colour_type |= 4;
6213
6214    /* Validate the combination of colour type and bit depth that we are getting
6215     * out of libpng; the semantics of something not in the PNG spec are, at
6216     * best, unclear.
6217     */
6218    switch (dp->output_colour_type)
6219    {
6220    case PNG_COLOR_TYPE_PALETTE:
6221       if (dp->output_bit_depth > 8) goto error;
6222       /*FALL THROUGH*/
6223    case PNG_COLOR_TYPE_GRAY:
6224       if (dp->output_bit_depth == 1 || dp->output_bit_depth == 2 ||
6225          dp->output_bit_depth == 4)
6226          break;
6227       /*FALL THROUGH*/
6228    default:
6229       if (dp->output_bit_depth == 8 || dp->output_bit_depth == 16)
6230          break;
6231       /*FALL THROUGH*/
6232    error:
6233       {
6234          char message[128];
6235          size_t pos;
6236
6237          pos = safecat(message, sizeof message, 0,
6238             "invalid final bit depth: colour type(");
6239          pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
6240          pos = safecat(message, sizeof message, pos, ") with bit depth: ");
6241          pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
6242
6243          png_error(pp, message);
6244       }
6245    }
6246
6247    /* Use a test pixel to check that the output agrees with what we expect -
6248     * this avoids running the whole test if the output is unexpected.  This also
6249     * checks for internal errors.
6250     */
6251    {
6252       image_pixel test_pixel;
6253
6254       memset(&test_pixel, 0, sizeof test_pixel);
6255       test_pixel.colour_type = dp->this.colour_type; /* input */
6256       test_pixel.bit_depth = dp->this.bit_depth;
6257       if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
6258          test_pixel.sample_depth = 8;
6259       else
6260          test_pixel.sample_depth = test_pixel.bit_depth;
6261       /* Don't need sBIT here, but it must be set to non-zero to avoid
6262        * arithmetic overflows.
6263        */
6264       test_pixel.have_tRNS = dp->this.is_transparent != 0;
6265       test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT =
6266          test_pixel.alpha_sBIT = test_pixel.sample_depth;
6267
6268       dp->transform_list->mod(dp->transform_list, &test_pixel, pp, dp);
6269
6270       if (test_pixel.colour_type != dp->output_colour_type)
6271       {
6272          char message[128];
6273          size_t pos = safecat(message, sizeof message, 0, "colour type ");
6274
6275          pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
6276          pos = safecat(message, sizeof message, pos, " expected ");
6277          pos = safecatn(message, sizeof message, pos, test_pixel.colour_type);
6278
6279          png_error(pp, message);
6280       }
6281
6282       if (test_pixel.bit_depth != dp->output_bit_depth)
6283       {
6284          char message[128];
6285          size_t pos = safecat(message, sizeof message, 0, "bit depth ");
6286
6287          pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
6288          pos = safecat(message, sizeof message, pos, " expected ");
6289          pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
6290
6291          png_error(pp, message);
6292       }
6293
6294       /* If both bit depth and colour type are correct check the sample depth.
6295        */
6296       if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE &&
6297           test_pixel.sample_depth != 8) /* oops - internal error! */
6298          png_error(pp, "pngvalid: internal: palette sample depth not 8");
6299       else if (dp->unpacked && test_pixel.bit_depth != 8)
6300          png_error(pp, "pngvalid: internal: bad unpacked pixel depth");
6301       else if (!dp->unpacked && test_pixel.colour_type != PNG_COLOR_TYPE_PALETTE
6302               && test_pixel.bit_depth != test_pixel.sample_depth)
6303       {
6304          char message[128];
6305          size_t pos = safecat(message, sizeof message, 0,
6306             "internal: sample depth ");
6307
6308          /* Because unless something has set 'unpacked' or the image is palette
6309           * mapped we expect the transform to keep sample depth and bit depth
6310           * the same.
6311           */
6312          pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth);
6313          pos = safecat(message, sizeof message, pos, " expected ");
6314          pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
6315
6316          png_error(pp, message);
6317       }
6318       else if (test_pixel.bit_depth != dp->output_bit_depth)
6319       {
6320          /* This could be a libpng error too; libpng has not produced what we
6321           * expect for the output bit depth.
6322           */
6323          char message[128];
6324          size_t pos = safecat(message, sizeof message, 0,
6325             "internal: bit depth ");
6326
6327          pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
6328          pos = safecat(message, sizeof message, pos, " expected ");
6329          pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
6330
6331          png_error(pp, message);
6332       }
6333    }
6334 }
6335
6336 static void PNGCBAPI
6337 transform_info(png_structp pp, png_infop pi)
6338 {
6339    transform_info_imp(voidcast(transform_display*, png_get_progressive_ptr(pp)),
6340       pp, pi);
6341 }
6342
6343 static void
6344 transform_range_check(png_const_structp pp, unsigned int r, unsigned int g,
6345    unsigned int b, unsigned int a, unsigned int in_digitized, double in,
6346    unsigned int out, png_byte sample_depth, double err, double limit,
6347    const char *name, double digitization_error)
6348 {
6349    /* Compare the scaled, digitzed, values of our local calculation (in+-err)
6350     * with the digitized values libpng produced;  'sample_depth' is the actual
6351     * digitization depth of the libpng output colors (the bit depth except for
6352     * palette images where it is always 8.)  The check on 'err' is to detect
6353     * internal errors in pngvalid itself.
6354     */
6355    unsigned int max = (1U<<sample_depth)-1;
6356    double in_min = ceil((in-err)*max - digitization_error);
6357    double in_max = floor((in+err)*max + digitization_error);
6358    if (debugonly(err > limit ||) !(out >= in_min && out <= in_max))
6359    {
6360       char message[256];
6361       size_t pos;
6362
6363       pos = safecat(message, sizeof message, 0, name);
6364       pos = safecat(message, sizeof message, pos, " output value error: rgba(");
6365       pos = safecatn(message, sizeof message, pos, r);
6366       pos = safecat(message, sizeof message, pos, ",");
6367       pos = safecatn(message, sizeof message, pos, g);
6368       pos = safecat(message, sizeof message, pos, ",");
6369       pos = safecatn(message, sizeof message, pos, b);
6370       pos = safecat(message, sizeof message, pos, ",");
6371       pos = safecatn(message, sizeof message, pos, a);
6372       pos = safecat(message, sizeof message, pos, "): ");
6373       pos = safecatn(message, sizeof message, pos, out);
6374       pos = safecat(message, sizeof message, pos, " expected: ");
6375       pos = safecatn(message, sizeof message, pos, in_digitized);
6376       pos = safecat(message, sizeof message, pos, " (");
6377       pos = safecatd(message, sizeof message, pos, (in-err)*max, 3);
6378       pos = safecat(message, sizeof message, pos, "..");
6379       pos = safecatd(message, sizeof message, pos, (in+err)*max, 3);
6380       pos = safecat(message, sizeof message, pos, ")");
6381
6382       png_error(pp, message);
6383    }
6384
6385    UNUSED(limit)
6386 }
6387
6388 static void
6389 transform_image_validate(transform_display *dp, png_const_structp pp,
6390    png_infop pi)
6391 {
6392    /* Constants for the loop below: */
6393    const png_store* const ps = dp->this.ps;
6394    const png_byte in_ct = dp->this.colour_type;
6395    const png_byte in_bd = dp->this.bit_depth;
6396    const png_uint_32 w = dp->this.w;
6397    const png_uint_32 h = dp->this.h;
6398    const png_byte out_ct = dp->output_colour_type;
6399    const png_byte out_bd = dp->output_bit_depth;
6400    const png_byte sample_depth = (png_byte)(out_ct ==
6401       PNG_COLOR_TYPE_PALETTE ? 8 : out_bd);
6402    const png_byte red_sBIT = dp->this.red_sBIT;
6403    const png_byte green_sBIT = dp->this.green_sBIT;
6404    const png_byte blue_sBIT = dp->this.blue_sBIT;
6405    const png_byte alpha_sBIT = dp->this.alpha_sBIT;
6406    const int have_tRNS = dp->this.is_transparent;
6407    double digitization_error;
6408
6409    store_palette out_palette;
6410    png_uint_32 y;
6411
6412    UNUSED(pi)
6413
6414    /* Check for row overwrite errors */
6415    store_image_check(dp->this.ps, pp, 0);
6416
6417    /* Read the palette corresponding to the output if the output colour type
6418     * indicates a palette, othewise set out_palette to garbage.
6419     */
6420    if (out_ct == PNG_COLOR_TYPE_PALETTE)
6421    {
6422       /* Validate that the palette count itself has not changed - this is not
6423        * expected.
6424        */
6425       int npalette = (-1);
6426
6427       (void)read_palette(out_palette, &npalette, pp, pi);
6428       if (npalette != dp->this.npalette)
6429          png_error(pp, "unexpected change in palette size");
6430
6431       digitization_error = .5;
6432    }
6433    else
6434    {
6435       png_byte in_sample_depth;
6436
6437       memset(out_palette, 0x5e, sizeof out_palette);
6438
6439       /* use-input-precision means assume that if the input has 8 bit (or less)
6440        * samples and the output has 16 bit samples the calculations will be done
6441        * with 8 bit precision, not 16.
6442        */
6443       if (in_ct == PNG_COLOR_TYPE_PALETTE || in_bd < 16)
6444          in_sample_depth = 8;
6445       else
6446          in_sample_depth = in_bd;
6447
6448       if (sample_depth != 16 || in_sample_depth > 8 ||
6449          !dp->pm->calculations_use_input_precision)
6450          digitization_error = .5;
6451
6452       /* Else calculations are at 8 bit precision, and the output actually
6453        * consists of scaled 8-bit values, so scale .5 in 8 bits to the 16 bits:
6454        */
6455       else
6456          digitization_error = .5 * 257;
6457    }
6458
6459    for (y=0; y<h; ++y)
6460    {
6461       png_const_bytep const pRow = store_image_row(ps, pp, 0, y);
6462       png_uint_32 x;
6463
6464       /* The original, standard, row pre-transforms. */
6465       png_byte std[STANDARD_ROWMAX];
6466
6467       transform_row(pp, std, in_ct, in_bd, y);
6468
6469       /* Go through each original pixel transforming it and comparing with what
6470        * libpng did to the same pixel.
6471        */
6472       for (x=0; x<w; ++x)
6473       {
6474          image_pixel in_pixel, out_pixel;
6475          unsigned int r, g, b, a;
6476
6477          /* Find out what we think the pixel should be: */
6478          image_pixel_init(&in_pixel, std, in_ct, in_bd, x, dp->this.palette,
6479                  NULL);
6480
6481          in_pixel.red_sBIT = red_sBIT;
6482          in_pixel.green_sBIT = green_sBIT;
6483          in_pixel.blue_sBIT = blue_sBIT;
6484          in_pixel.alpha_sBIT = alpha_sBIT;
6485          in_pixel.have_tRNS = have_tRNS != 0;
6486
6487          /* For error detection, below. */
6488          r = in_pixel.red;
6489          g = in_pixel.green;
6490          b = in_pixel.blue;
6491          a = in_pixel.alpha;
6492
6493          /* This applies the transforms to the input data, including output
6494           * format operations which must be used when reading the output
6495           * pixel that libpng produces.
6496           */
6497          dp->transform_list->mod(dp->transform_list, &in_pixel, pp, dp);
6498
6499          /* Read the output pixel and compare it to what we got, we don't
6500           * use the error field here, so no need to update sBIT.  in_pixel
6501           * says whether we expect libpng to change the output format.
6502           */
6503          image_pixel_init(&out_pixel, pRow, out_ct, out_bd, x, out_palette,
6504                  &in_pixel);
6505
6506          /* We don't expect changes to the index here even if the bit depth is
6507           * changed.
6508           */
6509          if (in_ct == PNG_COLOR_TYPE_PALETTE &&
6510             out_ct == PNG_COLOR_TYPE_PALETTE)
6511          {
6512             if (in_pixel.palette_index != out_pixel.palette_index)
6513                png_error(pp, "unexpected transformed palette index");
6514          }
6515
6516          /* Check the colours for palette images too - in fact the palette could
6517           * be separately verified itself in most cases.
6518           */
6519          if (in_pixel.red != out_pixel.red)
6520             transform_range_check(pp, r, g, b, a, in_pixel.red, in_pixel.redf,
6521                out_pixel.red, sample_depth, in_pixel.rede,
6522                dp->pm->limit + 1./(2*((1U<<in_pixel.red_sBIT)-1)), "red/gray",
6523                digitization_error);
6524
6525          if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
6526             in_pixel.green != out_pixel.green)
6527             transform_range_check(pp, r, g, b, a, in_pixel.green,
6528                in_pixel.greenf, out_pixel.green, sample_depth, in_pixel.greene,
6529                dp->pm->limit + 1./(2*((1U<<in_pixel.green_sBIT)-1)), "green",
6530                digitization_error);
6531
6532          if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
6533             in_pixel.blue != out_pixel.blue)
6534             transform_range_check(pp, r, g, b, a, in_pixel.blue, in_pixel.bluef,
6535                out_pixel.blue, sample_depth, in_pixel.bluee,
6536                dp->pm->limit + 1./(2*((1U<<in_pixel.blue_sBIT)-1)), "blue",
6537                digitization_error);
6538
6539          if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0 &&
6540             in_pixel.alpha != out_pixel.alpha)
6541             transform_range_check(pp, r, g, b, a, in_pixel.alpha,
6542                in_pixel.alphaf, out_pixel.alpha, sample_depth, in_pixel.alphae,
6543                dp->pm->limit + 1./(2*((1U<<in_pixel.alpha_sBIT)-1)), "alpha",
6544                digitization_error);
6545       } /* pixel (x) loop */
6546    } /* row (y) loop */
6547
6548    /* Record that something was actually checked to avoid a false positive. */
6549    dp->this.ps->validated = 1;
6550 }
6551
6552 static void PNGCBAPI
6553 transform_end(png_structp ppIn, png_infop pi)
6554 {
6555    png_const_structp pp = ppIn;
6556    transform_display *dp = voidcast(transform_display*,
6557       png_get_progressive_ptr(pp));
6558
6559    if (!dp->this.speed)
6560       transform_image_validate(dp, pp, pi);
6561    else
6562       dp->this.ps->validated = 1;
6563 }
6564
6565 /* A single test run. */
6566 static void
6567 transform_test(png_modifier *pmIn, const png_uint_32 idIn,
6568     const image_transform* transform_listIn, const char * const name)
6569 {
6570    transform_display d;
6571    context(&pmIn->this, fault);
6572
6573    transform_display_init(&d, pmIn, idIn, transform_listIn);
6574
6575    Try
6576    {
6577       size_t pos = 0;
6578       png_structp pp;
6579       png_infop pi;
6580       char full_name[256];
6581
6582       /* Make sure the encoding fields are correct and enter the required
6583        * modifications.
6584        */
6585       transform_set_encoding(&d);
6586
6587       /* Add any modifications required by the transform list. */
6588       d.transform_list->ini(d.transform_list, &d);
6589
6590       /* Add the color space information, if any, to the name. */
6591       pos = safecat(full_name, sizeof full_name, pos, name);
6592       pos = safecat_current_encoding(full_name, sizeof full_name, pos, d.pm);
6593
6594       /* Get a png_struct for reading the image. */
6595       pp = set_modifier_for_read(d.pm, &pi, d.this.id, full_name);
6596       standard_palette_init(&d.this);
6597
6598 #     if 0
6599          /* Logging (debugging only) */
6600          {
6601             char buffer[256];
6602
6603             (void)store_message(&d.pm->this, pp, buffer, sizeof buffer, 0,
6604                "running test");
6605
6606             fprintf(stderr, "%s\n", buffer);
6607          }
6608 #     endif
6609
6610       /* Introduce the correct read function. */
6611       if (d.pm->this.progressive)
6612       {
6613          /* Share the row function with the standard implementation. */
6614          png_set_progressive_read_fn(pp, &d, transform_info, progressive_row,
6615             transform_end);
6616
6617          /* Now feed data into the reader until we reach the end: */
6618          modifier_progressive_read(d.pm, pp, pi);
6619       }
6620       else
6621       {
6622          /* modifier_read expects a png_modifier* */
6623          png_set_read_fn(pp, d.pm, modifier_read);
6624
6625          /* Check the header values: */
6626          png_read_info(pp, pi);
6627
6628          /* Process the 'info' requirements. Only one image is generated */
6629          transform_info_imp(&d, pp, pi);
6630
6631          sequential_row(&d.this, pp, pi, -1, 0);
6632
6633          if (!d.this.speed)
6634             transform_image_validate(&d, pp, pi);
6635          else
6636             d.this.ps->validated = 1;
6637       }
6638
6639       modifier_reset(d.pm);
6640    }
6641
6642    Catch(fault)
6643    {
6644       modifier_reset(voidcast(png_modifier*,(void*)fault));
6645    }
6646 }
6647
6648 /* The transforms: */
6649 #define ITSTRUCT(name) image_transform_##name
6650 #define ITDATA(name) image_transform_data_##name
6651 #define image_transform_ini image_transform_default_ini
6652 #define IT(name)\
6653 static image_transform ITSTRUCT(name) =\
6654 {\
6655    #name,\
6656    1, /*enable*/\
6657    &PT, /*list*/\
6658    0, /*global_use*/\
6659    0, /*local_use*/\
6660    0, /*next*/\
6661    image_transform_ini,\
6662    image_transform_png_set_##name##_set,\
6663    image_transform_png_set_##name##_mod,\
6664    image_transform_png_set_##name##_add\
6665 }
6666 #define PT ITSTRUCT(end) /* stores the previous transform */
6667
6668 /* To save code: */
6669 extern void image_transform_default_ini(const image_transform *this,
6670    transform_display *that); /* silence GCC warnings */
6671
6672 void /* private, but almost always needed */
6673 image_transform_default_ini(const image_transform *this,
6674     transform_display *that)
6675 {
6676    this->next->ini(this->next, that);
6677 }
6678
6679 #ifdef PNG_READ_BACKGROUND_SUPPORTED
6680 static int
6681 image_transform_default_add(image_transform *this,
6682     const image_transform **that, png_byte colour_type, png_byte bit_depth)
6683 {
6684    UNUSED(colour_type)
6685    UNUSED(bit_depth)
6686
6687    this->next = *that;
6688    *that = this;
6689
6690    return 1;
6691 }
6692 #endif
6693
6694 #ifdef PNG_READ_EXPAND_SUPPORTED
6695 /* png_set_palette_to_rgb */
6696 static void
6697 image_transform_png_set_palette_to_rgb_set(const image_transform *this,
6698     transform_display *that, png_structp pp, png_infop pi)
6699 {
6700    png_set_palette_to_rgb(pp);
6701    this->next->set(this->next, that, pp, pi);
6702 }
6703
6704 static void
6705 image_transform_png_set_palette_to_rgb_mod(const image_transform *this,
6706     image_pixel *that, png_const_structp pp,
6707     const transform_display *display)
6708 {
6709    if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
6710       image_pixel_convert_PLTE(that);
6711
6712    this->next->mod(this->next, that, pp, display);
6713 }
6714
6715 static int
6716 image_transform_png_set_palette_to_rgb_add(image_transform *this,
6717     const image_transform **that, png_byte colour_type, png_byte bit_depth)
6718 {
6719    UNUSED(bit_depth)
6720
6721    this->next = *that;
6722    *that = this;
6723
6724    return colour_type == PNG_COLOR_TYPE_PALETTE;
6725 }
6726
6727 IT(palette_to_rgb);
6728 #undef PT
6729 #define PT ITSTRUCT(palette_to_rgb)
6730 #endif /* PNG_READ_EXPAND_SUPPORTED */
6731
6732 #ifdef PNG_READ_EXPAND_SUPPORTED
6733 /* png_set_tRNS_to_alpha */
6734 static void
6735 image_transform_png_set_tRNS_to_alpha_set(const image_transform *this,
6736    transform_display *that, png_structp pp, png_infop pi)
6737 {
6738    png_set_tRNS_to_alpha(pp);
6739
6740    /* If there was a tRNS chunk that would get expanded and add an alpha
6741     * channel is_transparent must be updated:
6742     */
6743    if (that->this.has_tRNS)
6744       that->this.is_transparent = 1;
6745
6746    this->next->set(this->next, that, pp, pi);
6747 }
6748
6749 static void
6750 image_transform_png_set_tRNS_to_alpha_mod(const image_transform *this,
6751    image_pixel *that, png_const_structp pp,
6752    const transform_display *display)
6753 {
6754 #if PNG_LIBPNG_VER < 10700
6755    /* LIBPNG BUG: this always forces palette images to RGB. */
6756    if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
6757       image_pixel_convert_PLTE(that);
6758 #endif
6759
6760    /* This effectively does an 'expand' only if there is some transparency to
6761     * convert to an alpha channel.
6762     */
6763    if (that->have_tRNS)
6764 #     if PNG_LIBPNG_VER >= 10700
6765          if (that->colour_type != PNG_COLOR_TYPE_PALETTE &&
6766              (that->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
6767 #     endif
6768       image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
6769
6770 #if PNG_LIBPNG_VER < 10700
6771    /* LIBPNG BUG: otherwise libpng still expands to 8 bits! */
6772    else
6773    {
6774       if (that->bit_depth < 8)
6775          that->bit_depth =8;
6776       if (that->sample_depth < 8)
6777          that->sample_depth = 8;
6778    }
6779 #endif
6780
6781    this->next->mod(this->next, that, pp, display);
6782 }
6783
6784 static int
6785 image_transform_png_set_tRNS_to_alpha_add(image_transform *this,
6786     const image_transform **that, png_byte colour_type, png_byte bit_depth)
6787 {
6788    UNUSED(bit_depth)
6789
6790    this->next = *that;
6791    *that = this;
6792
6793    /* We don't know yet whether there will be a tRNS chunk, but we know that
6794     * this transformation should do nothing if there already is an alpha
6795     * channel.  In addition, after the bug fix in 1.7.0, there is no longer
6796     * any action on a palette image.
6797     */
6798    return
6799 #  if PNG_LIBPNG_VER >= 10700
6800       colour_type != PNG_COLOR_TYPE_PALETTE &&
6801 #  endif
6802    (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
6803 }
6804
6805 IT(tRNS_to_alpha);
6806 #undef PT
6807 #define PT ITSTRUCT(tRNS_to_alpha)
6808 #endif /* PNG_READ_EXPAND_SUPPORTED */
6809
6810 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
6811 /* png_set_gray_to_rgb */
6812 static void
6813 image_transform_png_set_gray_to_rgb_set(const image_transform *this,
6814     transform_display *that, png_structp pp, png_infop pi)
6815 {
6816    png_set_gray_to_rgb(pp);
6817    /* NOTE: this doesn't result in tRNS expansion. */
6818    this->next->set(this->next, that, pp, pi);
6819 }
6820
6821 static void
6822 image_transform_png_set_gray_to_rgb_mod(const image_transform *this,
6823     image_pixel *that, png_const_structp pp,
6824     const transform_display *display)
6825 {
6826    /* NOTE: we can actually pend the tRNS processing at this point because we
6827     * can correctly recognize the original pixel value even though we have
6828     * mapped the one gray channel to the three RGB ones, but in fact libpng
6829     * doesn't do this, so we don't either.
6830     */
6831    if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS)
6832       image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
6833
6834    /* Simply expand the bit depth and alter the colour type as required. */
6835    if (that->colour_type == PNG_COLOR_TYPE_GRAY)
6836    {
6837       /* RGB images have a bit depth at least equal to '8' */
6838       if (that->bit_depth < 8)
6839          that->sample_depth = that->bit_depth = 8;
6840
6841       /* And just changing the colour type works here because the green and blue
6842        * channels are being maintained in lock-step with the red/gray:
6843        */
6844       that->colour_type = PNG_COLOR_TYPE_RGB;
6845    }
6846
6847    else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6848       that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
6849
6850    this->next->mod(this->next, that, pp, display);
6851 }
6852
6853 static int
6854 image_transform_png_set_gray_to_rgb_add(image_transform *this,
6855     const image_transform **that, png_byte colour_type, png_byte bit_depth)
6856 {
6857    UNUSED(bit_depth)
6858
6859    this->next = *that;
6860    *that = this;
6861
6862    return (colour_type & PNG_COLOR_MASK_COLOR) == 0;
6863 }
6864
6865 IT(gray_to_rgb);
6866 #undef PT
6867 #define PT ITSTRUCT(gray_to_rgb)
6868 #endif /* PNG_READ_GRAY_TO_RGB_SUPPORTED */
6869
6870 #ifdef PNG_READ_EXPAND_SUPPORTED
6871 /* png_set_expand */
6872 static void
6873 image_transform_png_set_expand_set(const image_transform *this,
6874     transform_display *that, png_structp pp, png_infop pi)
6875 {
6876    png_set_expand(pp);
6877
6878    if (that->this.has_tRNS)
6879       that->this.is_transparent = 1;
6880
6881    this->next->set(this->next, that, pp, pi);
6882 }
6883
6884 static void
6885 image_transform_png_set_expand_mod(const image_transform *this,
6886     image_pixel *that, png_const_structp pp,
6887     const transform_display *display)
6888 {
6889    /* The general expand case depends on what the colour type is: */
6890    if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
6891       image_pixel_convert_PLTE(that);
6892    else if (that->bit_depth < 8) /* grayscale */
6893       that->sample_depth = that->bit_depth = 8;
6894
6895    if (that->have_tRNS)
6896       image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
6897
6898    this->next->mod(this->next, that, pp, display);
6899 }
6900
6901 static int
6902 image_transform_png_set_expand_add(image_transform *this,
6903     const image_transform **that, png_byte colour_type, png_byte bit_depth)
6904 {
6905    UNUSED(bit_depth)
6906
6907    this->next = *that;
6908    *that = this;
6909
6910    /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit
6911     * depth is at least 8 already.
6912     */
6913    return (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
6914 }
6915
6916 IT(expand);
6917 #undef PT
6918 #define PT ITSTRUCT(expand)
6919 #endif /* PNG_READ_EXPAND_SUPPORTED */
6920
6921 #ifdef PNG_READ_EXPAND_SUPPORTED
6922 /* png_set_expand_gray_1_2_4_to_8
6923  * Pre 1.7.0 LIBPNG BUG: this just does an 'expand'
6924  */
6925 static void
6926 image_transform_png_set_expand_gray_1_2_4_to_8_set(
6927     const image_transform *this, transform_display *that, png_structp pp,
6928     png_infop pi)
6929 {
6930    png_set_expand_gray_1_2_4_to_8(pp);
6931    /* NOTE: don't expect this to expand tRNS */
6932    this->next->set(this->next, that, pp, pi);
6933 }
6934
6935 static void
6936 image_transform_png_set_expand_gray_1_2_4_to_8_mod(
6937     const image_transform *this, image_pixel *that, png_const_structp pp,
6938     const transform_display *display)
6939 {
6940 #if PNG_LIBPNG_VER < 10700
6941    image_transform_png_set_expand_mod(this, that, pp, display);
6942 #else
6943    /* Only expand grayscale of bit depth less than 8: */
6944    if (that->colour_type == PNG_COLOR_TYPE_GRAY &&
6945        that->bit_depth < 8)
6946       that->sample_depth = that->bit_depth = 8;
6947
6948    this->next->mod(this->next, that, pp, display);
6949 #endif /* 1.7 or later */
6950 }
6951
6952 static int
6953 image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this,
6954     const image_transform **that, png_byte colour_type, png_byte bit_depth)
6955 {
6956 #if PNG_LIBPNG_VER < 10700
6957    return image_transform_png_set_expand_add(this, that, colour_type,
6958       bit_depth);
6959 #else
6960    UNUSED(bit_depth)
6961
6962    this->next = *that;
6963    *that = this;
6964
6965    /* This should do nothing unless the color type is gray and the bit depth is
6966     * less than 8:
6967     */
6968    return colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8;
6969 #endif /* 1.7 or later */
6970 }
6971
6972 IT(expand_gray_1_2_4_to_8);
6973 #undef PT
6974 #define PT ITSTRUCT(expand_gray_1_2_4_to_8)
6975 #endif /* PNG_READ_EXPAND_SUPPORTED */
6976
6977 #ifdef PNG_READ_EXPAND_16_SUPPORTED
6978 /* png_set_expand_16 */
6979 static void
6980 image_transform_png_set_expand_16_set(const image_transform *this,
6981     transform_display *that, png_structp pp, png_infop pi)
6982 {
6983    png_set_expand_16(pp);
6984
6985    /* NOTE: prior to 1.7 libpng does SET_EXPAND as well, so tRNS is expanded. */
6986 #  if PNG_LIBPNG_VER < 10700
6987       if (that->this.has_tRNS)
6988          that->this.is_transparent = 1;
6989 #  endif
6990
6991    this->next->set(this->next, that, pp, pi);
6992 }
6993
6994 static void
6995 image_transform_png_set_expand_16_mod(const image_transform *this,
6996     image_pixel *that, png_const_structp pp,
6997     const transform_display *display)
6998 {
6999    /* Expect expand_16 to expand everything to 16 bits as a result of also
7000     * causing 'expand' to happen.
7001     */
7002    if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
7003       image_pixel_convert_PLTE(that);
7004
7005    if (that->have_tRNS)
7006       image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
7007
7008    if (that->bit_depth < 16)
7009       that->sample_depth = that->bit_depth = 16;
7010
7011    this->next->mod(this->next, that, pp, display);
7012 }
7013
7014 static int
7015 image_transform_png_set_expand_16_add(image_transform *this,
7016     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7017 {
7018    UNUSED(colour_type)
7019
7020    this->next = *that;
7021    *that = this;
7022
7023    /* expand_16 does something unless the bit depth is already 16. */
7024    return bit_depth < 16;
7025 }
7026
7027 IT(expand_16);
7028 #undef PT
7029 #define PT ITSTRUCT(expand_16)
7030 #endif /* PNG_READ_EXPAND_16_SUPPORTED */
7031
7032 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED  /* API added in 1.5.4 */
7033 /* png_set_scale_16 */
7034 static void
7035 image_transform_png_set_scale_16_set(const image_transform *this,
7036     transform_display *that, png_structp pp, png_infop pi)
7037 {
7038    png_set_scale_16(pp);
7039 #  if PNG_LIBPNG_VER < 10700
7040       /* libpng will limit the gamma table size: */
7041       that->max_gamma_8 = PNG_MAX_GAMMA_8;
7042 #  endif
7043    this->next->set(this->next, that, pp, pi);
7044 }
7045
7046 static void
7047 image_transform_png_set_scale_16_mod(const image_transform *this,
7048     image_pixel *that, png_const_structp pp,
7049     const transform_display *display)
7050 {
7051    if (that->bit_depth == 16)
7052    {
7053       that->sample_depth = that->bit_depth = 8;
7054       if (that->red_sBIT > 8) that->red_sBIT = 8;
7055       if (that->green_sBIT > 8) that->green_sBIT = 8;
7056       if (that->blue_sBIT > 8) that->blue_sBIT = 8;
7057       if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
7058    }
7059
7060    this->next->mod(this->next, that, pp, display);
7061 }
7062
7063 static int
7064 image_transform_png_set_scale_16_add(image_transform *this,
7065     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7066 {
7067    UNUSED(colour_type)
7068
7069    this->next = *that;
7070    *that = this;
7071
7072    return bit_depth > 8;
7073 }
7074
7075 IT(scale_16);
7076 #undef PT
7077 #define PT ITSTRUCT(scale_16)
7078 #endif /* PNG_READ_SCALE_16_TO_8_SUPPORTED (1.5.4 on) */
7079
7080 #ifdef PNG_READ_16_TO_8_SUPPORTED /* the default before 1.5.4 */
7081 /* png_set_strip_16 */
7082 static void
7083 image_transform_png_set_strip_16_set(const image_transform *this,
7084     transform_display *that, png_structp pp, png_infop pi)
7085 {
7086    png_set_strip_16(pp);
7087 #  if PNG_LIBPNG_VER < 10700
7088       /* libpng will limit the gamma table size: */
7089       that->max_gamma_8 = PNG_MAX_GAMMA_8;
7090 #  endif
7091    this->next->set(this->next, that, pp, pi);
7092 }
7093
7094 static void
7095 image_transform_png_set_strip_16_mod(const image_transform *this,
7096     image_pixel *that, png_const_structp pp,
7097     const transform_display *display)
7098 {
7099    if (that->bit_depth == 16)
7100    {
7101       that->sample_depth = that->bit_depth = 8;
7102       if (that->red_sBIT > 8) that->red_sBIT = 8;
7103       if (that->green_sBIT > 8) that->green_sBIT = 8;
7104       if (that->blue_sBIT > 8) that->blue_sBIT = 8;
7105       if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
7106
7107       /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
7108        * configuration option is set.  From 1.5.4 the flag is never set and the
7109        * 'scale' API (above) must be used.
7110        */
7111 #     ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
7112 #        if PNG_LIBPNG_VER >= 10504
7113 #           error PNG_READ_ACCURATE_SCALE should not be set
7114 #        endif
7115
7116          /* The strip 16 algorithm drops the low 8 bits rather than calculating
7117           * 1/257, so we need to adjust the permitted errors appropriately:
7118           * Notice that this is only relevant prior to the addition of the
7119           * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
7120           */
7121          {
7122             const double d = (255-128.5)/65535;
7123             that->rede += d;
7124             that->greene += d;
7125             that->bluee += d;
7126             that->alphae += d;
7127          }
7128 #     endif
7129    }
7130
7131    this->next->mod(this->next, that, pp, display);
7132 }
7133
7134 static int
7135 image_transform_png_set_strip_16_add(image_transform *this,
7136     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7137 {
7138    UNUSED(colour_type)
7139
7140    this->next = *that;
7141    *that = this;
7142
7143    return bit_depth > 8;
7144 }
7145
7146 IT(strip_16);
7147 #undef PT
7148 #define PT ITSTRUCT(strip_16)
7149 #endif /* PNG_READ_16_TO_8_SUPPORTED */
7150
7151 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
7152 /* png_set_strip_alpha */
7153 static void
7154 image_transform_png_set_strip_alpha_set(const image_transform *this,
7155     transform_display *that, png_structp pp, png_infop pi)
7156 {
7157    png_set_strip_alpha(pp);
7158    this->next->set(this->next, that, pp, pi);
7159 }
7160
7161 static void
7162 image_transform_png_set_strip_alpha_mod(const image_transform *this,
7163     image_pixel *that, png_const_structp pp,
7164     const transform_display *display)
7165 {
7166    if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
7167       that->colour_type = PNG_COLOR_TYPE_GRAY;
7168    else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
7169       that->colour_type = PNG_COLOR_TYPE_RGB;
7170
7171    that->have_tRNS = 0;
7172    that->alphaf = 1;
7173
7174    this->next->mod(this->next, that, pp, display);
7175 }
7176
7177 static int
7178 image_transform_png_set_strip_alpha_add(image_transform *this,
7179     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7180 {
7181    UNUSED(bit_depth)
7182
7183    this->next = *that;
7184    *that = this;
7185
7186    return (colour_type & PNG_COLOR_MASK_ALPHA) != 0;
7187 }
7188
7189 IT(strip_alpha);
7190 #undef PT
7191 #define PT ITSTRUCT(strip_alpha)
7192 #endif /* PNG_READ_STRIP_ALPHA_SUPPORTED */
7193
7194 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
7195 /* png_set_rgb_to_gray(png_structp, int err_action, double red, double green)
7196  * png_set_rgb_to_gray_fixed(png_structp, int err_action, png_fixed_point red,
7197  *    png_fixed_point green)
7198  * png_get_rgb_to_gray_status
7199  *
7200  * The 'default' test here uses values known to be used inside libpng prior to
7201  * 1.7.0:
7202  *
7203  *   red:    6968
7204  *   green: 23434
7205  *   blue:   2366
7206  *
7207  * These values are being retained for compatibility, along with the somewhat
7208  * broken truncation calculation in the fast-and-inaccurate code path.  Older
7209  * versions of libpng will fail the accuracy tests below because they use the
7210  * truncation algorithm everywhere.
7211  */
7212 #define data ITDATA(rgb_to_gray)
7213 static struct
7214 {
7215    double gamma;      /* File gamma to use in processing */
7216
7217    /* The following are the parameters for png_set_rgb_to_gray: */
7218 #  ifdef PNG_FLOATING_POINT_SUPPORTED
7219       double red_to_set;
7220       double green_to_set;
7221 #  else
7222       png_fixed_point red_to_set;
7223       png_fixed_point green_to_set;
7224 #  endif
7225
7226    /* The actual coefficients: */
7227    double red_coefficient;
7228    double green_coefficient;
7229    double blue_coefficient;
7230
7231    /* Set if the coeefficients have been overridden. */
7232    int coefficients_overridden;
7233 } data;
7234
7235 #undef image_transform_ini
7236 #define image_transform_ini image_transform_png_set_rgb_to_gray_ini
7237 static void
7238 image_transform_png_set_rgb_to_gray_ini(const image_transform *this,
7239     transform_display *that)
7240 {
7241    png_modifier *pm = that->pm;
7242    const color_encoding *e = pm->current_encoding;
7243
7244    UNUSED(this)
7245
7246    /* Since we check the encoding this flag must be set: */
7247    pm->test_uses_encoding = 1;
7248
7249    /* If 'e' is not NULL chromaticity information is present and either a cHRM
7250     * or an sRGB chunk will be inserted.
7251     */
7252    if (e != 0)
7253    {
7254       /* Coefficients come from the encoding, but may need to be normalized to a
7255        * white point Y of 1.0
7256        */
7257       const double whiteY = e->red.Y + e->green.Y + e->blue.Y;
7258
7259       data.red_coefficient = e->red.Y;
7260       data.green_coefficient = e->green.Y;
7261       data.blue_coefficient = e->blue.Y;
7262
7263       if (whiteY != 1)
7264       {
7265          data.red_coefficient /= whiteY;
7266          data.green_coefficient /= whiteY;
7267          data.blue_coefficient /= whiteY;
7268       }
7269    }
7270
7271    else
7272    {
7273       /* The default (built in) coeffcients, as above: */
7274 #     if PNG_LIBPNG_VER < 10700
7275          data.red_coefficient = 6968 / 32768.;
7276          data.green_coefficient = 23434 / 32768.;
7277          data.blue_coefficient = 2366 / 32768.;
7278 #     else
7279          data.red_coefficient = .2126;
7280          data.green_coefficient = .7152;
7281          data.blue_coefficient = .0722;
7282 #     endif
7283    }
7284
7285    data.gamma = pm->current_gamma;
7286
7287    /* If not set then the calculations assume linear encoding (implicitly): */
7288    if (data.gamma == 0)
7289       data.gamma = 1;
7290
7291    /* The arguments to png_set_rgb_to_gray can override the coefficients implied
7292     * by the color space encoding.  If doing exhaustive checks do the override
7293     * in each case, otherwise do it randomly.
7294     */
7295    if (pm->test_exhaustive)
7296    {
7297       /* First time in coefficients_overridden is 0, the following sets it to 1,
7298        * so repeat if it is set.  If a test fails this may mean we subsequently
7299        * skip a non-override test, ignore that.
7300        */
7301       data.coefficients_overridden = !data.coefficients_overridden;
7302       pm->repeat = data.coefficients_overridden != 0;
7303    }
7304
7305    else
7306       data.coefficients_overridden = random_choice();
7307
7308    if (data.coefficients_overridden)
7309    {
7310       /* These values override the color encoding defaults, simply use random
7311        * numbers.
7312        */
7313       png_uint_32 ru;
7314       double total;
7315
7316       R32(ru);
7317       data.green_coefficient = total = (ru & 0xffff) / 65535.;
7318       ru >>= 16;
7319       data.red_coefficient = (1 - total) * (ru & 0xffff) / 65535.;
7320       total += data.red_coefficient;
7321       data.blue_coefficient = 1 - total;
7322
7323 #     ifdef PNG_FLOATING_POINT_SUPPORTED
7324          data.red_to_set = data.red_coefficient;
7325          data.green_to_set = data.green_coefficient;
7326 #     else
7327          data.red_to_set = fix(data.red_coefficient);
7328          data.green_to_set = fix(data.green_coefficient);
7329 #     endif
7330
7331       /* The following just changes the error messages: */
7332       pm->encoding_ignored = 1;
7333    }
7334
7335    else
7336    {
7337       data.red_to_set = -1;
7338       data.green_to_set = -1;
7339    }
7340
7341    /* Adjust the error limit in the png_modifier because of the larger errors
7342     * produced in the digitization during the gamma handling.
7343     */
7344    if (data.gamma != 1) /* Use gamma tables */
7345    {
7346       if (that->this.bit_depth == 16 || pm->assume_16_bit_calculations)
7347       {
7348          /* The computations have the form:
7349           *
7350           *    r * rc + g * gc + b * bc
7351           *
7352           *  Each component of which is +/-1/65535 from the gamma_to_1 table
7353           *  lookup, resulting in a base error of +/-6.  The gamma_from_1
7354           *  conversion adds another +/-2 in the 16-bit case and
7355           *  +/-(1<<(15-PNG_MAX_GAMMA_8)) in the 8-bit case.
7356           */
7357 #        if PNG_LIBPNG_VER < 10700
7358             if (that->this.bit_depth < 16)
7359                that->max_gamma_8 = PNG_MAX_GAMMA_8;
7360 #        endif
7361          that->pm->limit += pow(
7362             (that->this.bit_depth == 16 || that->max_gamma_8 > 14 ?
7363                8. :
7364                6. + (1<<(15-that->max_gamma_8))
7365             )/65535, data.gamma);
7366       }
7367
7368       else
7369       {
7370          /* Rounding to 8 bits in the linear space causes massive errors which
7371           * will trigger the error check in transform_range_check.  Fix that
7372           * here by taking the gamma encoding into account.
7373           *
7374           * When DIGITIZE is set because a pre-1.7 version of libpng is being
7375           * tested allow a bigger slack.
7376           *
7377           * NOTE: this number only affects the internal limit check in pngvalid,
7378           * it has no effect on the limits applied to the libpng values.
7379           */
7380          that->pm->limit += pow(
7381 #        if DIGITIZE
7382             2.0
7383 #        else
7384             1.0
7385 #        endif
7386             /255, data.gamma);
7387       }
7388    }
7389
7390    else
7391    {
7392       /* With no gamma correction a large error comes from the truncation of the
7393        * calculation in the 8 bit case, allow for that here.
7394        */
7395       if (that->this.bit_depth != 16 && !pm->assume_16_bit_calculations)
7396          that->pm->limit += 4E-3;
7397    }
7398 }
7399
7400 static void
7401 image_transform_png_set_rgb_to_gray_set(const image_transform *this,
7402     transform_display *that, png_structp pp, png_infop pi)
7403 {
7404    const int error_action = 1; /* no error, no defines in png.h */
7405
7406 #  ifdef PNG_FLOATING_POINT_SUPPORTED
7407       png_set_rgb_to_gray(pp, error_action, data.red_to_set, data.green_to_set);
7408 #  else
7409       png_set_rgb_to_gray_fixed(pp, error_action, data.red_to_set,
7410          data.green_to_set);
7411 #  endif
7412
7413 #  ifdef PNG_READ_cHRM_SUPPORTED
7414       if (that->pm->current_encoding != 0)
7415       {
7416          /* We have an encoding so a cHRM chunk may have been set; if so then
7417           * check that the libpng APIs give the correct (X,Y,Z) values within
7418           * some margin of error for the round trip through the chromaticity
7419           * form.
7420           */
7421 #        ifdef PNG_FLOATING_POINT_SUPPORTED
7422 #           define API_function png_get_cHRM_XYZ
7423 #           define API_form "FP"
7424 #           define API_type double
7425 #           define API_cvt(x) (x)
7426 #        else
7427 #           define API_function png_get_cHRM_XYZ_fixed
7428 #           define API_form "fixed"
7429 #           define API_type png_fixed_point
7430 #           define API_cvt(x) ((double)(x)/PNG_FP_1)
7431 #        endif
7432
7433          API_type rX, gX, bX;
7434          API_type rY, gY, bY;
7435          API_type rZ, gZ, bZ;
7436
7437          if ((API_function(pp, pi, &rX, &rY, &rZ, &gX, &gY, &gZ, &bX, &bY, &bZ)
7438                & PNG_INFO_cHRM) != 0)
7439          {
7440             double maxe;
7441             const char *el;
7442             color_encoding e, o;
7443
7444             /* Expect libpng to return a normalized result, but the original
7445              * color space encoding may not be normalized.
7446              */
7447             modifier_current_encoding(that->pm, &o);
7448             normalize_color_encoding(&o);
7449
7450             /* Sanity check the pngvalid code - the coefficients should match
7451              * the normalized Y values of the encoding unless they were
7452              * overridden.
7453              */
7454             if (data.red_to_set == -1 && data.green_to_set == -1 &&
7455                (fabs(o.red.Y - data.red_coefficient) > DBL_EPSILON ||
7456                fabs(o.green.Y - data.green_coefficient) > DBL_EPSILON ||
7457                fabs(o.blue.Y - data.blue_coefficient) > DBL_EPSILON))
7458                png_error(pp, "internal pngvalid cHRM coefficient error");
7459
7460             /* Generate a colour space encoding. */
7461             e.gamma = o.gamma; /* not used */
7462             e.red.X = API_cvt(rX);
7463             e.red.Y = API_cvt(rY);
7464             e.red.Z = API_cvt(rZ);
7465             e.green.X = API_cvt(gX);
7466             e.green.Y = API_cvt(gY);
7467             e.green.Z = API_cvt(gZ);
7468             e.blue.X = API_cvt(bX);
7469             e.blue.Y = API_cvt(bY);
7470             e.blue.Z = API_cvt(bZ);
7471
7472             /* This should match the original one from the png_modifier, within
7473              * the range permitted by the libpng fixed point representation.
7474              */
7475             maxe = 0;
7476             el = "-"; /* Set to element name with error */
7477
7478 #           define CHECK(col,x)\
7479             {\
7480                double err = fabs(o.col.x - e.col.x);\
7481                if (err > maxe)\
7482                {\
7483                   maxe = err;\
7484                   el = #col "(" #x ")";\
7485                }\
7486             }
7487
7488             CHECK(red,X)
7489             CHECK(red,Y)
7490             CHECK(red,Z)
7491             CHECK(green,X)
7492             CHECK(green,Y)
7493             CHECK(green,Z)
7494             CHECK(blue,X)
7495             CHECK(blue,Y)
7496             CHECK(blue,Z)
7497
7498             /* Here in both fixed and floating cases to check the values read
7499              * from the cHRm chunk.  PNG uses fixed point in the cHRM chunk, so
7500              * we can't expect better than +/-.5E-5 on the result, allow 1E-5.
7501              */
7502             if (maxe >= 1E-5)
7503             {
7504                size_t pos = 0;
7505                char buffer[256];
7506
7507                pos = safecat(buffer, sizeof buffer, pos, API_form);
7508                pos = safecat(buffer, sizeof buffer, pos, " cHRM ");
7509                pos = safecat(buffer, sizeof buffer, pos, el);
7510                pos = safecat(buffer, sizeof buffer, pos, " error: ");
7511                pos = safecatd(buffer, sizeof buffer, pos, maxe, 7);
7512                pos = safecat(buffer, sizeof buffer, pos, " ");
7513                /* Print the color space without the gamma value: */
7514                pos = safecat_color_encoding(buffer, sizeof buffer, pos, &o, 0);
7515                pos = safecat(buffer, sizeof buffer, pos, " -> ");
7516                pos = safecat_color_encoding(buffer, sizeof buffer, pos, &e, 0);
7517
7518                png_error(pp, buffer);
7519             }
7520          }
7521       }
7522 #  endif /* READ_cHRM */
7523
7524    this->next->set(this->next, that, pp, pi);
7525 }
7526
7527 static void
7528 image_transform_png_set_rgb_to_gray_mod(const image_transform *this,
7529     image_pixel *that, png_const_structp pp,
7530     const transform_display *display)
7531 {
7532    if ((that->colour_type & PNG_COLOR_MASK_COLOR) != 0)
7533    {
7534       double gray, err;
7535
7536 #     if PNG_LIBPNG_VER < 10700
7537          if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
7538             image_pixel_convert_PLTE(that);
7539 #     endif
7540
7541       /* Image now has RGB channels... */
7542 #  if DIGITIZE
7543       {
7544          png_modifier *pm = display->pm;
7545          const unsigned int sample_depth = that->sample_depth;
7546          const unsigned int calc_depth = (pm->assume_16_bit_calculations ? 16 :
7547             sample_depth);
7548          const unsigned int gamma_depth =
7549             (sample_depth == 16 ?
7550                display->max_gamma_8 :
7551                (pm->assume_16_bit_calculations ?
7552                   display->max_gamma_8 :
7553                   sample_depth));
7554          int isgray;
7555          double r, g, b;
7556          double rlo, rhi, glo, ghi, blo, bhi, graylo, grayhi;
7557
7558          /* Do this using interval arithmetic, otherwise it is too difficult to
7559           * handle the errors correctly.
7560           *
7561           * To handle the gamma correction work out the upper and lower bounds
7562           * of the digitized value.  Assume rounding here - normally the values
7563           * will be identical after this operation if there is only one
7564           * transform, feel free to delete the png_error checks on this below in
7565           * the future (this is just me trying to ensure it works!)
7566           *
7567           * Interval arithmetic is exact, but to implement it it must be
7568           * possible to control the floating point implementation rounding mode.
7569           * This cannot be done in ANSI-C, so instead I reduce the 'lo' values
7570           * by DBL_EPSILON and increase the 'hi' values by the same.
7571           */
7572 #        define DD(v,d,r) (digitize(v*(1-DBL_EPSILON), d, r) * (1-DBL_EPSILON))
7573 #        define DU(v,d,r) (digitize(v*(1+DBL_EPSILON), d, r) * (1+DBL_EPSILON))
7574
7575          r = rlo = rhi = that->redf;
7576          rlo -= that->rede;
7577          rlo = DD(rlo, calc_depth, 1/*round*/);
7578          rhi += that->rede;
7579          rhi = DU(rhi, calc_depth, 1/*round*/);
7580
7581          g = glo = ghi = that->greenf;
7582          glo -= that->greene;
7583          glo = DD(glo, calc_depth, 1/*round*/);
7584          ghi += that->greene;
7585          ghi = DU(ghi, calc_depth, 1/*round*/);
7586
7587          b = blo = bhi = that->bluef;
7588          blo -= that->bluee;
7589          blo = DD(blo, calc_depth, 1/*round*/);
7590          bhi += that->bluee;
7591          bhi = DU(bhi, calc_depth, 1/*round*/);
7592
7593          isgray = r==g && g==b;
7594
7595          if (data.gamma != 1)
7596          {
7597             const double power = 1/data.gamma;
7598             const double abse = .5/(sample_depth == 16 ? 65535 : 255);
7599
7600             /* If a gamma calculation is done it is done using lookup tables of
7601              * precision gamma_depth, so the already digitized value above may
7602              * need to be further digitized here.
7603              */
7604             if (gamma_depth != calc_depth)
7605             {
7606                rlo = DD(rlo, gamma_depth, 0/*truncate*/);
7607                rhi = DU(rhi, gamma_depth, 0/*truncate*/);
7608                glo = DD(glo, gamma_depth, 0/*truncate*/);
7609                ghi = DU(ghi, gamma_depth, 0/*truncate*/);
7610                blo = DD(blo, gamma_depth, 0/*truncate*/);
7611                bhi = DU(bhi, gamma_depth, 0/*truncate*/);
7612             }
7613
7614             /* 'abse' is the error in the gamma table calculation itself. */
7615             r = pow(r, power);
7616             rlo = DD(pow(rlo, power)-abse, calc_depth, 1);
7617             rhi = DU(pow(rhi, power)+abse, calc_depth, 1);
7618
7619             g = pow(g, power);
7620             glo = DD(pow(glo, power)-abse, calc_depth, 1);
7621             ghi = DU(pow(ghi, power)+abse, calc_depth, 1);
7622
7623             b = pow(b, power);
7624             blo = DD(pow(blo, power)-abse, calc_depth, 1);
7625             bhi = DU(pow(bhi, power)+abse, calc_depth, 1);
7626          }
7627
7628          /* Now calculate the actual gray values.  Although the error in the
7629           * coefficients depends on whether they were specified on the command
7630           * line (in which case truncation to 15 bits happened) or not (rounding
7631           * was used) the maxium error in an individual coefficient is always
7632           * 2/32768, because even in the rounding case the requirement that
7633           * coefficients add up to 32768 can cause a larger rounding error.
7634           *
7635           * The only time when rounding doesn't occur in 1.5.5 and later is when
7636           * the non-gamma code path is used for less than 16 bit data.
7637           */
7638          gray = r * data.red_coefficient + g * data.green_coefficient +
7639             b * data.blue_coefficient;
7640
7641          {
7642             const int do_round = data.gamma != 1 || calc_depth == 16;
7643             const double ce = 2. / 32768;
7644
7645             graylo = DD(rlo * (data.red_coefficient-ce) +
7646                glo * (data.green_coefficient-ce) +
7647                blo * (data.blue_coefficient-ce), calc_depth, do_round);
7648             if (graylo > gray) /* always accept the right answer */
7649                graylo = gray;
7650
7651             grayhi = DU(rhi * (data.red_coefficient+ce) +
7652                ghi * (data.green_coefficient+ce) +
7653                bhi * (data.blue_coefficient+ce), calc_depth, do_round);
7654             if (grayhi < gray)
7655                grayhi = gray;
7656          }
7657
7658          /* And invert the gamma. */
7659          if (data.gamma != 1)
7660          {
7661             const double power = data.gamma;
7662
7663             /* And this happens yet again, shifting the values once more. */
7664             if (gamma_depth != sample_depth)
7665             {
7666                rlo = DD(rlo, gamma_depth, 0/*truncate*/);
7667                rhi = DU(rhi, gamma_depth, 0/*truncate*/);
7668                glo = DD(glo, gamma_depth, 0/*truncate*/);
7669                ghi = DU(ghi, gamma_depth, 0/*truncate*/);
7670                blo = DD(blo, gamma_depth, 0/*truncate*/);
7671                bhi = DU(bhi, gamma_depth, 0/*truncate*/);
7672             }
7673
7674             gray = pow(gray, power);
7675             graylo = DD(pow(graylo, power), sample_depth, 1);
7676             grayhi = DU(pow(grayhi, power), sample_depth, 1);
7677          }
7678
7679 #        undef DD
7680 #        undef DU
7681
7682          /* Now the error can be calculated.
7683           *
7684           * If r==g==b because there is no overall gamma correction libpng
7685           * currently preserves the original value.
7686           */
7687          if (isgray)
7688             err = (that->rede + that->greene + that->bluee)/3;
7689
7690          else
7691          {
7692             err = fabs(grayhi-gray);
7693
7694             if (fabs(gray - graylo) > err)
7695                err = fabs(graylo-gray);
7696
7697 #if !RELEASE_BUILD
7698             /* Check that this worked: */
7699             if (err > pm->limit)
7700             {
7701                size_t pos = 0;
7702                char buffer[128];
7703
7704                pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
7705                pos = safecatd(buffer, sizeof buffer, pos, err, 6);
7706                pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
7707                pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
7708                png_warning(pp, buffer);
7709                pm->limit = err;
7710             }
7711 #endif /* !RELEASE_BUILD */
7712          }
7713       }
7714 #  else  /* !DIGITIZE */
7715       {
7716          double r = that->redf;
7717          double re = that->rede;
7718          double g = that->greenf;
7719          double ge = that->greene;
7720          double b = that->bluef;
7721          double be = that->bluee;
7722
7723 #        if PNG_LIBPNG_VER < 10700
7724             /* The true gray case involves no math in earlier versions (not
7725              * true, there was some if gamma correction was happening too.)
7726              */
7727             if (r == g && r == b)
7728             {
7729                gray = r;
7730                err = re;
7731                if (err < ge) err = ge;
7732                if (err < be) err = be;
7733             }
7734
7735             else
7736 #        endif /* before 1.7 */
7737          if (data.gamma == 1)
7738          {
7739             /* There is no need to do the conversions to and from linear space,
7740              * so the calculation should be a lot more accurate.  There is a
7741              * built in error in the coefficients because they only have 15 bits
7742              * and are adjusted to make sure they add up to 32768.  This
7743              * involves a integer calculation with truncation of the form:
7744              *
7745              *     ((int)(coefficient * 100000) * 32768)/100000
7746              *
7747              * This is done to the red and green coefficients (the ones
7748              * provided to the API) then blue is calculated from them so the
7749              * result adds up to 32768.  In the worst case this can result in
7750              * a -1 error in red and green and a +2 error in blue.  Consequently
7751              * the worst case in the calculation below is 2/32768 error.
7752              *
7753              * TODO: consider fixing this in libpng by rounding the calculation
7754              * limiting the error to 1/32768.
7755              *
7756              * Handling this by adding 2/32768 here avoids needing to increase
7757              * the global error limits to take this into account.)
7758              */
7759             gray = r * data.red_coefficient + g * data.green_coefficient +
7760                b * data.blue_coefficient;
7761             err = re * data.red_coefficient + ge * data.green_coefficient +
7762                be * data.blue_coefficient + 2./32768 + gray * 5 * DBL_EPSILON;
7763          }
7764
7765          else
7766          {
7767             /* The calculation happens in linear space, and this produces much
7768              * wider errors in the encoded space.  These are handled here by
7769              * factoring the errors in to the calculation.  There are two table
7770              * lookups in the calculation and each introduces a quantization
7771              * error defined by the table size.
7772              */
7773             png_modifier *pm = display->pm;
7774             double in_qe = (that->sample_depth > 8 ? .5/65535 : .5/255);
7775             double out_qe = (that->sample_depth > 8 ? .5/65535 :
7776                (pm->assume_16_bit_calculations ? .5/(1<<display->max_gamma_8) :
7777                .5/255));
7778             double rhi, ghi, bhi, grayhi;
7779             double g1 = 1/data.gamma;
7780
7781             rhi = r + re + in_qe; if (rhi > 1) rhi = 1;
7782             r -= re + in_qe; if (r < 0) r = 0;
7783             ghi = g + ge + in_qe; if (ghi > 1) ghi = 1;
7784             g -= ge + in_qe; if (g < 0) g = 0;
7785             bhi = b + be + in_qe; if (bhi > 1) bhi = 1;
7786             b -= be + in_qe; if (b < 0) b = 0;
7787
7788             r = pow(r, g1)*(1-DBL_EPSILON); rhi = pow(rhi, g1)*(1+DBL_EPSILON);
7789             g = pow(g, g1)*(1-DBL_EPSILON); ghi = pow(ghi, g1)*(1+DBL_EPSILON);
7790             b = pow(b, g1)*(1-DBL_EPSILON); bhi = pow(bhi, g1)*(1+DBL_EPSILON);
7791
7792             /* Work out the lower and upper bounds for the gray value in the
7793              * encoded space, then work out an average and error.  Remove the
7794              * previously added input quantization error at this point.
7795              */
7796             gray = r * data.red_coefficient + g * data.green_coefficient +
7797                b * data.blue_coefficient - 2./32768 - out_qe;
7798             if (gray <= 0)
7799                gray = 0;
7800             else
7801             {
7802                gray *= (1 - 6 * DBL_EPSILON);
7803                gray = pow(gray, data.gamma) * (1-DBL_EPSILON);
7804             }
7805
7806             grayhi = rhi * data.red_coefficient + ghi * data.green_coefficient +
7807                bhi * data.blue_coefficient + 2./32768 + out_qe;
7808             grayhi *= (1 + 6 * DBL_EPSILON);
7809             if (grayhi >= 1)
7810                grayhi = 1;
7811             else
7812                grayhi = pow(grayhi, data.gamma) * (1+DBL_EPSILON);
7813
7814             err = (grayhi - gray) / 2;
7815             gray = (grayhi + gray) / 2;
7816
7817             if (err <= in_qe)
7818                err = gray * DBL_EPSILON;
7819
7820             else
7821                err -= in_qe;
7822
7823 #if !RELEASE_BUILD
7824             /* Validate that the error is within limits (this has caused
7825              * problems before, it's much easier to detect them here.)
7826              */
7827             if (err > pm->limit)
7828             {
7829                size_t pos = 0;
7830                char buffer[128];
7831
7832                pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
7833                pos = safecatd(buffer, sizeof buffer, pos, err, 6);
7834                pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
7835                pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
7836                png_warning(pp, buffer);
7837                pm->limit = err;
7838             }
7839 #endif /* !RELEASE_BUILD */
7840          }
7841       }
7842 #  endif /* !DIGITIZE */
7843
7844       that->bluef = that->greenf = that->redf = gray;
7845       that->bluee = that->greene = that->rede = err;
7846
7847       /* The sBIT is the minium of the three colour channel sBITs. */
7848       if (that->red_sBIT > that->green_sBIT)
7849          that->red_sBIT = that->green_sBIT;
7850       if (that->red_sBIT > that->blue_sBIT)
7851          that->red_sBIT = that->blue_sBIT;
7852       that->blue_sBIT = that->green_sBIT = that->red_sBIT;
7853
7854       /* And remove the colour bit in the type: */
7855       if (that->colour_type == PNG_COLOR_TYPE_RGB)
7856          that->colour_type = PNG_COLOR_TYPE_GRAY;
7857       else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
7858          that->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
7859    }
7860
7861    this->next->mod(this->next, that, pp, display);
7862 }
7863
7864 static int
7865 image_transform_png_set_rgb_to_gray_add(image_transform *this,
7866     const image_transform **that, png_byte colour_type, png_byte bit_depth)
7867 {
7868    UNUSED(bit_depth)
7869
7870    this->next = *that;
7871    *that = this;
7872
7873    return (colour_type & PNG_COLOR_MASK_COLOR) != 0;
7874 }
7875
7876 #undef data
7877 IT(rgb_to_gray);
7878 #undef PT
7879 #define PT ITSTRUCT(rgb_to_gray)
7880 #undef image_transform_ini
7881 #define image_transform_ini image_transform_default_ini
7882 #endif /* PNG_READ_RGB_TO_GRAY_SUPPORTED */
7883
7884 #ifdef PNG_READ_BACKGROUND_SUPPORTED
7885 /* png_set_background(png_structp, png_const_color_16p background_color,
7886  *    int background_gamma_code, int need_expand, double background_gamma)
7887  * png_set_background_fixed(png_structp, png_const_color_16p background_color,
7888  *    int background_gamma_code, int need_expand,
7889  *    png_fixed_point background_gamma)
7890  *
7891  * This ignores the gamma (at present.)
7892 */
7893 #define data ITDATA(background)
7894 static image_pixel data;
7895
7896 static void
7897 image_transform_png_set_background_set(const image_transform *this,
7898     transform_display *that, png_structp pp, png_infop pi)
7899 {
7900    png_byte colour_type, bit_depth;
7901    png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */
7902    int expand;
7903    png_color_16 back;
7904
7905    /* We need a background colour, because we don't know exactly what transforms
7906     * have been set we have to supply the colour in the original file format and
7907     * so we need to know what that is!  The background colour is stored in the
7908     * transform_display.
7909     */
7910    R8(random_bytes);
7911
7912    /* Read the random value, for colour type 3 the background colour is actually
7913     * expressed as a 24bit rgb, not an index.
7914     */
7915    colour_type = that->this.colour_type;
7916    if (colour_type == 3)
7917    {
7918       colour_type = PNG_COLOR_TYPE_RGB;
7919       bit_depth = 8;
7920       expand = 0; /* passing in an RGB not a pixel index */
7921    }
7922
7923    else
7924    {
7925       if (that->this.has_tRNS)
7926          that->this.is_transparent = 1;
7927
7928       bit_depth = that->this.bit_depth;
7929       expand = 1;
7930    }
7931
7932    image_pixel_init(&data, random_bytes, colour_type,
7933       bit_depth, 0/*x*/, 0/*unused: palette*/, NULL/*format*/);
7934
7935    /* Extract the background colour from this image_pixel, but make sure the
7936     * unused fields of 'back' are garbage.
7937     */
7938    R8(back);
7939
7940    if (colour_type & PNG_COLOR_MASK_COLOR)
7941    {
7942       back.red = (png_uint_16)data.red;
7943       back.green = (png_uint_16)data.green;
7944       back.blue = (png_uint_16)data.blue;
7945    }
7946
7947    else
7948       back.gray = (png_uint_16)data.red;
7949
7950 #  ifdef PNG_FLOATING_POINT_SUPPORTED
7951       png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
7952 #  else
7953       png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
7954 #  endif
7955
7956    this->next->set(this->next, that, pp, pi);
7957 }
7958
7959 static void
7960 image_transform_png_set_background_mod(const image_transform *this,
7961     image_pixel *that, png_const_structp pp,
7962     const transform_display *display)
7963 {
7964    /* Check for tRNS first: */
7965    if (that->have_tRNS && that->colour_type != PNG_COLOR_TYPE_PALETTE)
7966       image_pixel_add_alpha(that, &display->this, 1/*for background*/);
7967
7968    /* This is only necessary if the alpha value is less than 1. */
7969    if (that->alphaf < 1)
7970    {
7971       /* Now we do the background calculation without any gamma correction. */
7972       if (that->alphaf <= 0)
7973       {
7974          that->redf = data.redf;
7975          that->greenf = data.greenf;
7976          that->bluef = data.bluef;
7977
7978          that->rede = data.rede;
7979          that->greene = data.greene;
7980          that->bluee = data.bluee;
7981
7982          that->red_sBIT= data.red_sBIT;
7983          that->green_sBIT= data.green_sBIT;
7984          that->blue_sBIT= data.blue_sBIT;
7985       }
7986
7987       else /* 0 < alpha < 1 */
7988       {
7989          double alf = 1 - that->alphaf;
7990
7991          that->redf = that->redf * that->alphaf + data.redf * alf;
7992          that->rede = that->rede * that->alphaf + data.rede * alf +
7993             DBL_EPSILON;
7994          that->greenf = that->greenf * that->alphaf + data.greenf * alf;
7995          that->greene = that->greene * that->alphaf + data.greene * alf +
7996             DBL_EPSILON;
7997          that->bluef = that->bluef * that->alphaf + data.bluef * alf;
7998          that->bluee = that->bluee * that->alphaf + data.bluee * alf +
7999             DBL_EPSILON;
8000       }
8001
8002       /* Remove the alpha type and set the alpha (not in that order.) */
8003       that->alphaf = 1;
8004       that->alphae = 0;
8005    }
8006
8007    if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
8008       that->colour_type = PNG_COLOR_TYPE_RGB;
8009    else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
8010       that->colour_type = PNG_COLOR_TYPE_GRAY;
8011    /* PNG_COLOR_TYPE_PALETTE is not changed */
8012
8013    this->next->mod(this->next, that, pp, display);
8014 }
8015
8016 #define image_transform_png_set_background_add image_transform_default_add
8017
8018 #undef data
8019 IT(background);
8020 #undef PT
8021 #define PT ITSTRUCT(background)
8022 #endif /* PNG_READ_BACKGROUND_SUPPORTED */
8023
8024 /* png_set_quantize(png_structp, png_colorp palette, int num_palette,
8025  *    int maximum_colors, png_const_uint_16p histogram, int full_quantize)
8026  *
8027  * Very difficult to validate this!
8028  */
8029 /*NOTE: TBD NYI */
8030
8031 /* The data layout transforms are handled by swapping our own channel data,
8032  * necessarily these need to happen at the end of the transform list because the
8033  * semantic of the channels changes after these are executed.  Some of these,
8034  * like set_shift and set_packing, can't be done at present because they change
8035  * the layout of the data at the sub-sample level so sample() won't get the
8036  * right answer.
8037  */
8038 /* png_set_invert_alpha */
8039 #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
8040 /* Invert the alpha channel
8041  *
8042  *  png_set_invert_alpha(png_structrp png_ptr)
8043  */
8044 static void
8045 image_transform_png_set_invert_alpha_set(const image_transform *this,
8046     transform_display *that, png_structp pp, png_infop pi)
8047 {
8048    png_set_invert_alpha(pp);
8049    this->next->set(this->next, that, pp, pi);
8050 }
8051
8052 static void
8053 image_transform_png_set_invert_alpha_mod(const image_transform *this,
8054     image_pixel *that, png_const_structp pp,
8055     const transform_display *display)
8056 {
8057    if (that->colour_type & 4)
8058       that->alpha_inverted = 1;
8059
8060    this->next->mod(this->next, that, pp, display);
8061 }
8062
8063 static int
8064 image_transform_png_set_invert_alpha_add(image_transform *this,
8065     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8066 {
8067    UNUSED(bit_depth)
8068
8069    this->next = *that;
8070    *that = this;
8071
8072    /* Only has an effect on pixels with alpha: */
8073    return (colour_type & 4) != 0;
8074 }
8075
8076 IT(invert_alpha);
8077 #undef PT
8078 #define PT ITSTRUCT(invert_alpha)
8079
8080 #endif /* PNG_READ_INVERT_ALPHA_SUPPORTED */
8081
8082 /* png_set_bgr */
8083 #ifdef PNG_READ_BGR_SUPPORTED
8084 /* Swap R,G,B channels to order B,G,R.
8085  *
8086  *  png_set_bgr(png_structrp png_ptr)
8087  *
8088  * This only has an effect on RGB and RGBA pixels.
8089  */
8090 static void
8091 image_transform_png_set_bgr_set(const image_transform *this,
8092     transform_display *that, png_structp pp, png_infop pi)
8093 {
8094    png_set_bgr(pp);
8095    this->next->set(this->next, that, pp, pi);
8096 }
8097
8098 static void
8099 image_transform_png_set_bgr_mod(const image_transform *this,
8100     image_pixel *that, png_const_structp pp,
8101     const transform_display *display)
8102 {
8103    if (that->colour_type == PNG_COLOR_TYPE_RGB ||
8104        that->colour_type == PNG_COLOR_TYPE_RGBA)
8105        that->swap_rgb = 1;
8106
8107    this->next->mod(this->next, that, pp, display);
8108 }
8109
8110 static int
8111 image_transform_png_set_bgr_add(image_transform *this,
8112     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8113 {
8114    UNUSED(bit_depth)
8115
8116    this->next = *that;
8117    *that = this;
8118
8119    return colour_type == PNG_COLOR_TYPE_RGB ||
8120        colour_type == PNG_COLOR_TYPE_RGBA;
8121 }
8122
8123 IT(bgr);
8124 #undef PT
8125 #define PT ITSTRUCT(bgr)
8126
8127 #endif /* PNG_READ_BGR_SUPPORTED */
8128
8129 /* png_set_swap_alpha */
8130 #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
8131 /* Put the alpha channel first.
8132  *
8133  *  png_set_swap_alpha(png_structrp png_ptr)
8134  *
8135  * This only has an effect on GA and RGBA pixels.
8136  */
8137 static void
8138 image_transform_png_set_swap_alpha_set(const image_transform *this,
8139     transform_display *that, png_structp pp, png_infop pi)
8140 {
8141    png_set_swap_alpha(pp);
8142    this->next->set(this->next, that, pp, pi);
8143 }
8144
8145 static void
8146 image_transform_png_set_swap_alpha_mod(const image_transform *this,
8147     image_pixel *that, png_const_structp pp,
8148     const transform_display *display)
8149 {
8150    if (that->colour_type == PNG_COLOR_TYPE_GA ||
8151        that->colour_type == PNG_COLOR_TYPE_RGBA)
8152       that->alpha_first = 1;
8153
8154    this->next->mod(this->next, that, pp, display);
8155 }
8156
8157 static int
8158 image_transform_png_set_swap_alpha_add(image_transform *this,
8159     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8160 {
8161    UNUSED(bit_depth)
8162
8163    this->next = *that;
8164    *that = this;
8165
8166    return colour_type == PNG_COLOR_TYPE_GA ||
8167        colour_type == PNG_COLOR_TYPE_RGBA;
8168 }
8169
8170 IT(swap_alpha);
8171 #undef PT
8172 #define PT ITSTRUCT(swap_alpha)
8173
8174 #endif /* PNG_READ_SWAP_ALPHA_SUPPORTED */
8175
8176 /* png_set_swap */
8177 #ifdef PNG_READ_SWAP_SUPPORTED
8178 /* Byte swap 16-bit components.
8179  *
8180  *  png_set_swap(png_structrp png_ptr)
8181  */
8182 static void
8183 image_transform_png_set_swap_set(const image_transform *this,
8184     transform_display *that, png_structp pp, png_infop pi)
8185 {
8186    png_set_swap(pp);
8187    this->next->set(this->next, that, pp, pi);
8188 }
8189
8190 static void
8191 image_transform_png_set_swap_mod(const image_transform *this,
8192     image_pixel *that, png_const_structp pp,
8193     const transform_display *display)
8194 {
8195    if (that->bit_depth == 16)
8196       that->swap16 = 1;
8197
8198    this->next->mod(this->next, that, pp, display);
8199 }
8200
8201 static int
8202 image_transform_png_set_swap_add(image_transform *this,
8203     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8204 {
8205    UNUSED(colour_type)
8206
8207    this->next = *that;
8208    *that = this;
8209
8210    return bit_depth == 16;
8211 }
8212
8213 IT(swap);
8214 #undef PT
8215 #define PT ITSTRUCT(swap)
8216
8217 #endif /* PNG_READ_SWAP_SUPPORTED */
8218
8219 #ifdef PNG_READ_FILLER_SUPPORTED
8220 /* Add a filler byte to 8-bit Gray or 24-bit RGB images.
8221  *
8222  *  png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags));
8223  *
8224  * Flags:
8225  *
8226  *  PNG_FILLER_BEFORE
8227  *  PNG_FILLER_AFTER
8228  */
8229 #define data ITDATA(filler)
8230 static struct
8231 {
8232    png_uint_32 filler;
8233    int         flags;
8234 } data;
8235
8236 static void
8237 image_transform_png_set_filler_set(const image_transform *this,
8238     transform_display *that, png_structp pp, png_infop pi)
8239 {
8240    /* Need a random choice for 'before' and 'after' as well as for the
8241     * filler.  The 'filler' value has all 32 bits set, but only bit_depth
8242     * will be used.  At this point we don't know bit_depth.
8243     */
8244    R32(data.filler);
8245    data.flags = random_choice();
8246
8247    png_set_filler(pp, data.filler, data.flags);
8248
8249    /* The standard display handling stuff also needs to know that
8250     * there is a filler, so set that here.
8251     */
8252    that->this.filler = 1;
8253
8254    this->next->set(this->next, that, pp, pi);
8255 }
8256
8257 static void
8258 image_transform_png_set_filler_mod(const image_transform *this,
8259     image_pixel *that, png_const_structp pp,
8260     const transform_display *display)
8261 {
8262    if (that->bit_depth >= 8 &&
8263        (that->colour_type == PNG_COLOR_TYPE_RGB ||
8264         that->colour_type == PNG_COLOR_TYPE_GRAY))
8265    {
8266       const unsigned int max = (1U << that->bit_depth)-1;
8267       that->alpha = data.filler & max;
8268       that->alphaf = ((double)that->alpha) / max;
8269       that->alphae = 0;
8270
8271       /* The filler has been stored in the alpha channel, we must record
8272        * that this has been done for the checking later on, the color
8273        * type is faked to have an alpha channel, but libpng won't report
8274        * this; the app has to know the extra channel is there and this
8275        * was recording in standard_display::filler above.
8276        */
8277       that->colour_type |= 4; /* alpha added */
8278       that->alpha_first = data.flags == PNG_FILLER_BEFORE;
8279    }
8280
8281    this->next->mod(this->next, that, pp, display);
8282 }
8283
8284 static int
8285 image_transform_png_set_filler_add(image_transform *this,
8286     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8287 {
8288    this->next = *that;
8289    *that = this;
8290
8291    return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
8292            colour_type == PNG_COLOR_TYPE_GRAY);
8293 }
8294
8295 #undef data
8296 IT(filler);
8297 #undef PT
8298 #define PT ITSTRUCT(filler)
8299
8300 /* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */
8301 /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
8302 #define data ITDATA(add_alpha)
8303 static struct
8304 {
8305    png_uint_32 filler;
8306    int         flags;
8307 } data;
8308
8309 static void
8310 image_transform_png_set_add_alpha_set(const image_transform *this,
8311     transform_display *that, png_structp pp, png_infop pi)
8312 {
8313    /* Need a random choice for 'before' and 'after' as well as for the
8314     * filler.  The 'filler' value has all 32 bits set, but only bit_depth
8315     * will be used.  At this point we don't know bit_depth.
8316     */
8317    R32(data.filler);
8318    data.flags = random_choice();
8319
8320    png_set_add_alpha(pp, data.filler, data.flags);
8321    this->next->set(this->next, that, pp, pi);
8322 }
8323
8324 static void
8325 image_transform_png_set_add_alpha_mod(const image_transform *this,
8326     image_pixel *that, png_const_structp pp,
8327     const transform_display *display)
8328 {
8329    if (that->bit_depth >= 8 &&
8330        (that->colour_type == PNG_COLOR_TYPE_RGB ||
8331         that->colour_type == PNG_COLOR_TYPE_GRAY))
8332    {
8333       const unsigned int max = (1U << that->bit_depth)-1;
8334       that->alpha = data.filler & max;
8335       that->alphaf = ((double)that->alpha) / max;
8336       that->alphae = 0;
8337
8338       that->colour_type |= 4; /* alpha added */
8339       that->alpha_first = data.flags == PNG_FILLER_BEFORE;
8340    }
8341
8342    this->next->mod(this->next, that, pp, display);
8343 }
8344
8345 static int
8346 image_transform_png_set_add_alpha_add(image_transform *this,
8347     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8348 {
8349    this->next = *that;
8350    *that = this;
8351
8352    return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
8353            colour_type == PNG_COLOR_TYPE_GRAY);
8354 }
8355
8356 #undef data
8357 IT(add_alpha);
8358 #undef PT
8359 #define PT ITSTRUCT(add_alpha)
8360
8361 #endif /* PNG_READ_FILLER_SUPPORTED */
8362
8363 /* png_set_packing */
8364 #ifdef PNG_READ_PACK_SUPPORTED
8365 /* Use 1 byte per pixel in 1, 2, or 4-bit depth files.
8366  *
8367  *  png_set_packing(png_structrp png_ptr)
8368  *
8369  * This should only affect grayscale and palette images with less than 8 bits
8370  * per pixel.
8371  */
8372 static void
8373 image_transform_png_set_packing_set(const image_transform *this,
8374     transform_display *that, png_structp pp, png_infop pi)
8375 {
8376    png_set_packing(pp);
8377    that->unpacked = 1;
8378    this->next->set(this->next, that, pp, pi);
8379 }
8380
8381 static void
8382 image_transform_png_set_packing_mod(const image_transform *this,
8383     image_pixel *that, png_const_structp pp,
8384     const transform_display *display)
8385 {
8386    /* The general expand case depends on what the colour type is,
8387     * low bit-depth pixel values are unpacked into bytes without
8388     * scaling, so sample_depth is not changed.
8389     */
8390    if (that->bit_depth < 8) /* grayscale or palette */
8391       that->bit_depth = 8;
8392
8393    this->next->mod(this->next, that, pp, display);
8394 }
8395
8396 static int
8397 image_transform_png_set_packing_add(image_transform *this,
8398     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8399 {
8400    UNUSED(colour_type)
8401
8402    this->next = *that;
8403    *that = this;
8404
8405    /* Nothing should happen unless the bit depth is less than 8: */
8406    return bit_depth < 8;
8407 }
8408
8409 IT(packing);
8410 #undef PT
8411 #define PT ITSTRUCT(packing)
8412
8413 #endif /* PNG_READ_PACK_SUPPORTED */
8414
8415 /* png_set_packswap */
8416 #ifdef PNG_READ_PACKSWAP_SUPPORTED
8417 /* Swap pixels packed into bytes; reverses the order on screen so that
8418  * the high order bits correspond to the rightmost pixels.
8419  *
8420  *  png_set_packswap(png_structrp png_ptr)
8421  */
8422 static void
8423 image_transform_png_set_packswap_set(const image_transform *this,
8424     transform_display *that, png_structp pp, png_infop pi)
8425 {
8426    png_set_packswap(pp);
8427    that->this.littleendian = 1;
8428    this->next->set(this->next, that, pp, pi);
8429 }
8430
8431 static void
8432 image_transform_png_set_packswap_mod(const image_transform *this,
8433     image_pixel *that, png_const_structp pp,
8434     const transform_display *display)
8435 {
8436    if (that->bit_depth < 8)
8437       that->littleendian = 1;
8438
8439    this->next->mod(this->next, that, pp, display);
8440 }
8441
8442 static int
8443 image_transform_png_set_packswap_add(image_transform *this,
8444     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8445 {
8446    UNUSED(colour_type)
8447
8448    this->next = *that;
8449    *that = this;
8450
8451    return bit_depth < 8;
8452 }
8453
8454 IT(packswap);
8455 #undef PT
8456 #define PT ITSTRUCT(packswap)
8457
8458 #endif /* PNG_READ_PACKSWAP_SUPPORTED */
8459
8460
8461 /* png_set_invert_mono */
8462 #ifdef PNG_READ_INVERT_MONO_SUPPORTED
8463 /* Invert the gray channel
8464  *
8465  *  png_set_invert_mono(png_structrp png_ptr)
8466  */
8467 static void
8468 image_transform_png_set_invert_mono_set(const image_transform *this,
8469     transform_display *that, png_structp pp, png_infop pi)
8470 {
8471    png_set_invert_mono(pp);
8472    this->next->set(this->next, that, pp, pi);
8473 }
8474
8475 static void
8476 image_transform_png_set_invert_mono_mod(const image_transform *this,
8477     image_pixel *that, png_const_structp pp,
8478     const transform_display *display)
8479 {
8480    if (that->colour_type & 4)
8481       that->mono_inverted = 1;
8482
8483    this->next->mod(this->next, that, pp, display);
8484 }
8485
8486 static int
8487 image_transform_png_set_invert_mono_add(image_transform *this,
8488     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8489 {
8490    UNUSED(bit_depth)
8491
8492    this->next = *that;
8493    *that = this;
8494
8495    /* Only has an effect on pixels with no colour: */
8496    return (colour_type & 2) == 0;
8497 }
8498
8499 IT(invert_mono);
8500 #undef PT
8501 #define PT ITSTRUCT(invert_mono)
8502
8503 #endif /* PNG_READ_INVERT_MONO_SUPPORTED */
8504
8505 #ifdef PNG_READ_SHIFT_SUPPORTED
8506 /* png_set_shift(png_structp, png_const_color_8p true_bits)
8507  *
8508  * The output pixels will be shifted by the given true_bits
8509  * values.
8510  */
8511 #define data ITDATA(shift)
8512 static png_color_8 data;
8513
8514 static void
8515 image_transform_png_set_shift_set(const image_transform *this,
8516     transform_display *that, png_structp pp, png_infop pi)
8517 {
8518    /* Get a random set of shifts.  The shifts need to do something
8519     * to test the transform, so they are limited to the bit depth
8520     * of the input image.  Notice that in the following the 'gray'
8521     * field is randomized independently.  This acts as a check that
8522     * libpng does use the correct field.
8523     */
8524    const unsigned int depth = that->this.bit_depth;
8525
8526    data.red = (png_byte)/*SAFE*/(random_mod(depth)+1);
8527    data.green = (png_byte)/*SAFE*/(random_mod(depth)+1);
8528    data.blue = (png_byte)/*SAFE*/(random_mod(depth)+1);
8529    data.gray = (png_byte)/*SAFE*/(random_mod(depth)+1);
8530    data.alpha = (png_byte)/*SAFE*/(random_mod(depth)+1);
8531
8532    png_set_shift(pp, &data);
8533    this->next->set(this->next, that, pp, pi);
8534 }
8535
8536 static void
8537 image_transform_png_set_shift_mod(const image_transform *this,
8538     image_pixel *that, png_const_structp pp,
8539     const transform_display *display)
8540 {
8541    /* Copy the correct values into the sBIT fields, libpng does not do
8542     * anything to palette data:
8543     */
8544    if (that->colour_type != PNG_COLOR_TYPE_PALETTE)
8545    {
8546        that->sig_bits = 1;
8547
8548        /* The sBIT fields are reset to the values previously sent to
8549         * png_set_shift according to the colour type.
8550         * does.
8551         */
8552        if (that->colour_type & 2) /* RGB channels */
8553        {
8554           that->red_sBIT = data.red;
8555           that->green_sBIT = data.green;
8556           that->blue_sBIT = data.blue;
8557        }
8558
8559        else /* One grey channel */
8560           that->red_sBIT = that->green_sBIT = that->blue_sBIT = data.gray;
8561
8562        that->alpha_sBIT = data.alpha;
8563    }
8564
8565    this->next->mod(this->next, that, pp, display);
8566 }
8567
8568 static int
8569 image_transform_png_set_shift_add(image_transform *this,
8570     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8571 {
8572    UNUSED(bit_depth)
8573
8574    this->next = *that;
8575    *that = this;
8576
8577    return colour_type != PNG_COLOR_TYPE_PALETTE;
8578 }
8579
8580 IT(shift);
8581 #undef PT
8582 #define PT ITSTRUCT(shift)
8583
8584 #endif /* PNG_READ_SHIFT_SUPPORTED */
8585
8586 #ifdef THIS_IS_THE_PROFORMA
8587 static void
8588 image_transform_png_set_@_set(const image_transform *this,
8589     transform_display *that, png_structp pp, png_infop pi)
8590 {
8591    png_set_@(pp);
8592    this->next->set(this->next, that, pp, pi);
8593 }
8594
8595 static void
8596 image_transform_png_set_@_mod(const image_transform *this,
8597     image_pixel *that, png_const_structp pp,
8598     const transform_display *display)
8599 {
8600    this->next->mod(this->next, that, pp, display);
8601 }
8602
8603 static int
8604 image_transform_png_set_@_add(image_transform *this,
8605     const image_transform **that, png_byte colour_type, png_byte bit_depth)
8606 {
8607    this->next = *that;
8608    *that = this;
8609
8610    return 1;
8611 }
8612
8613 IT(@);
8614 #endif
8615
8616
8617 /* This may just be 'end' if all the transforms are disabled! */
8618 static image_transform *const image_transform_first = &PT;
8619
8620 static void
8621 transform_enable(const char *name)
8622 {
8623    /* Everything starts out enabled, so if we see an 'enable' disabled
8624     * everything else the first time round.
8625     */
8626    static int all_disabled = 0;
8627    int found_it = 0;
8628    image_transform *list = image_transform_first;
8629
8630    while (list != &image_transform_end)
8631    {
8632       if (strcmp(list->name, name) == 0)
8633       {
8634          list->enable = 1;
8635          found_it = 1;
8636       }
8637       else if (!all_disabled)
8638          list->enable = 0;
8639
8640       list = list->list;
8641    }
8642
8643    all_disabled = 1;
8644
8645    if (!found_it)
8646    {
8647       fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n",
8648          name);
8649       exit(99);
8650    }
8651 }
8652
8653 static void
8654 transform_disable(const char *name)
8655 {
8656    image_transform *list = image_transform_first;
8657
8658    while (list != &image_transform_end)
8659    {
8660       if (strcmp(list->name, name) == 0)
8661       {
8662          list->enable = 0;
8663          return;
8664       }
8665
8666       list = list->list;
8667    }
8668
8669    fprintf(stderr, "pngvalid: --transform-disable=%s: unknown transform\n",
8670       name);
8671    exit(99);
8672 }
8673
8674 static void
8675 image_transform_reset_count(void)
8676 {
8677    image_transform *next = image_transform_first;
8678    int count = 0;
8679
8680    while (next != &image_transform_end)
8681    {
8682       next->local_use = 0;
8683       next->next = 0;
8684       next = next->list;
8685       ++count;
8686    }
8687
8688    /* This can only happen if we every have more than 32 transforms (excluding
8689     * the end) in the list.
8690     */
8691    if (count > 32) abort();
8692 }
8693
8694 static int
8695 image_transform_test_counter(png_uint_32 counter, unsigned int max)
8696 {
8697    /* Test the list to see if there is any point contining, given a current
8698     * counter and a 'max' value.
8699     */
8700    image_transform *next = image_transform_first;
8701
8702    while (next != &image_transform_end)
8703    {
8704       /* For max 0 or 1 continue until the counter overflows: */
8705       counter >>= 1;
8706
8707       /* Continue if any entry hasn't reacked the max. */
8708       if (max > 1 && next->local_use < max)
8709          return 1;
8710       next = next->list;
8711    }
8712
8713    return max <= 1 && counter == 0;
8714 }
8715
8716 static png_uint_32
8717 image_transform_add(const image_transform **this, unsigned int max,
8718    png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos,
8719    png_byte colour_type, png_byte bit_depth)
8720 {
8721    for (;;) /* until we manage to add something */
8722    {
8723       png_uint_32 mask;
8724       image_transform *list;
8725
8726       /* Find the next counter value, if the counter is zero this is the start
8727        * of the list.  This routine always returns the current counter (not the
8728        * next) so it returns 0 at the end and expects 0 at the beginning.
8729        */
8730       if (counter == 0) /* first time */
8731       {
8732          image_transform_reset_count();
8733          if (max <= 1)
8734             counter = 1;
8735          else
8736             counter = random_32();
8737       }
8738       else /* advance the counter */
8739       {
8740          switch (max)
8741          {
8742             case 0:  ++counter; break;
8743             case 1:  counter <<= 1; break;
8744             default: counter = random_32(); break;
8745          }
8746       }
8747
8748       /* Now add all these items, if possible */
8749       *this = &image_transform_end;
8750       list = image_transform_first;
8751       mask = 1;
8752
8753       /* Go through the whole list adding anything that the counter selects: */
8754       while (list != &image_transform_end)
8755       {
8756          if ((counter & mask) != 0 && list->enable &&
8757              (max == 0 || list->local_use < max))
8758          {
8759             /* Candidate to add: */
8760             if (list->add(list, this, colour_type, bit_depth) || max == 0)
8761             {
8762                /* Added, so add to the name too. */
8763                *pos = safecat(name, sizeof_name, *pos, " +");
8764                *pos = safecat(name, sizeof_name, *pos, list->name);
8765             }
8766
8767             else
8768             {
8769                /* Not useful and max>0, so remove it from *this: */
8770                *this = list->next;
8771                list->next = 0;
8772
8773                /* And, since we know it isn't useful, stop it being added again
8774                 * in this run:
8775                 */
8776                list->local_use = max;
8777             }
8778          }
8779
8780          mask <<= 1;
8781          list = list->list;
8782       }
8783
8784       /* Now if anything was added we have something to do. */
8785       if (*this != &image_transform_end)
8786          return counter;
8787
8788       /* Nothing added, but was there anything in there to add? */
8789       if (!image_transform_test_counter(counter, max))
8790          return 0;
8791    }
8792 }
8793
8794 static void
8795 perform_transform_test(png_modifier *pm)
8796 {
8797    png_byte colour_type = 0;
8798    png_byte bit_depth = 0;
8799    unsigned int palette_number = 0;
8800
8801    while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg,
8802             pm->test_tRNS))
8803    {
8804       png_uint_32 counter = 0;
8805       size_t base_pos;
8806       char name[64];
8807
8808       base_pos = safecat(name, sizeof name, 0, "transform:");
8809
8810       for (;;)
8811       {
8812          size_t pos = base_pos;
8813          const image_transform *list = 0;
8814
8815          /* 'max' is currently hardwired to '1'; this should be settable on the
8816           * command line.
8817           */
8818          counter = image_transform_add(&list, 1/*max*/, counter,
8819             name, sizeof name, &pos, colour_type, bit_depth);
8820
8821          if (counter == 0)
8822             break;
8823
8824          /* The command line can change this to checking interlaced images. */
8825          do
8826          {
8827             pm->repeat = 0;
8828             transform_test(pm, FILEID(colour_type, bit_depth, palette_number,
8829                pm->interlace_type, 0, 0, 0), list, name);
8830
8831             if (fail(pm))
8832                return;
8833          }
8834          while (pm->repeat);
8835       }
8836    }
8837 }
8838 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
8839
8840 /********************************* GAMMA TESTS ********************************/
8841 #ifdef PNG_READ_GAMMA_SUPPORTED
8842 /* Reader callbacks and implementations, where they differ from the standard
8843  * ones.
8844  */
8845 typedef struct gamma_display
8846 {
8847    standard_display this;
8848
8849    /* Parameters */
8850    png_modifier*    pm;
8851    double           file_gamma;
8852    double           screen_gamma;
8853    double           background_gamma;
8854    png_byte         sbit;
8855    int              threshold_test;
8856    int              use_input_precision;
8857    int              scale16;
8858    int              expand16;
8859    int              do_background;
8860    png_color_16     background_color;
8861
8862    /* Local variables */
8863    double       maxerrout;
8864    double       maxerrpc;
8865    double       maxerrabs;
8866 } gamma_display;
8867
8868 #define ALPHA_MODE_OFFSET 4
8869
8870 static void
8871 gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
8872     double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
8873     int use_input_precision, int scale16, int expand16,
8874     int do_background, const png_color_16 *pointer_to_the_background_color,
8875     double background_gamma)
8876 {
8877    /* Standard fields */
8878    standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
8879       pm->use_update_info);
8880
8881    /* Parameter fields */
8882    dp->pm = pm;
8883    dp->file_gamma = file_gamma;
8884    dp->screen_gamma = screen_gamma;
8885    dp->background_gamma = background_gamma;
8886    dp->sbit = sbit;
8887    dp->threshold_test = threshold_test;
8888    dp->use_input_precision = use_input_precision;
8889    dp->scale16 = scale16;
8890    dp->expand16 = expand16;
8891    dp->do_background = do_background;
8892    if (do_background && pointer_to_the_background_color != 0)
8893       dp->background_color = *pointer_to_the_background_color;
8894    else
8895       memset(&dp->background_color, 0, sizeof dp->background_color);
8896
8897    /* Local variable fields */
8898    dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
8899 }
8900
8901 static void
8902 gamma_info_imp(gamma_display *dp, png_structp pp, png_infop pi)
8903 {
8904    /* Reuse the standard stuff as appropriate. */
8905    standard_info_part1(&dp->this, pp, pi);
8906
8907    /* If requested strip 16 to 8 bits - this is handled automagically below
8908     * because the output bit depth is read from the library.  Note that there
8909     * are interactions with sBIT but, internally, libpng makes sbit at most
8910     * PNG_MAX_GAMMA_8 prior to 1.7 when doing the following.
8911     */
8912    if (dp->scale16)
8913 #     ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
8914          png_set_scale_16(pp);
8915 #     else
8916          /* The following works both in 1.5.4 and earlier versions: */
8917 #        ifdef PNG_READ_16_TO_8_SUPPORTED
8918             png_set_strip_16(pp);
8919 #        else
8920             png_error(pp, "scale16 (16 to 8 bit conversion) not supported");
8921 #        endif
8922 #     endif
8923
8924    if (dp->expand16)
8925 #     ifdef PNG_READ_EXPAND_16_SUPPORTED
8926          png_set_expand_16(pp);
8927 #     else
8928          png_error(pp, "expand16 (8 to 16 bit conversion) not supported");
8929 #     endif
8930
8931    if (dp->do_background >= ALPHA_MODE_OFFSET)
8932    {
8933 #     ifdef PNG_READ_ALPHA_MODE_SUPPORTED
8934       {
8935          /* This tests the alpha mode handling, if supported. */
8936          int mode = dp->do_background - ALPHA_MODE_OFFSET;
8937
8938          /* The gamma value is the output gamma, and is in the standard,
8939           * non-inverted, represenation.  It provides a default for the PNG file
8940           * gamma, but since the file has a gAMA chunk this does not matter.
8941           */
8942          const double sg = dp->screen_gamma;
8943 #        ifndef PNG_FLOATING_POINT_SUPPORTED
8944             const png_fixed_point g = fix(sg);
8945 #        endif
8946
8947 #        ifdef PNG_FLOATING_POINT_SUPPORTED
8948             png_set_alpha_mode(pp, mode, sg);
8949 #        else
8950             png_set_alpha_mode_fixed(pp, mode, g);
8951 #        endif
8952
8953          /* However, for the standard Porter-Duff algorithm the output defaults
8954           * to be linear, so if the test requires non-linear output it must be
8955           * corrected here.
8956           */
8957          if (mode == PNG_ALPHA_STANDARD && sg != 1)
8958          {
8959 #           ifdef PNG_FLOATING_POINT_SUPPORTED
8960                png_set_gamma(pp, sg, dp->file_gamma);
8961 #           else
8962                png_fixed_point f = fix(dp->file_gamma);
8963                png_set_gamma_fixed(pp, g, f);
8964 #           endif
8965          }
8966       }
8967 #     else
8968          png_error(pp, "alpha mode handling not supported");
8969 #     endif
8970    }
8971
8972    else
8973    {
8974       /* Set up gamma processing. */
8975 #     ifdef PNG_FLOATING_POINT_SUPPORTED
8976          png_set_gamma(pp, dp->screen_gamma, dp->file_gamma);
8977 #     else
8978       {
8979          png_fixed_point s = fix(dp->screen_gamma);
8980          png_fixed_point f = fix(dp->file_gamma);
8981          png_set_gamma_fixed(pp, s, f);
8982       }
8983 #     endif
8984
8985       if (dp->do_background)
8986       {
8987 #     ifdef PNG_READ_BACKGROUND_SUPPORTED
8988          /* NOTE: this assumes the caller provided the correct background gamma!
8989           */
8990          const double bg = dp->background_gamma;
8991 #        ifndef PNG_FLOATING_POINT_SUPPORTED
8992             const png_fixed_point g = fix(bg);
8993 #        endif
8994
8995 #        ifdef PNG_FLOATING_POINT_SUPPORTED
8996             png_set_background(pp, &dp->background_color, dp->do_background,
8997                0/*need_expand*/, bg);
8998 #        else
8999             png_set_background_fixed(pp, &dp->background_color,
9000                dp->do_background, 0/*need_expand*/, g);
9001 #        endif
9002 #     else
9003          png_error(pp, "png_set_background not supported");
9004 #     endif
9005       }
9006    }
9007
9008    {
9009       int i = dp->this.use_update_info;
9010       /* Always do one call, even if use_update_info is 0. */
9011       do
9012          png_read_update_info(pp, pi);
9013       while (--i > 0);
9014    }
9015
9016    /* Now we may get a different cbRow: */
9017    standard_info_part2(&dp->this, pp, pi, 1 /*images*/);
9018 }
9019
9020 static void PNGCBAPI
9021 gamma_info(png_structp pp, png_infop pi)
9022 {
9023    gamma_info_imp(voidcast(gamma_display*, png_get_progressive_ptr(pp)), pp,
9024       pi);
9025 }
9026
9027 /* Validate a single component value - the routine gets the input and output
9028  * sample values as unscaled PNG component values along with a cache of all the
9029  * information required to validate the values.
9030  */
9031 typedef struct validate_info
9032 {
9033    png_const_structp  pp;
9034    gamma_display *dp;
9035    png_byte sbit;
9036    int use_input_precision;
9037    int do_background;
9038    int scale16;
9039    unsigned int sbit_max;
9040    unsigned int isbit_shift;
9041    unsigned int outmax;
9042
9043    double gamma_correction; /* Overall correction required. */
9044    double file_inverse;     /* Inverse of file gamma. */
9045    double screen_gamma;
9046    double screen_inverse;   /* Inverse of screen gamma. */
9047
9048    double background_red;   /* Linear background value, red or gray. */
9049    double background_green;
9050    double background_blue;
9051
9052    double maxabs;
9053    double maxpc;
9054    double maxcalc;
9055    double maxout;
9056    double maxout_total;     /* Total including quantization error */
9057    double outlog;
9058    int    outquant;
9059 }
9060 validate_info;
9061
9062 static void
9063 init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp,
9064     int in_depth, int out_depth)
9065 {
9066    const unsigned int outmax = (1U<<out_depth)-1;
9067
9068    vi->pp = pp;
9069    vi->dp = dp;
9070
9071    if (dp->sbit > 0 && dp->sbit < in_depth)
9072    {
9073       vi->sbit = dp->sbit;
9074       vi->isbit_shift = in_depth - dp->sbit;
9075    }
9076
9077    else
9078    {
9079       vi->sbit = (png_byte)in_depth;
9080       vi->isbit_shift = 0;
9081    }
9082
9083    vi->sbit_max = (1U << vi->sbit)-1;
9084
9085    /* This mimics the libpng threshold test, '0' is used to prevent gamma
9086     * correction in the validation test.
9087     */
9088    vi->screen_gamma = dp->screen_gamma;
9089    if (fabs(vi->screen_gamma-1) < PNG_GAMMA_THRESHOLD)
9090       vi->screen_gamma = vi->screen_inverse = 0;
9091    else
9092       vi->screen_inverse = 1/vi->screen_gamma;
9093
9094    vi->use_input_precision = dp->use_input_precision;
9095    vi->outmax = outmax;
9096    vi->maxabs = abserr(dp->pm, in_depth, out_depth);
9097    vi->maxpc = pcerr(dp->pm, in_depth, out_depth);
9098    vi->maxcalc = calcerr(dp->pm, in_depth, out_depth);
9099    vi->maxout = outerr(dp->pm, in_depth, out_depth);
9100    vi->outquant = output_quantization_factor(dp->pm, in_depth, out_depth);
9101    vi->maxout_total = vi->maxout + vi->outquant * .5;
9102    vi->outlog = outlog(dp->pm, in_depth, out_depth);
9103
9104    if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 ||
9105       (dp->this.colour_type == 3 && dp->this.is_transparent) ||
9106       ((dp->this.colour_type == 0 || dp->this.colour_type == 2) &&
9107        dp->this.has_tRNS))
9108    {
9109       vi->do_background = dp->do_background;
9110
9111       if (vi->do_background != 0)
9112       {
9113          const double bg_inverse = 1/dp->background_gamma;
9114          double r, g, b;
9115
9116          /* Caller must at least put the gray value into the red channel */
9117          r = dp->background_color.red; r /= outmax;
9118          g = dp->background_color.green; g /= outmax;
9119          b = dp->background_color.blue; b /= outmax;
9120
9121 #     if 0
9122          /* libpng doesn't do this optimization, if we do pngvalid will fail.
9123           */
9124          if (fabs(bg_inverse-1) >= PNG_GAMMA_THRESHOLD)
9125 #     endif
9126          {
9127             r = pow(r, bg_inverse);
9128             g = pow(g, bg_inverse);
9129             b = pow(b, bg_inverse);
9130          }
9131
9132          vi->background_red = r;
9133          vi->background_green = g;
9134          vi->background_blue = b;
9135       }
9136    }
9137    else /* Do not expect any background processing */
9138       vi->do_background = 0;
9139
9140    if (vi->do_background == 0)
9141       vi->background_red = vi->background_green = vi->background_blue = 0;
9142
9143    vi->gamma_correction = 1/(dp->file_gamma*dp->screen_gamma);
9144    if (fabs(vi->gamma_correction-1) < PNG_GAMMA_THRESHOLD)
9145       vi->gamma_correction = 0;
9146
9147    vi->file_inverse = 1/dp->file_gamma;
9148    if (fabs(vi->file_inverse-1) < PNG_GAMMA_THRESHOLD)
9149       vi->file_inverse = 0;
9150
9151    vi->scale16 = dp->scale16;
9152 }
9153
9154 /* This function handles composition of a single non-alpha component.  The
9155  * argument is the input sample value, in the range 0..1, and the alpha value.
9156  * The result is the composed, linear, input sample.  If alpha is less than zero
9157  * this is the alpha component and the function should not be called!
9158  */
9159 static double
9160 gamma_component_compose(int do_background, double input_sample, double alpha,
9161    double background, int *compose)
9162 {
9163    switch (do_background)
9164    {
9165 #ifdef PNG_READ_BACKGROUND_SUPPORTED
9166       case PNG_BACKGROUND_GAMMA_SCREEN:
9167       case PNG_BACKGROUND_GAMMA_FILE:
9168       case PNG_BACKGROUND_GAMMA_UNIQUE:
9169          /* Standard PNG background processing. */
9170          if (alpha < 1)
9171          {
9172             if (alpha > 0)
9173             {
9174                input_sample = input_sample * alpha + background * (1-alpha);
9175                if (compose != NULL)
9176                   *compose = 1;
9177             }
9178
9179             else
9180                input_sample = background;
9181          }
9182          break;
9183 #endif
9184
9185 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9186       case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
9187       case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
9188          /* The components are premultiplied in either case and the output is
9189           * gamma encoded (to get standard Porter-Duff we expect the output
9190           * gamma to be set to 1.0!)
9191           */
9192       case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
9193          /* The optimization is that the partial-alpha entries are linear
9194           * while the opaque pixels are gamma encoded, but this only affects the
9195           * output encoding.
9196           */
9197          if (alpha < 1)
9198          {
9199             if (alpha > 0)
9200             {
9201                input_sample *= alpha;
9202                if (compose != NULL)
9203                   *compose = 1;
9204             }
9205
9206             else
9207                input_sample = 0;
9208          }
9209          break;
9210 #endif
9211
9212       default:
9213          /* Standard cases where no compositing is done (so the component
9214           * value is already correct.)
9215           */
9216          UNUSED(alpha)
9217          UNUSED(background)
9218          UNUSED(compose)
9219          break;
9220    }
9221
9222    return input_sample;
9223 }
9224
9225 /* This API returns the encoded *input* component, in the range 0..1 */
9226 static double
9227 gamma_component_validate(const char *name, const validate_info *vi,
9228     const unsigned int id, const unsigned int od,
9229     const double alpha /* <0 for the alpha channel itself */,
9230     const double background /* component background value */)
9231 {
9232    const unsigned int isbit = id >> vi->isbit_shift;
9233    const unsigned int sbit_max = vi->sbit_max;
9234    const unsigned int outmax = vi->outmax;
9235    const int do_background = vi->do_background;
9236
9237    double i;
9238
9239    /* First check on the 'perfect' result obtained from the digitized input
9240     * value, id, and compare this against the actual digitized result, 'od'.
9241     * 'i' is the input result in the range 0..1:
9242     */
9243    i = isbit; i /= sbit_max;
9244
9245    /* Check for the fast route: if we don't do any background composition or if
9246     * this is the alpha channel ('alpha' < 0) or if the pixel is opaque then
9247     * just use the gamma_correction field to correct to the final output gamma.
9248     */
9249    if (alpha == 1 /* opaque pixel component */ || !do_background
9250 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9251       || do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_PNG
9252 #endif
9253       || (alpha < 0 /* alpha channel */
9254 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9255       && do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN
9256 #endif
9257       ))
9258    {
9259       /* Then get the gamma corrected version of 'i' and compare to 'od', any
9260        * error less than .5 is insignificant - just quantization of the output
9261        * value to the nearest digital value (nevertheless the error is still
9262        * recorded - it's interesting ;-)
9263        */
9264       double encoded_sample = i;
9265       double encoded_error;
9266
9267       /* alpha less than 0 indicates the alpha channel, which is always linear
9268        */
9269       if (alpha >= 0 && vi->gamma_correction > 0)
9270          encoded_sample = pow(encoded_sample, vi->gamma_correction);
9271       encoded_sample *= outmax;
9272
9273       encoded_error = fabs(od-encoded_sample);
9274
9275       if (encoded_error > vi->dp->maxerrout)
9276          vi->dp->maxerrout = encoded_error;
9277
9278       if (encoded_error < vi->maxout_total && encoded_error < vi->outlog)
9279          return i;
9280    }
9281
9282    /* The slow route - attempt to do linear calculations. */
9283    /* There may be an error, or background processing is required, so calculate
9284     * the actual sample values - unencoded light intensity values.  Note that in
9285     * practice these are not completely unencoded because they include a
9286     * 'viewing correction' to decrease or (normally) increase the perceptual
9287     * contrast of the image.  There's nothing we can do about this - we don't
9288     * know what it is - so assume the unencoded value is perceptually linear.
9289     */
9290    {
9291       double input_sample = i; /* In range 0..1 */
9292       double output, error, encoded_sample, encoded_error;
9293       double es_lo, es_hi;
9294       int compose = 0;           /* Set to one if composition done */
9295       int output_is_encoded;     /* Set if encoded to screen gamma */
9296       int log_max_error = 1;     /* Check maximum error values */
9297       png_const_charp pass = 0;  /* Reason test passes (or 0 for fail) */
9298
9299       /* Convert to linear light (with the above caveat.)  The alpha channel is
9300        * already linear.
9301        */
9302       if (alpha >= 0)
9303       {
9304          int tcompose;
9305
9306          if (vi->file_inverse > 0)
9307             input_sample = pow(input_sample, vi->file_inverse);
9308
9309          /* Handle the compose processing: */
9310          tcompose = 0;
9311          input_sample = gamma_component_compose(do_background, input_sample,
9312             alpha, background, &tcompose);
9313
9314          if (tcompose)
9315             compose = 1;
9316       }
9317
9318       /* And similarly for the output value, but we need to check the background
9319        * handling to linearize it correctly.
9320        */
9321       output = od;
9322       output /= outmax;
9323
9324       output_is_encoded = vi->screen_gamma > 0;
9325
9326       if (alpha < 0) /* The alpha channel */
9327       {
9328 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9329          if (do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN)
9330 #endif
9331          {
9332             /* In all other cases the output alpha channel is linear already,
9333              * don't log errors here, they are much larger in linear data.
9334              */
9335             output_is_encoded = 0;
9336             log_max_error = 0;
9337          }
9338       }
9339
9340 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9341       else /* A component */
9342       {
9343          if (do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED &&
9344             alpha < 1) /* the optimized case - linear output */
9345          {
9346             if (alpha > 0) log_max_error = 0;
9347             output_is_encoded = 0;
9348          }
9349       }
9350 #endif
9351
9352       if (output_is_encoded)
9353          output = pow(output, vi->screen_gamma);
9354
9355       /* Calculate (or recalculate) the encoded_sample value and repeat the
9356        * check above (unnecessary if we took the fast route, but harmless.)
9357        */
9358       encoded_sample = input_sample;
9359       if (output_is_encoded)
9360          encoded_sample = pow(encoded_sample, vi->screen_inverse);
9361       encoded_sample *= outmax;
9362
9363       encoded_error = fabs(od-encoded_sample);
9364
9365       /* Don't log errors in the alpha channel, or the 'optimized' case,
9366        * neither are significant to the overall perception.
9367        */
9368       if (log_max_error && encoded_error > vi->dp->maxerrout)
9369          vi->dp->maxerrout = encoded_error;
9370
9371       if (encoded_error < vi->maxout_total)
9372       {
9373          if (encoded_error < vi->outlog)
9374             return i;
9375
9376          /* Test passed but error is bigger than the log limit, record why the
9377           * test passed:
9378           */
9379          pass = "less than maxout:\n";
9380       }
9381
9382       /* i: the original input value in the range 0..1
9383        *
9384        * pngvalid calculations:
9385        *  input_sample: linear result; i linearized and composed, range 0..1
9386        *  encoded_sample: encoded result; input_sample scaled to ouput bit depth
9387        *
9388        * libpng calculations:
9389        *  output: linear result; od scaled to 0..1 and linearized
9390        *  od: encoded result from libpng
9391        */
9392
9393       /* Now we have the numbers for real errors, both absolute values as as a
9394        * percentage of the correct value (output):
9395        */
9396       error = fabs(input_sample-output);
9397
9398       if (log_max_error && error > vi->dp->maxerrabs)
9399          vi->dp->maxerrabs = error;
9400
9401       /* The following is an attempt to ignore the tendency of quantization to
9402        * dominate the percentage errors for lower result values:
9403        */
9404       if (log_max_error && input_sample > .5)
9405       {
9406          double percentage_error = error/input_sample;
9407          if (percentage_error > vi->dp->maxerrpc)
9408             vi->dp->maxerrpc = percentage_error;
9409       }
9410
9411       /* Now calculate the digitization limits for 'encoded_sample' using the
9412        * 'max' values.  Note that maxout is in the encoded space but maxpc and
9413        * maxabs are in linear light space.
9414        *
9415        * First find the maximum error in linear light space, range 0..1:
9416        */
9417       {
9418          double tmp = input_sample * vi->maxpc;
9419          if (tmp < vi->maxabs) tmp = vi->maxabs;
9420          /* If 'compose' is true the composition was done in linear space using
9421           * integer arithmetic.  This introduces an extra error of +/- 0.5 (at
9422           * least) in the integer space used.  'maxcalc' records this, taking
9423           * into account the possibility that even for 16 bit output 8 bit space
9424           * may have been used.
9425           */
9426          if (compose && tmp < vi->maxcalc) tmp = vi->maxcalc;
9427
9428          /* The 'maxout' value refers to the encoded result, to compare with
9429           * this encode input_sample adjusted by the maximum error (tmp) above.
9430           */
9431          es_lo = encoded_sample - vi->maxout;
9432
9433          if (es_lo > 0 && input_sample-tmp > 0)
9434          {
9435             double low_value = input_sample-tmp;
9436             if (output_is_encoded)
9437                low_value = pow(low_value, vi->screen_inverse);
9438             low_value *= outmax;
9439             if (low_value < es_lo) es_lo = low_value;
9440
9441             /* Quantize this appropriately: */
9442             es_lo = ceil(es_lo / vi->outquant - .5) * vi->outquant;
9443          }
9444
9445          else
9446             es_lo = 0;
9447
9448          es_hi = encoded_sample + vi->maxout;
9449
9450          if (es_hi < outmax && input_sample+tmp < 1)
9451          {
9452             double high_value = input_sample+tmp;
9453             if (output_is_encoded)
9454                high_value = pow(high_value, vi->screen_inverse);
9455             high_value *= outmax;
9456             if (high_value > es_hi) es_hi = high_value;
9457
9458             es_hi = floor(es_hi / vi->outquant + .5) * vi->outquant;
9459          }
9460
9461          else
9462             es_hi = outmax;
9463       }
9464
9465       /* The primary test is that the final encoded value returned by the
9466        * library should be between the two limits (inclusive) that were
9467        * calculated above.
9468        */
9469       if (od >= es_lo && od <= es_hi)
9470       {
9471          /* The value passes, but we may need to log the information anyway. */
9472          if (encoded_error < vi->outlog)
9473             return i;
9474
9475          if (pass == 0)
9476             pass = "within digitization limits:\n";
9477       }
9478
9479       {
9480          /* There has been an error in processing, or we need to log this
9481           * value.
9482           */
9483          double is_lo, is_hi;
9484
9485          /* pass is set at this point if either of the tests above would have
9486           * passed.  Don't do these additional tests here - just log the
9487           * original [es_lo..es_hi] values.
9488           */
9489          if (pass == 0 && vi->use_input_precision && vi->dp->sbit)
9490          {
9491             /* Ok, something is wrong - this actually happens in current libpng
9492              * 16-to-8 processing.  Assume that the input value (id, adjusted
9493              * for sbit) can be anywhere between value-.5 and value+.5 - quite a
9494              * large range if sbit is low.
9495              *
9496              * NOTE: at present because the libpng gamma table stuff has been
9497              * changed to use a rounding algorithm to correct errors in 8-bit
9498              * calculations the precise sbit calculation (a shift) has been
9499              * lost.  This can result in up to a +/-1 error in the presence of
9500              * an sbit less than the bit depth.
9501              */
9502 #           if PNG_LIBPNG_VER < 10700
9503 #              define SBIT_ERROR .5
9504 #           else
9505 #              define SBIT_ERROR 1.
9506 #           endif
9507             double tmp = (isbit - SBIT_ERROR)/sbit_max;
9508
9509             if (tmp <= 0)
9510                tmp = 0;
9511
9512             else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
9513                tmp = pow(tmp, vi->file_inverse);
9514
9515             tmp = gamma_component_compose(do_background, tmp, alpha, background,
9516                NULL);
9517
9518             if (output_is_encoded && tmp > 0 && tmp < 1)
9519                tmp = pow(tmp, vi->screen_inverse);
9520
9521             is_lo = ceil(outmax * tmp - vi->maxout_total);
9522
9523             if (is_lo < 0)
9524                is_lo = 0;
9525
9526             tmp = (isbit + SBIT_ERROR)/sbit_max;
9527
9528             if (tmp >= 1)
9529                tmp = 1;
9530
9531             else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
9532                tmp = pow(tmp, vi->file_inverse);
9533
9534             tmp = gamma_component_compose(do_background, tmp, alpha, background,
9535                NULL);
9536
9537             if (output_is_encoded && tmp > 0 && tmp < 1)
9538                tmp = pow(tmp, vi->screen_inverse);
9539
9540             is_hi = floor(outmax * tmp + vi->maxout_total);
9541
9542             if (is_hi > outmax)
9543                is_hi = outmax;
9544
9545             if (!(od < is_lo || od > is_hi))
9546             {
9547                if (encoded_error < vi->outlog)
9548                   return i;
9549
9550                pass = "within input precision limits:\n";
9551             }
9552
9553             /* One last chance.  If this is an alpha channel and the 16to8
9554              * option has been used and 'inaccurate' scaling is used then the
9555              * bit reduction is obtained by simply using the top 8 bits of the
9556              * value.
9557              *
9558              * This is only done for older libpng versions when the 'inaccurate'
9559              * (chop) method of scaling was used.
9560              */
9561 #           ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
9562 #              if PNG_LIBPNG_VER < 10504
9563                   /* This may be required for other components in the future,
9564                    * but at present the presence of gamma correction effectively
9565                    * prevents the errors in the component scaling (I don't quite
9566                    * understand why, but since it's better this way I care not
9567                    * to ask, JB 20110419.)
9568                    */
9569                   if (pass == 0 && alpha < 0 && vi->scale16 && vi->sbit > 8 &&
9570                      vi->sbit + vi->isbit_shift == 16)
9571                   {
9572                      tmp = ((id >> 8) - .5)/255;
9573
9574                      if (tmp > 0)
9575                      {
9576                         is_lo = ceil(outmax * tmp - vi->maxout_total);
9577                         if (is_lo < 0) is_lo = 0;
9578                      }
9579
9580                      else
9581                         is_lo = 0;
9582
9583                      tmp = ((id >> 8) + .5)/255;
9584
9585                      if (tmp < 1)
9586                      {
9587                         is_hi = floor(outmax * tmp + vi->maxout_total);
9588                         if (is_hi > outmax) is_hi = outmax;
9589                      }
9590
9591                      else
9592                         is_hi = outmax;
9593
9594                      if (!(od < is_lo || od > is_hi))
9595                      {
9596                         if (encoded_error < vi->outlog)
9597                            return i;
9598
9599                         pass = "within 8 bit limits:\n";
9600                      }
9601                   }
9602 #              endif
9603 #           endif
9604          }
9605          else /* !use_input_precision */
9606             is_lo = es_lo, is_hi = es_hi;
9607
9608          /* Attempt to output a meaningful error/warning message: the message
9609           * output depends on the background/composite operation being performed
9610           * because this changes what parameters were actually used above.
9611           */
9612          {
9613             size_t pos = 0;
9614             /* Need either 1/255 or 1/65535 precision here; 3 or 6 decimal
9615              * places.  Just use outmax to work out which.
9616              */
9617             int precision = (outmax >= 1000 ? 6 : 3);
9618             int use_input=1, use_background=0, do_compose=0;
9619             char msg[256];
9620
9621             if (pass != 0)
9622                pos = safecat(msg, sizeof msg, pos, "\n\t");
9623
9624             /* Set up the various flags, the output_is_encoded flag above
9625              * is also used below.  do_compose is just a double check.
9626              */
9627             switch (do_background)
9628             {
9629 #           ifdef PNG_READ_BACKGROUND_SUPPORTED
9630                case PNG_BACKGROUND_GAMMA_SCREEN:
9631                case PNG_BACKGROUND_GAMMA_FILE:
9632                case PNG_BACKGROUND_GAMMA_UNIQUE:
9633                   use_background = (alpha >= 0 && alpha < 1);
9634                   /*FALL THROUGH*/
9635 #           endif
9636 #           ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9637                case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
9638                case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
9639                case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
9640 #           endif /* ALPHA_MODE_SUPPORTED */
9641                do_compose = (alpha > 0 && alpha < 1);
9642                use_input = (alpha != 0);
9643                break;
9644
9645             default:
9646                break;
9647             }
9648
9649             /* Check the 'compose' flag */
9650             if (compose != do_compose)
9651                png_error(vi->pp, "internal error (compose)");
9652
9653             /* 'name' is the component name */
9654             pos = safecat(msg, sizeof msg, pos, name);
9655             pos = safecat(msg, sizeof msg, pos, "(");
9656             pos = safecatn(msg, sizeof msg, pos, id);
9657             if (use_input || pass != 0/*logging*/)
9658             {
9659                if (isbit != id)
9660                {
9661                   /* sBIT has reduced the precision of the input: */
9662                   pos = safecat(msg, sizeof msg, pos, ", sbit(");
9663                   pos = safecatn(msg, sizeof msg, pos, vi->sbit);
9664                   pos = safecat(msg, sizeof msg, pos, "): ");
9665                   pos = safecatn(msg, sizeof msg, pos, isbit);
9666                }
9667                pos = safecat(msg, sizeof msg, pos, "/");
9668                /* The output is either "id/max" or "id sbit(sbit): isbit/max" */
9669                pos = safecatn(msg, sizeof msg, pos, vi->sbit_max);
9670             }
9671             pos = safecat(msg, sizeof msg, pos, ")");
9672
9673             /* A component may have been multiplied (in linear space) by the
9674              * alpha value, 'compose' says whether this is relevant.
9675              */
9676             if (compose || pass != 0)
9677             {
9678                /* If any form of composition is being done report our
9679                 * calculated linear value here (the code above doesn't record
9680                 * the input value before composition is performed, so what
9681                 * gets reported is the value after composition.)
9682                 */
9683                if (use_input || pass != 0)
9684                {
9685                   if (vi->file_inverse > 0)
9686                   {
9687                      pos = safecat(msg, sizeof msg, pos, "^");
9688                      pos = safecatd(msg, sizeof msg, pos, vi->file_inverse, 2);
9689                   }
9690
9691                   else
9692                      pos = safecat(msg, sizeof msg, pos, "[linear]");
9693
9694                   pos = safecat(msg, sizeof msg, pos, "*(alpha)");
9695                   pos = safecatd(msg, sizeof msg, pos, alpha, precision);
9696                }
9697
9698                /* Now record the *linear* background value if it was used
9699                 * (this function is not passed the original, non-linear,
9700                 * value but it is contained in the test name.)
9701                 */
9702                if (use_background)
9703                {
9704                   pos = safecat(msg, sizeof msg, pos, use_input ? "+" : " ");
9705                   pos = safecat(msg, sizeof msg, pos, "(background)");
9706                   pos = safecatd(msg, sizeof msg, pos, background, precision);
9707                   pos = safecat(msg, sizeof msg, pos, "*");
9708                   pos = safecatd(msg, sizeof msg, pos, 1-alpha, precision);
9709                }
9710             }
9711
9712             /* Report the calculated value (input_sample) and the linearized
9713              * libpng value (output) unless this is just a component gamma
9714              * correction.
9715              */
9716             if (compose || alpha < 0 || pass != 0)
9717             {
9718                pos = safecat(msg, sizeof msg, pos,
9719                   pass != 0 ? " =\n\t" : " = ");
9720                pos = safecatd(msg, sizeof msg, pos, input_sample, precision);
9721                pos = safecat(msg, sizeof msg, pos, " (libpng: ");
9722                pos = safecatd(msg, sizeof msg, pos, output, precision);
9723                pos = safecat(msg, sizeof msg, pos, ")");
9724
9725                /* Finally report the output gamma encoding, if any. */
9726                if (output_is_encoded)
9727                {
9728                   pos = safecat(msg, sizeof msg, pos, " ^");
9729                   pos = safecatd(msg, sizeof msg, pos, vi->screen_inverse, 2);
9730                   pos = safecat(msg, sizeof msg, pos, "(to screen) =");
9731                }
9732
9733                else
9734                   pos = safecat(msg, sizeof msg, pos, " [screen is linear] =");
9735             }
9736
9737             if ((!compose && alpha >= 0) || pass != 0)
9738             {
9739                if (pass != 0) /* logging */
9740                   pos = safecat(msg, sizeof msg, pos, "\n\t[overall:");
9741
9742                /* This is the non-composition case, the internal linear
9743                 * values are irrelevant (though the log below will reveal
9744                 * them.)  Output a much shorter warning/error message and report
9745                 * the overall gamma correction.
9746                 */
9747                if (vi->gamma_correction > 0)
9748                {
9749                   pos = safecat(msg, sizeof msg, pos, " ^");
9750                   pos = safecatd(msg, sizeof msg, pos, vi->gamma_correction, 2);
9751                   pos = safecat(msg, sizeof msg, pos, "(gamma correction) =");
9752                }
9753
9754                else
9755                   pos = safecat(msg, sizeof msg, pos,
9756                      " [no gamma correction] =");
9757
9758                if (pass != 0)
9759                   pos = safecat(msg, sizeof msg, pos, "]");
9760             }
9761
9762             /* This is our calculated encoded_sample which should (but does
9763              * not) match od:
9764              */
9765             pos = safecat(msg, sizeof msg, pos, pass != 0 ? "\n\t" : " ");
9766             pos = safecatd(msg, sizeof msg, pos, is_lo, 1);
9767             pos = safecat(msg, sizeof msg, pos, " < ");
9768             pos = safecatd(msg, sizeof msg, pos, encoded_sample, 1);
9769             pos = safecat(msg, sizeof msg, pos, " (libpng: ");
9770             pos = safecatn(msg, sizeof msg, pos, od);
9771             pos = safecat(msg, sizeof msg, pos, ")");
9772             pos = safecat(msg, sizeof msg, pos, "/");
9773             pos = safecatn(msg, sizeof msg, pos, outmax);
9774             pos = safecat(msg, sizeof msg, pos, " < ");
9775             pos = safecatd(msg, sizeof msg, pos, is_hi, 1);
9776
9777             if (pass == 0) /* The error condition */
9778             {
9779 #              ifdef PNG_WARNINGS_SUPPORTED
9780                   png_warning(vi->pp, msg);
9781 #              else
9782                   store_warning(vi->pp, msg);
9783 #              endif
9784             }
9785
9786             else /* logging this value */
9787                store_verbose(&vi->dp->pm->this, vi->pp, pass, msg);
9788          }
9789       }
9790    }
9791
9792    return i;
9793 }
9794
9795 static void
9796 gamma_image_validate(gamma_display *dp, png_const_structp pp,
9797    png_infop pi)
9798 {
9799    /* Get some constants derived from the input and output file formats: */
9800    const png_store* const ps = dp->this.ps;
9801    const png_byte in_ct = dp->this.colour_type;
9802    const png_byte in_bd = dp->this.bit_depth;
9803    const png_uint_32 w = dp->this.w;
9804    const png_uint_32 h = dp->this.h;
9805    const size_t cbRow = dp->this.cbRow;
9806    const png_byte out_ct = png_get_color_type(pp, pi);
9807    const png_byte out_bd = png_get_bit_depth(pp, pi);
9808
9809    /* There are three sources of error, firstly the quantization in the
9810     * file encoding, determined by sbit and/or the file depth, secondly
9811     * the output (screen) gamma and thirdly the output file encoding.
9812     *
9813     * Since this API receives the screen and file gamma in double
9814     * precision it is possible to calculate an exact answer given an input
9815     * pixel value.  Therefore we assume that the *input* value is exact -
9816     * sample/maxsample - calculate the corresponding gamma corrected
9817     * output to the limits of double precision arithmetic and compare with
9818     * what libpng returns.
9819     *
9820     * Since the library must quantize the output to 8 or 16 bits there is
9821     * a fundamental limit on the accuracy of the output of +/-.5 - this
9822     * quantization limit is included in addition to the other limits
9823     * specified by the paramaters to the API.  (Effectively, add .5
9824     * everywhere.)
9825     *
9826     * The behavior of the 'sbit' paramter is defined by section 12.5
9827     * (sample depth scaling) of the PNG spec.  That section forces the
9828     * decoder to assume that the PNG values have been scaled if sBIT is
9829     * present:
9830     *
9831     *     png-sample = floor( input-sample * (max-out/max-in) + .5);
9832     *
9833     * This means that only a subset of the possible PNG values should
9834     * appear in the input. However, the spec allows the encoder to use a
9835     * variety of approximations to the above and doesn't require any
9836     * restriction of the values produced.
9837     *
9838     * Nevertheless the spec requires that the upper 'sBIT' bits of the
9839     * value stored in a PNG file be the original sample bits.
9840     * Consequently the code below simply scales the top sbit bits by
9841     * (1<<sbit)-1 to obtain an original sample value.
9842     *
9843     * Because there is limited precision in the input it is arguable that
9844     * an acceptable result is any valid result from input-.5 to input+.5.
9845     * The basic tests below do not do this, however if 'use_input_precision'
9846     * is set a subsequent test is performed above.
9847     */
9848    const unsigned int samples_per_pixel = (out_ct & 2U) ? 3U : 1U;
9849    int processing;
9850    png_uint_32 y;
9851    const store_palette_entry *in_palette = dp->this.palette;
9852    const int in_is_transparent = dp->this.is_transparent;
9853    int process_tRNS;
9854    int out_npalette = -1;
9855    int out_is_transparent = 0; /* Just refers to the palette case */
9856    store_palette out_palette;
9857    validate_info vi;
9858
9859    /* Check for row overwrite errors */
9860    store_image_check(dp->this.ps, pp, 0);
9861
9862    /* Supply the input and output sample depths here - 8 for an indexed image,
9863     * otherwise the bit depth.
9864     */
9865    init_validate_info(&vi, dp, pp, in_ct==3?8:in_bd, out_ct==3?8:out_bd);
9866
9867    processing = (vi.gamma_correction > 0 && !dp->threshold_test)
9868       || in_bd != out_bd || in_ct != out_ct || vi.do_background;
9869    process_tRNS = dp->this.has_tRNS && vi.do_background;
9870
9871    /* TODO: FIX THIS: MAJOR BUG!  If the transformations all happen inside
9872     * the palette there is no way of finding out, because libpng fails to
9873     * update the palette on png_read_update_info.  Indeed, libpng doesn't
9874     * even do the required work until much later, when it doesn't have any
9875     * info pointer.  Oops.  For the moment 'processing' is turned off if
9876     * out_ct is palette.
9877     */
9878    if (in_ct == 3 && out_ct == 3)
9879       processing = 0;
9880
9881    if (processing && out_ct == 3)
9882       out_is_transparent = read_palette(out_palette, &out_npalette, pp, pi);
9883
9884    for (y=0; y<h; ++y)
9885    {
9886       png_const_bytep pRow = store_image_row(ps, pp, 0, y);
9887       png_byte std[STANDARD_ROWMAX];
9888
9889       transform_row(pp, std, in_ct, in_bd, y);
9890
9891       if (processing)
9892       {
9893          unsigned int x;
9894
9895          for (x=0; x<w; ++x)
9896          {
9897             double alpha = 1; /* serves as a flag value */
9898
9899             /* Record the palette index for index images. */
9900             const unsigned int in_index =
9901                in_ct == 3 ? sample(std, 3, in_bd, x, 0, 0, 0) : 256;
9902             const unsigned int out_index =
9903                out_ct == 3 ? sample(std, 3, out_bd, x, 0, 0, 0) : 256;
9904
9905             /* Handle input alpha - png_set_background will cause the output
9906              * alpha to disappear so there is nothing to check.
9907              */
9908             if ((in_ct & PNG_COLOR_MASK_ALPHA) != 0 ||
9909                 (in_ct == 3 && in_is_transparent))
9910             {
9911                const unsigned int input_alpha = in_ct == 3 ?
9912                   dp->this.palette[in_index].alpha :
9913                   sample(std, in_ct, in_bd, x, samples_per_pixel, 0, 0);
9914
9915                unsigned int output_alpha = 65536 /* as a flag value */;
9916
9917                if (out_ct == 3)
9918                {
9919                   if (out_is_transparent)
9920                      output_alpha = out_palette[out_index].alpha;
9921                }
9922
9923                else if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0)
9924                   output_alpha = sample(pRow, out_ct, out_bd, x,
9925                      samples_per_pixel, 0, 0);
9926
9927                if (output_alpha != 65536)
9928                   alpha = gamma_component_validate("alpha", &vi, input_alpha,
9929                      output_alpha, -1/*alpha*/, 0/*background*/);
9930
9931                else /* no alpha in output */
9932                {
9933                   /* This is a copy of the calculation of 'i' above in order to
9934                    * have the alpha value to use in the background calculation.
9935                    */
9936                   alpha = input_alpha >> vi.isbit_shift;
9937                   alpha /= vi.sbit_max;
9938                }
9939             }
9940
9941             else if (process_tRNS)
9942             {
9943                /* alpha needs to be set appropriately for this pixel, it is
9944                 * currently 1 and needs to be 0 for an input pixel which matches
9945                 * the values in tRNS.
9946                 */
9947                switch (in_ct)
9948                {
9949                   case 0: /* gray */
9950                      if (sample(std, in_ct, in_bd, x, 0, 0, 0) ==
9951                            dp->this.transparent.red)
9952                         alpha = 0;
9953                      break;
9954
9955                   case 2: /* RGB */
9956                      if (sample(std, in_ct, in_bd, x, 0, 0, 0) ==
9957                            dp->this.transparent.red &&
9958                          sample(std, in_ct, in_bd, x, 1, 0, 0) ==
9959                            dp->this.transparent.green &&
9960                          sample(std, in_ct, in_bd, x, 2, 0, 0) ==
9961                            dp->this.transparent.blue)
9962                         alpha = 0;
9963                      break;
9964
9965                   default:
9966                      break;
9967                }
9968             }
9969
9970             /* Handle grayscale or RGB components. */
9971             if ((in_ct & PNG_COLOR_MASK_COLOR) == 0) /* grayscale */
9972                (void)gamma_component_validate("gray", &vi,
9973                   sample(std, in_ct, in_bd, x, 0, 0, 0),
9974                   sample(pRow, out_ct, out_bd, x, 0, 0, 0),
9975                   alpha/*component*/, vi.background_red);
9976             else /* RGB or palette */
9977             {
9978                (void)gamma_component_validate("red", &vi,
9979                   in_ct == 3 ? in_palette[in_index].red :
9980                      sample(std, in_ct, in_bd, x, 0, 0, 0),
9981                   out_ct == 3 ? out_palette[out_index].red :
9982                      sample(pRow, out_ct, out_bd, x, 0, 0, 0),
9983                   alpha/*component*/, vi.background_red);
9984
9985                (void)gamma_component_validate("green", &vi,
9986                   in_ct == 3 ? in_palette[in_index].green :
9987                      sample(std, in_ct, in_bd, x, 1, 0, 0),
9988                   out_ct == 3 ? out_palette[out_index].green :
9989                      sample(pRow, out_ct, out_bd, x, 1, 0, 0),
9990                   alpha/*component*/, vi.background_green);
9991
9992                (void)gamma_component_validate("blue", &vi,
9993                   in_ct == 3 ? in_palette[in_index].blue :
9994                      sample(std, in_ct, in_bd, x, 2, 0, 0),
9995                   out_ct == 3 ? out_palette[out_index].blue :
9996                      sample(pRow, out_ct, out_bd, x, 2, 0, 0),
9997                   alpha/*component*/, vi.background_blue);
9998             }
9999          }
10000       }
10001
10002       else if (memcmp(std, pRow, cbRow) != 0)
10003       {
10004          char msg[64];
10005
10006          /* No transform is expected on the threshold tests. */
10007          sprintf(msg, "gamma: below threshold row %lu changed",
10008             (unsigned long)y);
10009
10010          png_error(pp, msg);
10011       }
10012    } /* row (y) loop */
10013
10014    dp->this.ps->validated = 1;
10015 }
10016
10017 static void PNGCBAPI
10018 gamma_end(png_structp ppIn, png_infop pi)
10019 {
10020    png_const_structp pp = ppIn;
10021    gamma_display *dp = voidcast(gamma_display*, png_get_progressive_ptr(pp));
10022
10023    if (!dp->this.speed)
10024       gamma_image_validate(dp, pp, pi);
10025    else
10026       dp->this.ps->validated = 1;
10027 }
10028
10029 /* A single test run checking a gamma transformation.
10030  *
10031  * maxabs: maximum absolute error as a fraction
10032  * maxout: maximum output error in the output units
10033  * maxpc:  maximum percentage error (as a percentage)
10034  */
10035 static void
10036 gamma_test(png_modifier *pmIn, const png_byte colour_typeIn,
10037     const png_byte bit_depthIn, const int palette_numberIn,
10038     const int interlace_typeIn,
10039     const double file_gammaIn, const double screen_gammaIn,
10040     const png_byte sbitIn, const int threshold_testIn,
10041     const char *name,
10042     const int use_input_precisionIn, const int scale16In,
10043     const int expand16In, const int do_backgroundIn,
10044     const png_color_16 *bkgd_colorIn, double bkgd_gammaIn)
10045 {
10046    gamma_display d;
10047    context(&pmIn->this, fault);
10048
10049    gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn,
10050       palette_numberIn, interlace_typeIn, 0, 0, 0),
10051       file_gammaIn, screen_gammaIn, sbitIn,
10052       threshold_testIn, use_input_precisionIn, scale16In,
10053       expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn);
10054
10055    Try
10056    {
10057       png_structp pp;
10058       png_infop pi;
10059       gama_modification gama_mod;
10060       srgb_modification srgb_mod;
10061       sbit_modification sbit_mod;
10062
10063       /* For the moment don't use the png_modifier support here. */
10064       d.pm->encoding_counter = 0;
10065       modifier_set_encoding(d.pm); /* Just resets everything */
10066       d.pm->current_gamma = d.file_gamma;
10067
10068       /* Make an appropriate modifier to set the PNG file gamma to the
10069        * given gamma value and the sBIT chunk to the given precision.
10070        */
10071       d.pm->modifications = NULL;
10072       gama_modification_init(&gama_mod, d.pm, d.file_gamma);
10073       srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/);
10074       if (d.sbit > 0)
10075          sbit_modification_init(&sbit_mod, d.pm, d.sbit);
10076
10077       modification_reset(d.pm->modifications);
10078
10079       /* Get a png_struct for reading the image. */
10080       pp = set_modifier_for_read(d.pm, &pi, d.this.id, name);
10081       standard_palette_init(&d.this);
10082
10083       /* Introduce the correct read function. */
10084       if (d.pm->this.progressive)
10085       {
10086          /* Share the row function with the standard implementation. */
10087          png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row,
10088             gamma_end);
10089
10090          /* Now feed data into the reader until we reach the end: */
10091          modifier_progressive_read(d.pm, pp, pi);
10092       }
10093       else
10094       {
10095          /* modifier_read expects a png_modifier* */
10096          png_set_read_fn(pp, d.pm, modifier_read);
10097
10098          /* Check the header values: */
10099          png_read_info(pp, pi);
10100
10101          /* Process the 'info' requirements. Only one image is generated */
10102          gamma_info_imp(&d, pp, pi);
10103
10104          sequential_row(&d.this, pp, pi, -1, 0);
10105
10106          if (!d.this.speed)
10107             gamma_image_validate(&d, pp, pi);
10108          else
10109             d.this.ps->validated = 1;
10110       }
10111
10112       modifier_reset(d.pm);
10113
10114       if (d.pm->log && !d.threshold_test && !d.this.speed)
10115          fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n",
10116             d.this.bit_depth, colour_types[d.this.colour_type], name,
10117             d.maxerrout, d.maxerrabs, 100*d.maxerrpc);
10118
10119       /* Log the summary values too. */
10120       if (d.this.colour_type == 0 || d.this.colour_type == 4)
10121       {
10122          switch (d.this.bit_depth)
10123          {
10124          case 1:
10125             break;
10126
10127          case 2:
10128             if (d.maxerrout > d.pm->error_gray_2)
10129                d.pm->error_gray_2 = d.maxerrout;
10130
10131             break;
10132
10133          case 4:
10134             if (d.maxerrout > d.pm->error_gray_4)
10135                d.pm->error_gray_4 = d.maxerrout;
10136
10137             break;
10138
10139          case 8:
10140             if (d.maxerrout > d.pm->error_gray_8)
10141                d.pm->error_gray_8 = d.maxerrout;
10142
10143             break;
10144
10145          case 16:
10146             if (d.maxerrout > d.pm->error_gray_16)
10147                d.pm->error_gray_16 = d.maxerrout;
10148
10149             break;
10150
10151          default:
10152             png_error(pp, "bad bit depth (internal: 1)");
10153          }
10154       }
10155
10156       else if (d.this.colour_type == 2 || d.this.colour_type == 6)
10157       {
10158          switch (d.this.bit_depth)
10159          {
10160          case 8:
10161
10162             if (d.maxerrout > d.pm->error_color_8)
10163                d.pm->error_color_8 = d.maxerrout;
10164
10165             break;
10166
10167          case 16:
10168
10169             if (d.maxerrout > d.pm->error_color_16)
10170                d.pm->error_color_16 = d.maxerrout;
10171
10172             break;
10173
10174          default:
10175             png_error(pp, "bad bit depth (internal: 2)");
10176          }
10177       }
10178
10179       else if (d.this.colour_type == 3)
10180       {
10181          if (d.maxerrout > d.pm->error_indexed)
10182             d.pm->error_indexed = d.maxerrout;
10183       }
10184    }
10185
10186    Catch(fault)
10187       modifier_reset(voidcast(png_modifier*,(void*)fault));
10188 }
10189
10190 static void gamma_threshold_test(png_modifier *pm, png_byte colour_type,
10191     png_byte bit_depth, int interlace_type, double file_gamma,
10192     double screen_gamma)
10193 {
10194    size_t pos = 0;
10195    char name[64];
10196    pos = safecat(name, sizeof name, pos, "threshold ");
10197    pos = safecatd(name, sizeof name, pos, file_gamma, 3);
10198    pos = safecat(name, sizeof name, pos, "/");
10199    pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
10200
10201    (void)gamma_test(pm, colour_type, bit_depth, 0/*palette*/, interlace_type,
10202       file_gamma, screen_gamma, 0/*sBIT*/, 1/*threshold test*/, name,
10203       0 /*no input precision*/,
10204       0 /*no scale16*/, 0 /*no expand16*/, 0 /*no background*/, 0 /*hence*/,
10205       0 /*no background gamma*/);
10206 }
10207
10208 static void
10209 perform_gamma_threshold_tests(png_modifier *pm)
10210 {
10211    png_byte colour_type = 0;
10212    png_byte bit_depth = 0;
10213    unsigned int palette_number = 0;
10214
10215    /* Don't test more than one instance of each palette - it's pointless, in
10216     * fact this test is somewhat excessive since libpng doesn't make this
10217     * decision based on colour type or bit depth!
10218     *
10219     * CHANGED: now test two palettes and, as a side effect, images with and
10220     * without tRNS.
10221     */
10222    while (next_format(&colour_type, &bit_depth, &palette_number,
10223                       pm->test_lbg_gamma_threshold, pm->test_tRNS))
10224       if (palette_number < 2)
10225    {
10226       double test_gamma = 1.0;
10227       while (test_gamma >= .4)
10228       {
10229          /* There's little point testing the interlacing vs non-interlacing,
10230           * but this can be set from the command line.
10231           */
10232          gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
10233             test_gamma, 1/test_gamma);
10234          test_gamma *= .95;
10235       }
10236
10237       /* And a special test for sRGB */
10238       gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
10239           .45455, 2.2);
10240
10241       if (fail(pm))
10242          return;
10243    }
10244 }
10245
10246 static void gamma_transform_test(png_modifier *pm,
10247    const png_byte colour_type, const png_byte bit_depth,
10248    const int palette_number,
10249    const int interlace_type, const double file_gamma,
10250    const double screen_gamma, const png_byte sbit,
10251    const int use_input_precision, const int scale16)
10252 {
10253    size_t pos = 0;
10254    char name[64];
10255
10256    if (sbit != bit_depth && sbit != 0)
10257    {
10258       pos = safecat(name, sizeof name, pos, "sbit(");
10259       pos = safecatn(name, sizeof name, pos, sbit);
10260       pos = safecat(name, sizeof name, pos, ") ");
10261    }
10262
10263    else
10264       pos = safecat(name, sizeof name, pos, "gamma ");
10265
10266    if (scale16)
10267       pos = safecat(name, sizeof name, pos, "16to8 ");
10268
10269    pos = safecatd(name, sizeof name, pos, file_gamma, 3);
10270    pos = safecat(name, sizeof name, pos, "->");
10271    pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
10272
10273    gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
10274       file_gamma, screen_gamma, sbit, 0, name, use_input_precision,
10275       scale16, pm->test_gamma_expand16, 0 , 0, 0);
10276 }
10277
10278 static void perform_gamma_transform_tests(png_modifier *pm)
10279 {
10280    png_byte colour_type = 0;
10281    png_byte bit_depth = 0;
10282    unsigned int palette_number = 0;
10283
10284    while (next_format(&colour_type, &bit_depth, &palette_number,
10285                       pm->test_lbg_gamma_transform, pm->test_tRNS))
10286    {
10287       unsigned int i, j;
10288
10289       for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
10290          if (i != j)
10291          {
10292             gamma_transform_test(pm, colour_type, bit_depth, palette_number,
10293                pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], 0/*sBIT*/,
10294                pm->use_input_precision, 0 /*do not scale16*/);
10295
10296             if (fail(pm))
10297                return;
10298          }
10299    }
10300 }
10301
10302 static void perform_gamma_sbit_tests(png_modifier *pm)
10303 {
10304    png_byte sbit;
10305
10306    /* The only interesting cases are colour and grayscale, alpha is ignored here
10307     * for overall speed.  Only bit depths where sbit is less than the bit depth
10308     * are tested.
10309     */
10310    for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit)
10311    {
10312       png_byte colour_type = 0, bit_depth = 0;
10313       unsigned int npalette = 0;
10314
10315       while (next_format(&colour_type, &bit_depth, &npalette,
10316                          pm->test_lbg_gamma_sbit, pm->test_tRNS))
10317          if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 &&
10318             ((colour_type == 3 && sbit < 8) ||
10319             (colour_type != 3 && sbit < bit_depth)))
10320       {
10321          unsigned int i;
10322
10323          for (i=0; i<pm->ngamma_tests; ++i)
10324          {
10325             unsigned int j;
10326
10327             for (j=0; j<pm->ngamma_tests; ++j) if (i != j)
10328             {
10329                gamma_transform_test(pm, colour_type, bit_depth, npalette,
10330                   pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
10331                   sbit, pm->use_input_precision_sbit, 0 /*scale16*/);
10332
10333                if (fail(pm))
10334                   return;
10335             }
10336          }
10337       }
10338    }
10339 }
10340
10341 /* Note that this requires a 16 bit source image but produces 8 bit output, so
10342  * we only need the 16bit write support, but the 16 bit images are only
10343  * generated if DO_16BIT is defined.
10344  */
10345 #ifdef DO_16BIT
10346 static void perform_gamma_scale16_tests(png_modifier *pm)
10347 {
10348 #  ifndef PNG_MAX_GAMMA_8
10349 #     define PNG_MAX_GAMMA_8 11
10350 #  endif
10351 #  if defined PNG_MAX_GAMMA_8 || PNG_LIBPNG_VER < 10700
10352 #     define SBIT_16_TO_8 PNG_MAX_GAMMA_8
10353 #  else
10354 #     define SBIT_16_TO_8 16
10355 #  endif
10356    /* Include the alpha cases here. Note that sbit matches the internal value
10357     * used by the library - otherwise we will get spurious errors from the
10358     * internal sbit style approximation.
10359     *
10360     * The threshold test is here because otherwise the 16 to 8 conversion will
10361     * proceed *without* gamma correction, and the tests above will fail (but not
10362     * by much) - this could be fixed, it only appears with the -g option.
10363     */
10364    unsigned int i, j;
10365    for (i=0; i<pm->ngamma_tests; ++i)
10366    {
10367       for (j=0; j<pm->ngamma_tests; ++j)
10368       {
10369          if (i != j &&
10370              fabs(pm->gammas[j]/pm->gammas[i]-1) >= PNG_GAMMA_THRESHOLD)
10371          {
10372             gamma_transform_test(pm, 0, 16, 0, pm->interlace_type,
10373                1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
10374                pm->use_input_precision_16to8, 1 /*scale16*/);
10375
10376             if (fail(pm))
10377                return;
10378
10379             gamma_transform_test(pm, 2, 16, 0, pm->interlace_type,
10380                1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
10381                pm->use_input_precision_16to8, 1 /*scale16*/);
10382
10383             if (fail(pm))
10384                return;
10385
10386             gamma_transform_test(pm, 4, 16, 0, pm->interlace_type,
10387                1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
10388                pm->use_input_precision_16to8, 1 /*scale16*/);
10389
10390             if (fail(pm))
10391                return;
10392
10393             gamma_transform_test(pm, 6, 16, 0, pm->interlace_type,
10394                1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
10395                pm->use_input_precision_16to8, 1 /*scale16*/);
10396
10397             if (fail(pm))
10398                return;
10399          }
10400       }
10401    }
10402 }
10403 #endif /* 16 to 8 bit conversion */
10404
10405 #if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\
10406    defined(PNG_READ_ALPHA_MODE_SUPPORTED)
10407 static void gamma_composition_test(png_modifier *pm,
10408    const png_byte colour_type, const png_byte bit_depth,
10409    const int palette_number,
10410    const int interlace_type, const double file_gamma,
10411    const double screen_gamma,
10412    const int use_input_precision, const int do_background,
10413    const int expand_16)
10414 {
10415    size_t pos = 0;
10416    png_const_charp base;
10417    double bg;
10418    char name[128];
10419    png_color_16 background;
10420
10421    /* Make up a name and get an appropriate background gamma value. */
10422    switch (do_background)
10423    {
10424       default:
10425          base = "";
10426          bg = 4; /* should not be used */
10427          break;
10428       case PNG_BACKGROUND_GAMMA_SCREEN:
10429          base = " bckg(Screen):";
10430          bg = 1/screen_gamma;
10431          break;
10432       case PNG_BACKGROUND_GAMMA_FILE:
10433          base = " bckg(File):";
10434          bg = file_gamma;
10435          break;
10436       case PNG_BACKGROUND_GAMMA_UNIQUE:
10437          base = " bckg(Unique):";
10438          /* This tests the handling of a unique value, the math is such that the
10439           * value tends to be <1, but is neither screen nor file (even if they
10440           * match!)
10441           */
10442          bg = (file_gamma + screen_gamma) / 3;
10443          break;
10444 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
10445       case ALPHA_MODE_OFFSET + PNG_ALPHA_PNG:
10446          base = " alpha(PNG)";
10447          bg = 4; /* should not be used */
10448          break;
10449       case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
10450          base = " alpha(Porter-Duff)";
10451          bg = 4; /* should not be used */
10452          break;
10453       case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
10454          base = " alpha(Optimized)";
10455          bg = 4; /* should not be used */
10456          break;
10457       case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
10458          base = " alpha(Broken)";
10459          bg = 4; /* should not be used */
10460          break;
10461 #endif
10462    }
10463
10464    /* Use random background values - the background is always presented in the
10465     * output space (8 or 16 bit components).
10466     */
10467    if (expand_16 || bit_depth == 16)
10468    {
10469       png_uint_32 r = random_32();
10470
10471       background.red = (png_uint_16)r;
10472       background.green = (png_uint_16)(r >> 16);
10473       r = random_32();
10474       background.blue = (png_uint_16)r;
10475       background.gray = (png_uint_16)(r >> 16);
10476
10477       /* In earlier libpng versions, those where DIGITIZE is set, any background
10478        * gamma correction in the expand16 case was done using 8-bit gamma
10479        * correction tables, resulting in larger errors.  To cope with those
10480        * cases use a 16-bit background value which will handle this gamma
10481        * correction.
10482        */
10483 #     if DIGITIZE
10484          if (expand_16 && (do_background == PNG_BACKGROUND_GAMMA_UNIQUE ||
10485                            do_background == PNG_BACKGROUND_GAMMA_FILE) &&
10486             fabs(bg*screen_gamma-1) > PNG_GAMMA_THRESHOLD)
10487          {
10488             /* The background values will be looked up in an 8-bit table to do
10489              * the gamma correction, so only select values which are an exact
10490              * match for the 8-bit table entries:
10491              */
10492             background.red = (png_uint_16)((background.red >> 8) * 257);
10493             background.green = (png_uint_16)((background.green >> 8) * 257);
10494             background.blue = (png_uint_16)((background.blue >> 8) * 257);
10495             background.gray = (png_uint_16)((background.gray >> 8) * 257);
10496          }
10497 #     endif
10498    }
10499
10500    else /* 8 bit colors */
10501    {
10502       png_uint_32 r = random_32();
10503
10504       background.red = (png_byte)r;
10505       background.green = (png_byte)(r >> 8);
10506       background.blue = (png_byte)(r >> 16);
10507       background.gray = (png_byte)(r >> 24);
10508    }
10509
10510    background.index = 193; /* rgb(193,193,193) to detect errors */
10511
10512    if (!(colour_type & PNG_COLOR_MASK_COLOR))
10513    {
10514       /* Because, currently, png_set_background is always called with
10515        * 'need_expand' false in this case and because the gamma test itself
10516        * doesn't cause an expand to 8-bit for lower bit depths the colour must
10517        * be reduced to the correct range.
10518        */
10519       if (bit_depth < 8)
10520          background.gray &= (png_uint_16)((1U << bit_depth)-1);
10521
10522       /* Grayscale input, we do not convert to RGB (TBD), so we must set the
10523        * background to gray - else libpng seems to fail.
10524        */
10525       background.red = background.green = background.blue = background.gray;
10526    }
10527
10528    pos = safecat(name, sizeof name, pos, "gamma ");
10529    pos = safecatd(name, sizeof name, pos, file_gamma, 3);
10530    pos = safecat(name, sizeof name, pos, "->");
10531    pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
10532
10533    pos = safecat(name, sizeof name, pos, base);
10534    if (do_background < ALPHA_MODE_OFFSET)
10535    {
10536       /* Include the background color and gamma in the name: */
10537       pos = safecat(name, sizeof name, pos, "(");
10538       /* This assumes no expand gray->rgb - the current code won't handle that!
10539        */
10540       if (colour_type & PNG_COLOR_MASK_COLOR)
10541       {
10542          pos = safecatn(name, sizeof name, pos, background.red);
10543          pos = safecat(name, sizeof name, pos, ",");
10544          pos = safecatn(name, sizeof name, pos, background.green);
10545          pos = safecat(name, sizeof name, pos, ",");
10546          pos = safecatn(name, sizeof name, pos, background.blue);
10547       }
10548       else
10549          pos = safecatn(name, sizeof name, pos, background.gray);
10550       pos = safecat(name, sizeof name, pos, ")^");
10551       pos = safecatd(name, sizeof name, pos, bg, 3);
10552    }
10553
10554    gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
10555       file_gamma, screen_gamma, 0/*sBIT*/, 0, name, use_input_precision,
10556       0/*strip 16*/, expand_16, do_background, &background, bg);
10557 }
10558
10559
10560 static void
10561 perform_gamma_composition_tests(png_modifier *pm, int do_background,
10562    int expand_16)
10563 {
10564    png_byte colour_type = 0;
10565    png_byte bit_depth = 0;
10566    unsigned int palette_number = 0;
10567
10568    /* Skip the non-alpha cases - there is no setting of a transparency colour at
10569     * present.
10570     *
10571     * TODO: incorrect; the palette case sets tRNS and, now RGB and gray do,
10572     * however the palette case fails miserably so is commented out below.
10573     */
10574    while (next_format(&colour_type, &bit_depth, &palette_number,
10575                       pm->test_lbg_gamma_composition, pm->test_tRNS))
10576       if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0
10577 #if 0 /* TODO: FIXME */
10578           /*TODO: FIXME: this should work */
10579           || colour_type == 3
10580 #endif
10581           || (colour_type != 3 && palette_number != 0))
10582    {
10583       unsigned int i, j;
10584
10585       /* Don't skip the i==j case here - it's relevant. */
10586       for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
10587       {
10588          gamma_composition_test(pm, colour_type, bit_depth, palette_number,
10589             pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
10590             pm->use_input_precision, do_background, expand_16);
10591
10592          if (fail(pm))
10593             return;
10594       }
10595    }
10596 }
10597 #endif /* READ_BACKGROUND || READ_ALPHA_MODE */
10598
10599 static void
10600 init_gamma_errors(png_modifier *pm)
10601 {
10602    /* Use -1 to catch tests that were not actually run */
10603    pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = -1.;
10604    pm->error_color_8 = -1.;
10605    pm->error_indexed = -1.;
10606    pm->error_gray_16 = pm->error_color_16 = -1.;
10607 }
10608
10609 static void
10610 print_one(const char *leader, double err)
10611 {
10612    if (err != -1.)
10613       printf(" %s %.5f\n", leader, err);
10614 }
10615
10616 static void
10617 summarize_gamma_errors(png_modifier *pm, png_const_charp who, int low_bit_depth,
10618    int indexed)
10619 {
10620    fflush(stderr);
10621
10622    if (who)
10623       printf("\nGamma correction with %s:\n", who);
10624
10625    else
10626       printf("\nBasic gamma correction:\n");
10627
10628    if (low_bit_depth)
10629    {
10630       print_one(" 2 bit gray: ", pm->error_gray_2);
10631       print_one(" 4 bit gray: ", pm->error_gray_4);
10632       print_one(" 8 bit gray: ", pm->error_gray_8);
10633       print_one(" 8 bit color:", pm->error_color_8);
10634       if (indexed)
10635          print_one(" indexed:    ", pm->error_indexed);
10636    }
10637
10638    print_one("16 bit gray: ", pm->error_gray_16);
10639    print_one("16 bit color:", pm->error_color_16);
10640
10641    fflush(stdout);
10642 }
10643
10644 static void
10645 perform_gamma_test(png_modifier *pm, int summary)
10646 {
10647    /*TODO: remove this*/
10648    /* Save certain values for the temporary overrides below. */
10649    unsigned int calculations_use_input_precision =
10650       pm->calculations_use_input_precision;
10651 #  ifdef PNG_READ_BACKGROUND_SUPPORTED
10652       double maxout8 = pm->maxout8;
10653 #  endif
10654
10655    /* First some arbitrary no-transform tests: */
10656    if (!pm->this.speed && pm->test_gamma_threshold)
10657    {
10658       perform_gamma_threshold_tests(pm);
10659
10660       if (fail(pm))
10661          return;
10662    }
10663
10664    /* Now some real transforms. */
10665    if (pm->test_gamma_transform)
10666    {
10667       if (summary)
10668       {
10669          fflush(stderr);
10670          printf("Gamma correction error summary\n\n");
10671          printf("The printed value is the maximum error in the pixel values\n");
10672          printf("calculated by the libpng gamma correction code.  The error\n");
10673          printf("is calculated as the difference between the output pixel\n");
10674          printf("value (always an integer) and the ideal value from the\n");
10675          printf("libpng specification (typically not an integer).\n\n");
10676
10677          printf("Expect this value to be less than .5 for 8 bit formats,\n");
10678          printf("less than 1 for formats with fewer than 8 bits and a small\n");
10679          printf("number (typically less than 5) for the 16 bit formats.\n");
10680          printf("For performance reasons the value for 16 bit formats\n");
10681          printf("increases when the image file includes an sBIT chunk.\n");
10682          fflush(stdout);
10683       }
10684
10685       init_gamma_errors(pm);
10686       /*TODO: remove this.  Necessary because the current libpng
10687        * implementation works in 8 bits:
10688        */
10689       if (pm->test_gamma_expand16)
10690          pm->calculations_use_input_precision = 1;
10691       perform_gamma_transform_tests(pm);
10692       if (!calculations_use_input_precision)
10693          pm->calculations_use_input_precision = 0;
10694
10695       if (summary)
10696          summarize_gamma_errors(pm, 0/*who*/, 1/*low bit depth*/, 1/*indexed*/);
10697
10698       if (fail(pm))
10699          return;
10700    }
10701
10702    /* The sbit tests produce much larger errors: */
10703    if (pm->test_gamma_sbit)
10704    {
10705       init_gamma_errors(pm);
10706       perform_gamma_sbit_tests(pm);
10707
10708       if (summary)
10709          summarize_gamma_errors(pm, "sBIT", pm->sbitlow < 8U, 1/*indexed*/);
10710
10711       if (fail(pm))
10712          return;
10713    }
10714
10715 #ifdef DO_16BIT /* Should be READ_16BIT_SUPPORTED */
10716    if (pm->test_gamma_scale16)
10717    {
10718       /* The 16 to 8 bit strip operations: */
10719       init_gamma_errors(pm);
10720       perform_gamma_scale16_tests(pm);
10721
10722       if (summary)
10723       {
10724          fflush(stderr);
10725          printf("\nGamma correction with 16 to 8 bit reduction:\n");
10726          printf(" 16 bit gray:  %.5f\n", pm->error_gray_16);
10727          printf(" 16 bit color: %.5f\n", pm->error_color_16);
10728          fflush(stdout);
10729       }
10730
10731       if (fail(pm))
10732          return;
10733    }
10734 #endif
10735
10736 #ifdef PNG_READ_BACKGROUND_SUPPORTED
10737    if (pm->test_gamma_background)
10738    {
10739       init_gamma_errors(pm);
10740
10741       /*TODO: remove this.  Necessary because the current libpng
10742        * implementation works in 8 bits:
10743        */
10744       if (pm->test_gamma_expand16)
10745       {
10746          pm->calculations_use_input_precision = 1;
10747          pm->maxout8 = .499; /* because the 16 bit background is smashed */
10748       }
10749       perform_gamma_composition_tests(pm, PNG_BACKGROUND_GAMMA_UNIQUE,
10750          pm->test_gamma_expand16);
10751       if (!calculations_use_input_precision)
10752          pm->calculations_use_input_precision = 0;
10753       pm->maxout8 = maxout8;
10754
10755       if (summary)
10756          summarize_gamma_errors(pm, "background", 1, 0/*indexed*/);
10757
10758       if (fail(pm))
10759          return;
10760    }
10761 #endif
10762
10763 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
10764    if (pm->test_gamma_alpha_mode)
10765    {
10766       int do_background;
10767
10768       init_gamma_errors(pm);
10769
10770       /*TODO: remove this.  Necessary because the current libpng
10771        * implementation works in 8 bits:
10772        */
10773       if (pm->test_gamma_expand16)
10774          pm->calculations_use_input_precision = 1;
10775       for (do_background = ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD;
10776          do_background <= ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN && !fail(pm);
10777          ++do_background)
10778          perform_gamma_composition_tests(pm, do_background,
10779             pm->test_gamma_expand16);
10780       if (!calculations_use_input_precision)
10781          pm->calculations_use_input_precision = 0;
10782
10783       if (summary)
10784          summarize_gamma_errors(pm, "alpha mode", 1, 0/*indexed*/);
10785
10786       if (fail(pm))
10787          return;
10788    }
10789 #endif
10790 }
10791 #endif /* PNG_READ_GAMMA_SUPPORTED */
10792 #endif /* PNG_READ_SUPPORTED */
10793
10794 /* INTERLACE MACRO VALIDATION */
10795 /* This is copied verbatim from the specification, it is simply the pass
10796  * number in which each pixel in each 8x8 tile appears.  The array must
10797  * be indexed adam7[y][x] and notice that the pass numbers are based at
10798  * 1, not 0 - the base libpng uses.
10799  */
10800 static const
10801 png_byte adam7[8][8] =
10802 {
10803    { 1,6,4,6,2,6,4,6 },
10804    { 7,7,7,7,7,7,7,7 },
10805    { 5,6,5,6,5,6,5,6 },
10806    { 7,7,7,7,7,7,7,7 },
10807    { 3,6,4,6,3,6,4,6 },
10808    { 7,7,7,7,7,7,7,7 },
10809    { 5,6,5,6,5,6,5,6 },
10810    { 7,7,7,7,7,7,7,7 }
10811 };
10812
10813 /* This routine validates all the interlace support macros in png.h for
10814  * a variety of valid PNG widths and heights.  It uses a number of similarly
10815  * named internal routines that feed off the above array.
10816  */
10817 static png_uint_32
10818 png_pass_start_row(int pass)
10819 {
10820    int x, y;
10821    ++pass;
10822    for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
10823       return y;
10824    return 0xf;
10825 }
10826
10827 static png_uint_32
10828 png_pass_start_col(int pass)
10829 {
10830    int x, y;
10831    ++pass;
10832    for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
10833       return x;
10834    return 0xf;
10835 }
10836
10837 static int
10838 png_pass_row_shift(int pass)
10839 {
10840    int x, y, base=(-1), inc=8;
10841    ++pass;
10842    for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
10843    {
10844       if (base == (-1))
10845          base = y;
10846       else if (base == y)
10847          {}
10848       else if (inc == y-base)
10849          base=y;
10850       else if (inc == 8)
10851          inc = y-base, base=y;
10852       else if (inc != y-base)
10853          return 0xff; /* error - more than one 'inc' value! */
10854    }
10855
10856    if (base == (-1)) return 0xfe; /* error - no row in pass! */
10857
10858    /* The shift is always 1, 2 or 3 - no pass has all the rows! */
10859    switch (inc)
10860    {
10861 case 2: return 1;
10862 case 4: return 2;
10863 case 8: return 3;
10864 default: break;
10865    }
10866
10867    /* error - unrecognized 'inc' */
10868    return (inc << 8) + 0xfd;
10869 }
10870
10871 static int
10872 png_pass_col_shift(int pass)
10873 {
10874    int x, y, base=(-1), inc=8;
10875    ++pass;
10876    for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
10877    {
10878       if (base == (-1))
10879          base = x;
10880       else if (base == x)
10881          {}
10882       else if (inc == x-base)
10883          base=x;
10884       else if (inc == 8)
10885          inc = x-base, base=x;
10886       else if (inc != x-base)
10887          return 0xff; /* error - more than one 'inc' value! */
10888    }
10889
10890    if (base == (-1)) return 0xfe; /* error - no row in pass! */
10891
10892    /* The shift is always 1, 2 or 3 - no pass has all the rows! */
10893    switch (inc)
10894    {
10895 case 1: return 0; /* pass 7 has all the columns */
10896 case 2: return 1;
10897 case 4: return 2;
10898 case 8: return 3;
10899 default: break;
10900    }
10901
10902    /* error - unrecognized 'inc' */
10903    return (inc << 8) + 0xfd;
10904 }
10905
10906 static png_uint_32
10907 png_row_from_pass_row(png_uint_32 yIn, int pass)
10908 {
10909    /* By examination of the array: */
10910    switch (pass)
10911    {
10912 case 0: return yIn * 8;
10913 case 1: return yIn * 8;
10914 case 2: return yIn * 8 + 4;
10915 case 3: return yIn * 4;
10916 case 4: return yIn * 4 + 2;
10917 case 5: return yIn * 2;
10918 case 6: return yIn * 2 + 1;
10919 default: break;
10920    }
10921
10922    return 0xff; /* bad pass number */
10923 }
10924
10925 static png_uint_32
10926 png_col_from_pass_col(png_uint_32 xIn, int pass)
10927 {
10928    /* By examination of the array: */
10929    switch (pass)
10930    {
10931 case 0: return xIn * 8;
10932 case 1: return xIn * 8 + 4;
10933 case 2: return xIn * 4;
10934 case 3: return xIn * 4 + 2;
10935 case 4: return xIn * 2;
10936 case 5: return xIn * 2 + 1;
10937 case 6: return xIn;
10938 default: break;
10939    }
10940
10941    return 0xff; /* bad pass number */
10942 }
10943
10944 static int
10945 png_row_in_interlace_pass(png_uint_32 y, int pass)
10946 {
10947    /* Is row 'y' in pass 'pass'? */
10948    int x;
10949    y &= 7;
10950    ++pass;
10951    for (x=0; x<8; ++x) if (adam7[y][x] == pass)
10952       return 1;
10953
10954    return 0;
10955 }
10956
10957 static int
10958 png_col_in_interlace_pass(png_uint_32 x, int pass)
10959 {
10960    /* Is column 'x' in pass 'pass'? */
10961    int y;
10962    x &= 7;
10963    ++pass;
10964    for (y=0; y<8; ++y) if (adam7[y][x] == pass)
10965       return 1;
10966
10967    return 0;
10968 }
10969
10970 static png_uint_32
10971 png_pass_rows(png_uint_32 height, int pass)
10972 {
10973    png_uint_32 tiles = height>>3;
10974    png_uint_32 rows = 0;
10975    unsigned int x, y;
10976
10977    height &= 7;
10978    ++pass;
10979    for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
10980    {
10981       rows += tiles;
10982       if (y < height) ++rows;
10983       break; /* i.e. break the 'x', column, loop. */
10984    }
10985
10986    return rows;
10987 }
10988
10989 static png_uint_32
10990 png_pass_cols(png_uint_32 width, int pass)
10991 {
10992    png_uint_32 tiles = width>>3;
10993    png_uint_32 cols = 0;
10994    unsigned int x, y;
10995
10996    width &= 7;
10997    ++pass;
10998    for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
10999    {
11000       cols += tiles;
11001       if (x < width) ++cols;
11002       break; /* i.e. break the 'y', row, loop. */
11003    }
11004
11005    return cols;
11006 }
11007
11008 static void
11009 perform_interlace_macro_validation(void)
11010 {
11011    /* The macros to validate, first those that depend only on pass:
11012     *
11013     * PNG_PASS_START_ROW(pass)
11014     * PNG_PASS_START_COL(pass)
11015     * PNG_PASS_ROW_SHIFT(pass)
11016     * PNG_PASS_COL_SHIFT(pass)
11017     */
11018    int pass;
11019
11020    for (pass=0; pass<7; ++pass)
11021    {
11022       png_uint_32 m, f, v;
11023
11024       m = PNG_PASS_START_ROW(pass);
11025       f = png_pass_start_row(pass);
11026       if (m != f)
11027       {
11028          fprintf(stderr, "PNG_PASS_START_ROW(%d) = %u != %x\n", pass, m, f);
11029          exit(99);
11030       }
11031
11032       m = PNG_PASS_START_COL(pass);
11033       f = png_pass_start_col(pass);
11034       if (m != f)
11035       {
11036          fprintf(stderr, "PNG_PASS_START_COL(%d) = %u != %x\n", pass, m, f);
11037          exit(99);
11038       }
11039
11040       m = PNG_PASS_ROW_SHIFT(pass);
11041       f = png_pass_row_shift(pass);
11042       if (m != f)
11043       {
11044          fprintf(stderr, "PNG_PASS_ROW_SHIFT(%d) = %u != %x\n", pass, m, f);
11045          exit(99);
11046       }
11047
11048       m = PNG_PASS_COL_SHIFT(pass);
11049       f = png_pass_col_shift(pass);
11050       if (m != f)
11051       {
11052          fprintf(stderr, "PNG_PASS_COL_SHIFT(%d) = %u != %x\n", pass, m, f);
11053          exit(99);
11054       }
11055
11056       /* Macros that depend on the image or sub-image height too:
11057        *
11058        * PNG_PASS_ROWS(height, pass)
11059        * PNG_PASS_COLS(width, pass)
11060        * PNG_ROW_FROM_PASS_ROW(yIn, pass)
11061        * PNG_COL_FROM_PASS_COL(xIn, pass)
11062        * PNG_ROW_IN_INTERLACE_PASS(y, pass)
11063        * PNG_COL_IN_INTERLACE_PASS(x, pass)
11064        */
11065       for (v=0;;)
11066       {
11067          /* First the base 0 stuff: */
11068          m = PNG_ROW_FROM_PASS_ROW(v, pass);
11069          f = png_row_from_pass_row(v, pass);
11070          if (m != f)
11071          {
11072             fprintf(stderr, "PNG_ROW_FROM_PASS_ROW(%u, %d) = %u != %x\n",
11073                v, pass, m, f);
11074             exit(99);
11075          }
11076
11077          m = PNG_COL_FROM_PASS_COL(v, pass);
11078          f = png_col_from_pass_col(v, pass);
11079          if (m != f)
11080          {
11081             fprintf(stderr, "PNG_COL_FROM_PASS_COL(%u, %d) = %u != %x\n",
11082                v, pass, m, f);
11083             exit(99);
11084          }
11085
11086          m = PNG_ROW_IN_INTERLACE_PASS(v, pass);
11087          f = png_row_in_interlace_pass(v, pass);
11088          if (m != f)
11089          {
11090             fprintf(stderr, "PNG_ROW_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
11091                v, pass, m, f);
11092             exit(99);
11093          }
11094
11095          m = PNG_COL_IN_INTERLACE_PASS(v, pass);
11096          f = png_col_in_interlace_pass(v, pass);
11097          if (m != f)
11098          {
11099             fprintf(stderr, "PNG_COL_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
11100                v, pass, m, f);
11101             exit(99);
11102          }
11103
11104          /* Then the base 1 stuff: */
11105          ++v;
11106          m = PNG_PASS_ROWS(v, pass);
11107          f = png_pass_rows(v, pass);
11108          if (m != f)
11109          {
11110             fprintf(stderr, "PNG_PASS_ROWS(%u, %d) = %u != %x\n",
11111                v, pass, m, f);
11112             exit(99);
11113          }
11114
11115          m = PNG_PASS_COLS(v, pass);
11116          f = png_pass_cols(v, pass);
11117          if (m != f)
11118          {
11119             fprintf(stderr, "PNG_PASS_COLS(%u, %d) = %u != %x\n",
11120                v, pass, m, f);
11121             exit(99);
11122          }
11123
11124          /* Move to the next v - the stepping algorithm starts skipping
11125           * values above 1024.
11126           */
11127          if (v > 1024)
11128          {
11129             if (v == PNG_UINT_31_MAX)
11130                break;
11131
11132             v = (v << 1) ^ v;
11133             if (v >= PNG_UINT_31_MAX)
11134                v = PNG_UINT_31_MAX-1;
11135          }
11136       }
11137    }
11138 }
11139
11140 /* Test color encodings. These values are back-calculated from the published
11141  * chromaticities.  The values are accurate to about 14 decimal places; 15 are
11142  * given.  These values are much more accurate than the ones given in the spec,
11143  * which typically don't exceed 4 decimal places.  This allows testing of the
11144  * libpng code to its theoretical accuracy of 4 decimal places.  (If pngvalid
11145  * used the published errors the 'slack' permitted would have to be +/-.5E-4 or
11146  * more.)
11147  *
11148  * The png_modifier code assumes that encodings[0] is sRGB and treats it
11149  * specially: do not change the first entry in this list!
11150  */
11151 static const color_encoding test_encodings[] =
11152 {
11153 /* sRGB: must be first in this list! */
11154 /*gamma:*/ { 1/2.2,
11155 /*red:  */ { 0.412390799265959, 0.212639005871510, 0.019330818715592 },
11156 /*green:*/ { 0.357584339383878, 0.715168678767756, 0.119194779794626 },
11157 /*blue: */ { 0.180480788401834, 0.072192315360734, 0.950532152249660} },
11158 /* Kodak ProPhoto (wide gamut) */
11159 /*gamma:*/ { 1/1.6 /*approximate: uses 1.8 power law compared to sRGB 2.4*/,
11160 /*red:  */ { 0.797760489672303, 0.288071128229293, 0.000000000000000 },
11161 /*green:*/ { 0.135185837175740, 0.711843217810102, 0.000000000000000 },
11162 /*blue: */ { 0.031349349581525, 0.000085653960605, 0.825104602510460} },
11163 /* Adobe RGB (1998) */
11164 /*gamma:*/ { 1/(2+51./256),
11165 /*red:  */ { 0.576669042910131, 0.297344975250536, 0.027031361386412 },
11166 /*green:*/ { 0.185558237906546, 0.627363566255466, 0.070688852535827 },
11167 /*blue: */ { 0.188228646234995, 0.075291458493998, 0.991337536837639} },
11168 /* Adobe Wide Gamut RGB */
11169 /*gamma:*/ { 1/(2+51./256),
11170 /*red:  */ { 0.716500716779386, 0.258728243040113, 0.000000000000000 },
11171 /*green:*/ { 0.101020574397477, 0.724682314948566, 0.051211818965388 },
11172 /*blue: */ { 0.146774385252705, 0.016589442011321, 0.773892783545073} },
11173 /* Fake encoding which selects just the green channel */
11174 /*gamma:*/ { 1.45/2.2, /* the 'Mac' gamma */
11175 /*red:  */ { 0.716500716779386, 0.000000000000000, 0.000000000000000 },
11176 /*green:*/ { 0.101020574397477, 1.000000000000000, 0.051211818965388 },
11177 /*blue: */ { 0.146774385252705, 0.000000000000000, 0.773892783545073} },
11178 };
11179
11180 /* signal handler
11181  *
11182  * This attempts to trap signals and escape without crashing.  It needs a
11183  * context pointer so that it can throw an exception (call longjmp) to recover
11184  * from the condition; this is handled by making the png_modifier used by 'main'
11185  * into a global variable.
11186  */
11187 static png_modifier pm;
11188
11189 static void signal_handler(int signum)
11190 {
11191
11192    size_t pos = 0;
11193    char msg[64];
11194
11195    pos = safecat(msg, sizeof msg, pos, "caught signal: ");
11196
11197    switch (signum)
11198    {
11199       case SIGABRT:
11200          pos = safecat(msg, sizeof msg, pos, "abort");
11201          break;
11202
11203       case SIGFPE:
11204          pos = safecat(msg, sizeof msg, pos, "floating point exception");
11205          break;
11206
11207       case SIGILL:
11208          pos = safecat(msg, sizeof msg, pos, "illegal instruction");
11209          break;
11210
11211       case SIGINT:
11212          pos = safecat(msg, sizeof msg, pos, "interrupt");
11213          break;
11214
11215       case SIGSEGV:
11216          pos = safecat(msg, sizeof msg, pos, "invalid memory access");
11217          break;
11218
11219       case SIGTERM:
11220          pos = safecat(msg, sizeof msg, pos, "termination request");
11221          break;
11222
11223       default:
11224          pos = safecat(msg, sizeof msg, pos, "unknown ");
11225          pos = safecatn(msg, sizeof msg, pos, signum);
11226          break;
11227    }
11228
11229    store_log(&pm.this, NULL/*png_structp*/, msg, 1/*error*/);
11230
11231    /* And finally throw an exception so we can keep going, unless this is
11232     * SIGTERM in which case stop now.
11233     */
11234    if (signum != SIGTERM)
11235    {
11236       struct exception_context *the_exception_context =
11237          &pm.this.exception_context;
11238
11239       Throw &pm.this;
11240    }
11241
11242    else
11243       exit(1);
11244 }
11245
11246 /* main program */
11247 int main(int argc, char **argv)
11248 {
11249    int summary = 1;  /* Print the error summary at the end */
11250    int memstats = 0; /* Print memory statistics at the end */
11251
11252    /* Create the given output file on success: */
11253    const char *touch = NULL;
11254
11255    /* This is an array of standard gamma values (believe it or not I've seen
11256     * every one of these mentioned somewhere.)
11257     *
11258     * In the following list the most useful values are first!
11259     */
11260    static double
11261       gammas[]={2.2, 1.0, 2.2/1.45, 1.8, 1.5, 2.4, 2.5, 2.62, 2.9};
11262
11263    /* This records the command and arguments: */
11264    size_t cp = 0;
11265    char command[1024];
11266
11267    anon_context(&pm.this);
11268
11269    gnu_volatile(summary)
11270    gnu_volatile(memstats)
11271    gnu_volatile(touch)
11272
11273    /* Add appropriate signal handlers, just the ANSI specified ones: */
11274    signal(SIGABRT, signal_handler);
11275    signal(SIGFPE, signal_handler);
11276    signal(SIGILL, signal_handler);
11277    signal(SIGINT, signal_handler);
11278    signal(SIGSEGV, signal_handler);
11279    signal(SIGTERM, signal_handler);
11280
11281 #ifdef HAVE_FEENABLEEXCEPT
11282    /* Only required to enable FP exceptions on platforms where they start off
11283     * disabled; this is not necessary but if it is not done pngvalid will likely
11284     * end up ignoring FP conditions that other platforms fault.
11285     */
11286    feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
11287 #endif
11288
11289    modifier_init(&pm);
11290
11291    /* Preallocate the image buffer, because we know how big it needs to be,
11292     * note that, for testing purposes, it is deliberately mis-aligned by tag
11293     * bytes either side.  All rows have an additional five bytes of padding for
11294     * overwrite checking.
11295     */
11296    store_ensure_image(&pm.this, NULL, 2, TRANSFORM_ROWMAX, TRANSFORM_HEIGHTMAX);
11297
11298    /* Don't give argv[0], it's normally some horrible libtool string: */
11299    cp = safecat(command, sizeof command, cp, "pngvalid");
11300
11301    /* Default to error on warning: */
11302    pm.this.treat_warnings_as_errors = 1;
11303
11304    /* Default assume_16_bit_calculations appropriately; this tells the checking
11305     * code that 16-bit arithmetic is used for 8-bit samples when it would make a
11306     * difference.
11307     */
11308    pm.assume_16_bit_calculations = PNG_LIBPNG_VER >= 10700;
11309
11310    /* Currently 16 bit expansion happens at the end of the pipeline, so the
11311     * calculations are done in the input bit depth not the output.
11312     *
11313     * TODO: fix this
11314     */
11315    pm.calculations_use_input_precision = 1U;
11316
11317    /* Store the test gammas */
11318    pm.gammas = gammas;
11319    pm.ngammas = ARRAY_SIZE(gammas);
11320    pm.ngamma_tests = 0; /* default to off */
11321
11322    /* Low bit depth gray images don't do well in the gamma tests, until
11323     * this is fixed turn them off for some gamma cases:
11324     */
11325 #  ifdef PNG_WRITE_tRNS_SUPPORTED
11326       pm.test_tRNS = 1;
11327 #  endif
11328    pm.test_lbg = PNG_LIBPNG_VER >= 10600;
11329    pm.test_lbg_gamma_threshold = 1;
11330    pm.test_lbg_gamma_transform = PNG_LIBPNG_VER >= 10600;
11331    pm.test_lbg_gamma_sbit = 1;
11332    pm.test_lbg_gamma_composition = PNG_LIBPNG_VER >= 10700;
11333
11334    /* And the test encodings */
11335    pm.encodings = test_encodings;
11336    pm.nencodings = ARRAY_SIZE(test_encodings);
11337
11338 #  if PNG_LIBPNG_VER < 10700
11339       pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */
11340 #  else
11341       pm.sbitlow = 1U;
11342 #  endif
11343
11344    /* The following allows results to pass if they correspond to anything in the
11345     * transformed range [input-.5,input+.5]; this is is required because of the
11346     * way libpng treates the 16_TO_8 flag when building the gamma tables in
11347     * releases up to 1.6.0.
11348     *
11349     * TODO: review this
11350     */
11351    pm.use_input_precision_16to8 = 1U;
11352    pm.use_input_precision_sbit = 1U; /* because libpng now rounds sBIT */
11353
11354    /* Some default values (set the behavior for 'make check' here).
11355     * These values simply control the maximum error permitted in the gamma
11356     * transformations.  The practial limits for human perception are described
11357     * below (the setting for maxpc16), however for 8 bit encodings it isn't
11358     * possible to meet the accepted capabilities of human vision - i.e. 8 bit
11359     * images can never be good enough, regardless of encoding.
11360     */
11361    pm.maxout8 = .1;     /* Arithmetic error in *encoded* value */
11362    pm.maxabs8 = .00005; /* 1/20000 */
11363    pm.maxcalc8 = 1./255;  /* +/-1 in 8 bits for compose errors */
11364    pm.maxpc8 = .499;    /* I.e., .499% fractional error */
11365    pm.maxout16 = .499;  /* Error in *encoded* value */
11366    pm.maxabs16 = .00005;/* 1/20000 */
11367    pm.maxcalc16 =1./65535;/* +/-1 in 16 bits for compose errors */
11368 #  if PNG_LIBPNG_VER < 10700
11369       pm.maxcalcG = 1./((1<<PNG_MAX_GAMMA_8)-1);
11370 #  else
11371       pm.maxcalcG = 1./((1<<16)-1);
11372 #  endif
11373
11374    /* NOTE: this is a reasonable perceptual limit. We assume that humans can
11375     * perceive light level differences of 1% over a 100:1 range, so we need to
11376     * maintain 1 in 10000 accuracy (in linear light space), which is what the
11377     * following guarantees.  It also allows significantly higher errors at
11378     * higher 16 bit values, which is important for performance.  The actual
11379     * maximum 16 bit error is about +/-1.9 in the fixed point implementation but
11380     * this is only allowed for values >38149 by the following:
11381     */
11382    pm.maxpc16 = .005;   /* I.e., 1/200% - 1/20000 */
11383
11384    /* Now parse the command line options. */
11385    while (--argc >= 1)
11386    {
11387       int catmore = 0; /* Set if the argument has an argument. */
11388
11389       /* Record each argument for posterity: */
11390       cp = safecat(command, sizeof command, cp, " ");
11391       cp = safecat(command, sizeof command, cp, *++argv);
11392
11393       if (strcmp(*argv, "-v") == 0)
11394          pm.this.verbose = 1;
11395
11396       else if (strcmp(*argv, "-l") == 0)
11397          pm.log = 1;
11398
11399       else if (strcmp(*argv, "-q") == 0)
11400          summary = pm.this.verbose = pm.log = 0;
11401
11402       else if (strcmp(*argv, "-w") == 0 ||
11403                strcmp(*argv, "--strict") == 0)
11404          pm.this.treat_warnings_as_errors = 1; /* NOTE: this is the default! */
11405
11406       else if (strcmp(*argv, "--nostrict") == 0)
11407          pm.this.treat_warnings_as_errors = 0;
11408
11409       else if (strcmp(*argv, "--speed") == 0)
11410          pm.this.speed = 1, pm.ngamma_tests = pm.ngammas, pm.test_standard = 0,
11411             summary = 0;
11412
11413       else if (strcmp(*argv, "--memory") == 0)
11414          memstats = 1;
11415
11416       else if (strcmp(*argv, "--size") == 0)
11417          pm.test_size = 1;
11418
11419       else if (strcmp(*argv, "--nosize") == 0)
11420          pm.test_size = 0;
11421
11422       else if (strcmp(*argv, "--standard") == 0)
11423          pm.test_standard = 1;
11424
11425       else if (strcmp(*argv, "--nostandard") == 0)
11426          pm.test_standard = 0;
11427
11428       else if (strcmp(*argv, "--transform") == 0)
11429          pm.test_transform = 1;
11430
11431       else if (strcmp(*argv, "--notransform") == 0)
11432          pm.test_transform = 0;
11433
11434 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
11435       else if (strncmp(*argv, "--transform-disable=",
11436          sizeof "--transform-disable") == 0)
11437          {
11438          pm.test_transform = 1;
11439          transform_disable(*argv + sizeof "--transform-disable");
11440          }
11441
11442       else if (strncmp(*argv, "--transform-enable=",
11443          sizeof "--transform-enable") == 0)
11444          {
11445          pm.test_transform = 1;
11446          transform_enable(*argv + sizeof "--transform-enable");
11447          }
11448 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
11449
11450       else if (strcmp(*argv, "--gamma") == 0)
11451          {
11452          /* Just do two gamma tests here (2.2 and linear) for speed: */
11453          pm.ngamma_tests = 2U;
11454          pm.test_gamma_threshold = 1;
11455          pm.test_gamma_transform = 1;
11456          pm.test_gamma_sbit = 1;
11457          pm.test_gamma_scale16 = 1;
11458          pm.test_gamma_background = 1; /* composition */
11459          pm.test_gamma_alpha_mode = 1;
11460          }
11461
11462       else if (strcmp(*argv, "--nogamma") == 0)
11463          pm.ngamma_tests = 0;
11464
11465       else if (strcmp(*argv, "--gamma-threshold") == 0)
11466          pm.ngamma_tests = 2U, pm.test_gamma_threshold = 1;
11467
11468       else if (strcmp(*argv, "--nogamma-threshold") == 0)
11469          pm.test_gamma_threshold = 0;
11470
11471       else if (strcmp(*argv, "--gamma-transform") == 0)
11472          pm.ngamma_tests = 2U, pm.test_gamma_transform = 1;
11473
11474       else if (strcmp(*argv, "--nogamma-transform") == 0)
11475          pm.test_gamma_transform = 0;
11476
11477       else if (strcmp(*argv, "--gamma-sbit") == 0)
11478          pm.ngamma_tests = 2U, pm.test_gamma_sbit = 1;
11479
11480       else if (strcmp(*argv, "--nogamma-sbit") == 0)
11481          pm.test_gamma_sbit = 0;
11482
11483       else if (strcmp(*argv, "--gamma-16-to-8") == 0)
11484          pm.ngamma_tests = 2U, pm.test_gamma_scale16 = 1;
11485
11486       else if (strcmp(*argv, "--nogamma-16-to-8") == 0)
11487          pm.test_gamma_scale16 = 0;
11488
11489       else if (strcmp(*argv, "--gamma-background") == 0)
11490          pm.ngamma_tests = 2U, pm.test_gamma_background = 1;
11491
11492       else if (strcmp(*argv, "--nogamma-background") == 0)
11493          pm.test_gamma_background = 0;
11494
11495       else if (strcmp(*argv, "--gamma-alpha-mode") == 0)
11496          pm.ngamma_tests = 2U, pm.test_gamma_alpha_mode = 1;
11497
11498       else if (strcmp(*argv, "--nogamma-alpha-mode") == 0)
11499          pm.test_gamma_alpha_mode = 0;
11500
11501       else if (strcmp(*argv, "--expand16") == 0)
11502          pm.test_gamma_expand16 = 1;
11503
11504       else if (strcmp(*argv, "--noexpand16") == 0)
11505          pm.test_gamma_expand16 = 0;
11506
11507       else if (strcmp(*argv, "--low-depth-gray") == 0)
11508          pm.test_lbg = pm.test_lbg_gamma_threshold =
11509             pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
11510             pm.test_lbg_gamma_composition = 1;
11511
11512       else if (strcmp(*argv, "--nolow-depth-gray") == 0)
11513          pm.test_lbg = pm.test_lbg_gamma_threshold =
11514             pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
11515             pm.test_lbg_gamma_composition = 0;
11516
11517 #     ifdef PNG_WRITE_tRNS_SUPPORTED
11518          else if (strcmp(*argv, "--tRNS") == 0)
11519             pm.test_tRNS = 1;
11520 #     endif
11521
11522       else if (strcmp(*argv, "--notRNS") == 0)
11523          pm.test_tRNS = 0;
11524
11525       else if (strcmp(*argv, "--more-gammas") == 0)
11526          pm.ngamma_tests = 3U;
11527
11528       else if (strcmp(*argv, "--all-gammas") == 0)
11529          pm.ngamma_tests = pm.ngammas;
11530
11531       else if (strcmp(*argv, "--progressive-read") == 0)
11532          pm.this.progressive = 1;
11533
11534       else if (strcmp(*argv, "--use-update-info") == 0)
11535          ++pm.use_update_info; /* Can call multiple times */
11536
11537       else if (strcmp(*argv, "--interlace") == 0)
11538       {
11539 #        if CAN_WRITE_INTERLACE
11540             pm.interlace_type = PNG_INTERLACE_ADAM7;
11541 #        else /* !CAN_WRITE_INTERLACE */
11542             fprintf(stderr, "pngvalid: no write interlace support\n");
11543             return SKIP;
11544 #        endif /* !CAN_WRITE_INTERLACE */
11545       }
11546
11547       else if (strcmp(*argv, "--use-input-precision") == 0)
11548          pm.use_input_precision = 1U;
11549
11550       else if (strcmp(*argv, "--use-calculation-precision") == 0)
11551          pm.use_input_precision = 0;
11552
11553       else if (strcmp(*argv, "--calculations-use-input-precision") == 0)
11554          pm.calculations_use_input_precision = 1U;
11555
11556       else if (strcmp(*argv, "--assume-16-bit-calculations") == 0)
11557          pm.assume_16_bit_calculations = 1U;
11558
11559       else if (strcmp(*argv, "--calculations-follow-bit-depth") == 0)
11560          pm.calculations_use_input_precision =
11561             pm.assume_16_bit_calculations = 0;
11562
11563       else if (strcmp(*argv, "--exhaustive") == 0)
11564          pm.test_exhaustive = 1;
11565
11566       else if (argc > 1 && strcmp(*argv, "--sbitlow") == 0)
11567          --argc, pm.sbitlow = (png_byte)atoi(*++argv), catmore = 1;
11568
11569       else if (argc > 1 && strcmp(*argv, "--touch") == 0)
11570          --argc, touch = *++argv, catmore = 1;
11571
11572       else if (argc > 1 && strncmp(*argv, "--max", 5) == 0)
11573       {
11574          --argc;
11575
11576          if (strcmp(5+*argv, "abs8") == 0)
11577             pm.maxabs8 = atof(*++argv);
11578
11579          else if (strcmp(5+*argv, "abs16") == 0)
11580             pm.maxabs16 = atof(*++argv);
11581
11582          else if (strcmp(5+*argv, "calc8") == 0)
11583             pm.maxcalc8 = atof(*++argv);
11584
11585          else if (strcmp(5+*argv, "calc16") == 0)
11586             pm.maxcalc16 = atof(*++argv);
11587
11588          else if (strcmp(5+*argv, "out8") == 0)
11589             pm.maxout8 = atof(*++argv);
11590
11591          else if (strcmp(5+*argv, "out16") == 0)
11592             pm.maxout16 = atof(*++argv);
11593
11594          else if (strcmp(5+*argv, "pc8") == 0)
11595             pm.maxpc8 = atof(*++argv);
11596
11597          else if (strcmp(5+*argv, "pc16") == 0)
11598             pm.maxpc16 = atof(*++argv);
11599
11600          else
11601          {
11602             fprintf(stderr, "pngvalid: %s: unknown 'max' option\n", *argv);
11603             exit(99);
11604          }
11605
11606          catmore = 1;
11607       }
11608
11609       else if (strcmp(*argv, "--log8") == 0)
11610          --argc, pm.log8 = atof(*++argv), catmore = 1;
11611
11612       else if (strcmp(*argv, "--log16") == 0)
11613          --argc, pm.log16 = atof(*++argv), catmore = 1;
11614
11615 #ifdef PNG_SET_OPTION_SUPPORTED
11616       else if (strncmp(*argv, "--option=", 9) == 0)
11617       {
11618          /* Syntax of the argument is <option>:{on|off} */
11619          const char *arg = 9+*argv;
11620          unsigned char option=0, setting=0;
11621
11622 #ifdef PNG_ARM_NEON
11623          if (strncmp(arg, "arm-neon:", 9) == 0)
11624             option = PNG_ARM_NEON, arg += 9;
11625
11626          else
11627 #endif
11628 #ifdef PNG_EXTENSIONS
11629          if (strncmp(arg, "extensions:", 11) == 0)
11630             option = PNG_EXTENSIONS, arg += 11;
11631
11632          else
11633 #endif
11634 #ifdef PNG_MAXIMUM_INFLATE_WINDOW
11635          if (strncmp(arg, "max-inflate-window:", 19) == 0)
11636             option = PNG_MAXIMUM_INFLATE_WINDOW, arg += 19;
11637
11638          else
11639 #endif
11640          {
11641             fprintf(stderr, "pngvalid: %s: %s: unknown option\n", *argv, arg);
11642             exit(99);
11643          }
11644
11645          if (strcmp(arg, "off") == 0)
11646             setting = PNG_OPTION_OFF;
11647
11648          else if (strcmp(arg, "on") == 0)
11649             setting = PNG_OPTION_ON;
11650
11651          else
11652          {
11653             fprintf(stderr,
11654                "pngvalid: %s: %s: unknown setting (use 'on' or 'off')\n",
11655                *argv, arg);
11656             exit(99);
11657          }
11658
11659          pm.this.options[pm.this.noptions].option = option;
11660          pm.this.options[pm.this.noptions++].setting = setting;
11661       }
11662 #endif /* PNG_SET_OPTION_SUPPORTED */
11663
11664       else
11665       {
11666          fprintf(stderr, "pngvalid: %s: unknown argument\n", *argv);
11667          exit(99);
11668       }
11669
11670       if (catmore) /* consumed an extra *argv */
11671       {
11672          cp = safecat(command, sizeof command, cp, " ");
11673          cp = safecat(command, sizeof command, cp, *argv);
11674       }
11675    }
11676
11677    /* If pngvalid is run with no arguments default to a reasonable set of the
11678     * tests.
11679     */
11680    if (pm.test_standard == 0 && pm.test_size == 0 && pm.test_transform == 0 &&
11681       pm.ngamma_tests == 0)
11682    {
11683       /* Make this do all the tests done in the test shell scripts with the same
11684        * parameters, where possible.  The limitation is that all the progressive
11685        * read and interlace stuff has to be done in separate runs, so only the
11686        * basic 'standard' and 'size' tests are done.
11687        */
11688       pm.test_standard = 1;
11689       pm.test_size = 1;
11690       pm.test_transform = 1;
11691       pm.ngamma_tests = 2U;
11692    }
11693
11694    if (pm.ngamma_tests > 0 &&
11695       pm.test_gamma_threshold == 0 && pm.test_gamma_transform == 0 &&
11696       pm.test_gamma_sbit == 0 && pm.test_gamma_scale16 == 0 &&
11697       pm.test_gamma_background == 0 && pm.test_gamma_alpha_mode == 0)
11698    {
11699       pm.test_gamma_threshold = 1;
11700       pm.test_gamma_transform = 1;
11701       pm.test_gamma_sbit = 1;
11702       pm.test_gamma_scale16 = 1;
11703       pm.test_gamma_background = 1;
11704       pm.test_gamma_alpha_mode = 1;
11705    }
11706
11707    else if (pm.ngamma_tests == 0)
11708    {
11709       /* Nothing to test so turn everything off: */
11710       pm.test_gamma_threshold = 0;
11711       pm.test_gamma_transform = 0;
11712       pm.test_gamma_sbit = 0;
11713       pm.test_gamma_scale16 = 0;
11714       pm.test_gamma_background = 0;
11715       pm.test_gamma_alpha_mode = 0;
11716    }
11717
11718    Try
11719    {
11720       /* Make useful base images */
11721       make_transform_images(&pm);
11722
11723       /* Perform the standard and gamma tests. */
11724       if (pm.test_standard)
11725       {
11726          perform_interlace_macro_validation();
11727          perform_formatting_test(&pm.this);
11728 #        ifdef PNG_READ_SUPPORTED
11729             perform_standard_test(&pm);
11730 #        endif
11731          perform_error_test(&pm);
11732       }
11733
11734       /* Various oddly sized images: */
11735       if (pm.test_size)
11736       {
11737          make_size_images(&pm.this);
11738 #        ifdef PNG_READ_SUPPORTED
11739             perform_size_test(&pm);
11740 #        endif
11741       }
11742
11743 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
11744       /* Combinatorial transforms: */
11745       if (pm.test_transform)
11746          perform_transform_test(&pm);
11747 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
11748
11749 #ifdef PNG_READ_GAMMA_SUPPORTED
11750       if (pm.ngamma_tests > 0)
11751          perform_gamma_test(&pm, summary);
11752 #endif
11753    }
11754
11755    Catch_anonymous
11756    {
11757       fprintf(stderr, "pngvalid: test aborted (probably failed in cleanup)\n");
11758       if (!pm.this.verbose)
11759       {
11760          if (pm.this.error[0] != 0)
11761             fprintf(stderr, "pngvalid: first error: %s\n", pm.this.error);
11762
11763          fprintf(stderr, "pngvalid: run with -v to see what happened\n");
11764       }
11765       exit(1);
11766    }
11767
11768    if (summary)
11769    {
11770       printf("%s: %s (%s point arithmetic)\n",
11771          (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
11772             pm.this.nwarnings)) ? "FAIL" : "PASS",
11773          command,
11774 #if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || PNG_LIBPNG_VER < 10500
11775          "floating"
11776 #else
11777          "fixed"
11778 #endif
11779          );
11780    }
11781
11782    if (memstats)
11783    {
11784       printf("Allocated memory statistics (in bytes):\n"
11785          "\tread  %lu maximum single, %lu peak, %lu total\n"
11786          "\twrite %lu maximum single, %lu peak, %lu total\n",
11787          (unsigned long)pm.this.read_memory_pool.max_max,
11788          (unsigned long)pm.this.read_memory_pool.max_limit,
11789          (unsigned long)pm.this.read_memory_pool.max_total,
11790          (unsigned long)pm.this.write_memory_pool.max_max,
11791          (unsigned long)pm.this.write_memory_pool.max_limit,
11792          (unsigned long)pm.this.write_memory_pool.max_total);
11793    }
11794
11795    /* Do this here to provoke memory corruption errors in memory not directly
11796     * allocated by libpng - not a complete test, but better than nothing.
11797     */
11798    store_delete(&pm.this);
11799
11800    /* Error exit if there are any errors, and maybe if there are any
11801     * warnings.
11802     */
11803    if (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
11804        pm.this.nwarnings))
11805    {
11806       if (!pm.this.verbose)
11807          fprintf(stderr, "pngvalid: %s\n", pm.this.error);
11808
11809       fprintf(stderr, "pngvalid: %d errors, %d warnings\n", pm.this.nerrors,
11810           pm.this.nwarnings);
11811
11812       exit(1);
11813    }
11814
11815    /* Success case. */
11816    if (touch != NULL)
11817    {
11818       FILE *fsuccess = fopen(touch, "wt");
11819
11820       if (fsuccess != NULL)
11821       {
11822          int error = 0;
11823          fprintf(fsuccess, "PNG validation succeeded\n");
11824          fflush(fsuccess);
11825          error = ferror(fsuccess);
11826
11827          if (fclose(fsuccess) || error)
11828          {
11829             fprintf(stderr, "%s: write failed\n", touch);
11830             exit(1);
11831          }
11832       }
11833
11834       else
11835       {
11836          fprintf(stderr, "%s: open failed\n", touch);
11837          exit(1);
11838       }
11839    }
11840
11841    /* This is required because some very minimal configurations do not use it:
11842     */
11843    UNUSED(fail)
11844    return 0;
11845 }
11846 #else /* write or low level APIs not supported */
11847 int main(void)
11848 {
11849    fprintf(stderr,
11850       "pngvalid: no low level write support in libpng, all tests skipped\n");
11851    /* So the test is skipped: */
11852    return SKIP;
11853 }
11854 #endif