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