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