2 /* pngvalid.c - validate libpng by constructing then reading png files.
4 * Last changed in libpng 1.6.1 [March 28, 2013]
5 * Copyright (c) 2013 Glenn Randers-Pehrson
6 * Written by John Cunningham Bowler
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
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.
18 * The program can be modified and extended to test the correctness of
19 * transformations performed by libpng.
22 #define _POSIX_SOURCE 1
23 #define _ISOC99_SOURCE 1 /* For floating point */
24 #define _GNU_SOURCE 1 /* For the floating point exception extension */
29 #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
33 #ifdef HAVE_FEENABLEEXCEPT /* from config.h, if included */
37 /* Define the following to use this test against your installed libpng, rather
38 * than the one being built here:
40 #ifdef PNG_FREESTANDING_TESTS
43 # include "../../png.h"
46 #ifdef PNG_WRITE_SUPPORTED /* else pngvalid can do nothing */
48 #if PNG_LIBPNG_VER < 10500
49 /* This deliberately lacks the PNG_CONST. */
50 typedef png_byte
*png_const_bytep
;
52 /* This is copied from 1.5.1 png.h: */
53 #define PNG_INTERLACE_ADAM7_PASSES 7
54 #define PNG_PASS_START_ROW(pass) (((1U&~(pass))<<(3-((pass)>>1)))&7)
55 #define PNG_PASS_START_COL(pass) (((1U& (pass))<<(3-(((pass)+1)>>1)))&7)
56 #define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3)
57 #define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3)
58 #define PNG_PASS_ROWS(height, pass) (((height)+(((1<<PNG_PASS_ROW_SHIFT(pass))\
59 -1)-PNG_PASS_START_ROW(pass)))>>PNG_PASS_ROW_SHIFT(pass))
60 #define PNG_PASS_COLS(width, pass) (((width)+(((1<<PNG_PASS_COL_SHIFT(pass))\
61 -1)-PNG_PASS_START_COL(pass)))>>PNG_PASS_COL_SHIFT(pass))
62 #define PNG_ROW_FROM_PASS_ROW(yIn, pass) \
63 (((yIn)<<PNG_PASS_ROW_SHIFT(pass))+PNG_PASS_START_ROW(pass))
64 #define PNG_COL_FROM_PASS_COL(xIn, pass) \
65 (((xIn)<<PNG_PASS_COL_SHIFT(pass))+PNG_PASS_START_COL(pass))
66 #define PNG_PASS_MASK(pass,off) ( \
67 ((0x110145AFU>>(((7-(off))-(pass))<<2)) & 0xFU) | \
68 ((0x01145AF0U>>(((7-(off))-(pass))<<2)) & 0xF0U))
69 #define PNG_ROW_IN_INTERLACE_PASS(y, pass) \
70 ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1)
71 #define PNG_COL_IN_INTERLACE_PASS(x, pass) \
72 ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1)
74 /* These are needed too for the default build: */
75 #define PNG_WRITE_16BIT_SUPPORTED
76 #define PNG_READ_16BIT_SUPPORTED
78 /* This comes from pnglibconf.h afer 1.5: */
79 #define PNG_FP_1 100000
80 #define PNG_GAMMA_THRESHOLD_FIXED\
81 ((png_fixed_point)(PNG_GAMMA_THRESHOLD * PNG_FP_1))
84 #if PNG_LIBPNG_VER < 10600
85 /* 1.6.0 constifies many APIs, the following exists to allow pngvalid to be
86 * compiled against earlier versions.
88 # define png_const_structp png_structp
91 #include <zlib.h> /* For crc32 */
93 #include <float.h> /* For floating point constants */
94 #include <stdlib.h> /* For malloc */
95 #include <string.h> /* For memcpy, memset */
96 #include <math.h> /* For floor */
98 /* Unused formal parameter errors are removed using the following macro which is
99 * expected to have no bad effects on performance.
102 # if defined(__GNUC__) || defined(_MSC_VER)
103 # define UNUSED(param) (void)param;
105 # define UNUSED(param)
109 /***************************** EXCEPTION HANDLING *****************************/
110 #ifdef PNG_FREESTANDING_TESTS
111 # include <cexcept.h>
113 # include "../visupng/cexcept.h"
117 # define this not_the_cpp_this
118 # define new not_the_cpp_new
119 # define voidcast(type, value) static_cast<type>(value)
121 # define voidcast(type, value) (value)
122 #endif /* __cplusplus */
125 define_exception_type(struct png_store
*);
127 /* The following are macros to reduce typing everywhere where the well known
128 * name 'the_exception_context' must be defined.
130 #define anon_context(ps) struct exception_context *the_exception_context = \
131 &(ps)->exception_context
132 #define context(ps,fault) anon_context(ps); png_store *fault
134 /******************************* UTILITIES ************************************/
135 /* Error handling is particularly problematic in production code - error
136 * handlers often themselves have bugs which lead to programs that detect
137 * minor errors crashing. The following functions deal with one very
138 * common class of errors in error handlers - attempting to format error or
139 * warning messages into buffers that are too small.
141 static size_t safecat(char *buffer
, size_t bufsize
, size_t pos
,
144 while (pos
< bufsize
&& cat
!= NULL
&& *cat
!= 0)
145 buffer
[pos
++] = *cat
++;
154 static size_t safecatn(char *buffer
, size_t bufsize
, size_t pos
, int n
)
157 sprintf(number
, "%d", n
);
158 return safecat(buffer
, bufsize
, pos
, number
);
161 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
162 static size_t safecatd(char *buffer
, size_t bufsize
, size_t pos
, double d
,
166 sprintf(number
, "%.*f", precision
, d
);
167 return safecat(buffer
, bufsize
, pos
, number
);
171 static PNG_CONST
char invalid
[] = "invalid";
172 static PNG_CONST
char sep
[] = ": ";
174 static PNG_CONST
char *colour_types
[8] =
176 "grayscale", invalid
, "truecolour", "indexed-colour",
177 "grayscale with alpha", invalid
, "truecolour with alpha", invalid
180 #ifdef PNG_READ_SUPPORTED
181 /* Convert a double precision value to fixed point. */
182 static png_fixed_point
185 d
= floor(d
* PNG_FP_1
+ .5);
186 return (png_fixed_point
)d
;
188 #endif /* PNG_READ_SUPPORTED */
190 /* Generate random bytes. This uses a boring repeatable algorithm and it
191 * is implemented here so that it gives the same set of numbers on every
192 * architecture. It's a linear congruential generator (Knuth or Sedgewick
193 * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
194 * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise
198 make_random_bytes(png_uint_32
* seed
, void* pv
, size_t size
)
200 png_uint_32 u0
= seed
[0], u1
= seed
[1];
201 png_bytep bytes
= voidcast(png_bytep
, pv
);
203 /* There are thirty three bits, the next bit in the sequence is bit-33 XOR
204 * bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
207 for (i
=0; i
<size
; ++i
)
209 /* First generate 8 new bits then shift them in at the end. */
210 png_uint_32 u
= ((u0
>> (20-8)) ^ ((u1
<< 7) | (u0
>> (32-7)))) & 0xff;
215 *bytes
++ = (png_byte
)u
;
223 make_four_random_bytes(png_uint_32
* seed
, png_bytep bytes
)
225 make_random_bytes(seed
, bytes
, 4);
228 #ifdef PNG_READ_SUPPORTED
230 randomize(void *pv
, size_t size
)
232 static png_uint_32 random_seed
[2] = {0x56789abc, 0xd};
233 make_random_bytes(random_seed
, pv
, size
);
236 #define RANDOMIZE(this) randomize(&(this), sizeof (this))
239 random_mod(unsigned int max
)
245 return x
% max
; /* 0 .. max-1 */
248 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
259 #endif /* PNG_READ_SUPPORTED */
261 /* A numeric ID based on PNG file characteristics. The 'do_interlace' field
262 * simply records whether pngvalid did the interlace itself or whether it
263 * was done by libpng. Width and height must be less than 256. 'palette' is an
264 * index of the palette to use for formats with a palette (0 otherwise.)
266 #define FILEID(col, depth, palette, interlace, width, height, do_interlace) \
267 ((png_uint_32)((col) + ((depth)<<3) + ((palette)<<8) + ((interlace)<<13) + \
268 (((do_interlace)!=0)<<15) + ((width)<<16) + ((height)<<24)))
270 #define COL_FROM_ID(id) ((png_byte)((id)& 0x7U))
271 #define DEPTH_FROM_ID(id) ((png_byte)(((id) >> 3) & 0x1fU))
272 #define PALETTE_FROM_ID(id) (((id) >> 8) & 0x1f)
273 #define INTERLACE_FROM_ID(id) ((int)(((id) >> 13) & 0x3))
274 #define DO_INTERLACE_FROM_ID(id) ((int)(((id)>>15) & 1))
275 #define WIDTH_FROM_ID(id) (((id)>>16) & 0xff)
276 #define HEIGHT_FROM_ID(id) (((id)>>24) & 0xff)
278 /* Utility to construct a standard name for a standard image. */
280 standard_name(char *buffer
, size_t bufsize
, size_t pos
, png_byte colour_type
,
281 int bit_depth
, unsigned int npalette
, int interlace_type
,
282 png_uint_32 w
, png_uint_32 h
, int do_interlace
)
284 pos
= safecat(buffer
, bufsize
, pos
, colour_types
[colour_type
]);
287 pos
= safecat(buffer
, bufsize
, pos
, "[");
288 pos
= safecatn(buffer
, bufsize
, pos
, npalette
);
289 pos
= safecat(buffer
, bufsize
, pos
, "]");
291 pos
= safecat(buffer
, bufsize
, pos
, " ");
292 pos
= safecatn(buffer
, bufsize
, pos
, bit_depth
);
293 pos
= safecat(buffer
, bufsize
, pos
, " bit");
295 if (interlace_type
!= PNG_INTERLACE_NONE
)
297 pos
= safecat(buffer
, bufsize
, pos
, " interlaced");
299 pos
= safecat(buffer
, bufsize
, pos
, "(pngvalid)");
301 pos
= safecat(buffer
, bufsize
, pos
, "(libpng)");
306 pos
= safecat(buffer
, bufsize
, pos
, " ");
307 pos
= safecatn(buffer
, bufsize
, pos
, w
);
308 pos
= safecat(buffer
, bufsize
, pos
, "x");
309 pos
= safecatn(buffer
, bufsize
, pos
, h
);
316 standard_name_from_id(char *buffer
, size_t bufsize
, size_t pos
, png_uint_32 id
)
318 return standard_name(buffer
, bufsize
, pos
, COL_FROM_ID(id
),
319 DEPTH_FROM_ID(id
), PALETTE_FROM_ID(id
), INTERLACE_FROM_ID(id
),
320 WIDTH_FROM_ID(id
), HEIGHT_FROM_ID(id
), DO_INTERLACE_FROM_ID(id
));
323 /* Convenience API and defines to list valid formats. Note that 16 bit read and
324 * write support is required to do 16 bit read tests (we must be able to make a
325 * 16 bit image to test!)
327 #ifdef PNG_WRITE_16BIT_SUPPORTED
328 # define WRITE_BDHI 4
329 # ifdef PNG_READ_16BIT_SUPPORTED
334 # define WRITE_BDHI 3
340 /* The following defines the number of different palettes to generate for
341 * each log bit depth of a colour type 3 standard image.
343 #define PALETTE_COUNT(bit_depth) ((bit_depth) > 4 ? 1U : 16U)
346 next_format(png_bytep colour_type
, png_bytep bit_depth
,
347 unsigned int* palette_number
)
351 *colour_type
= 0, *bit_depth
= 1, *palette_number
= 0;
355 if (*colour_type
== 3)
357 /* Add multiple palettes for colour type 3. */
358 if (++*palette_number
< PALETTE_COUNT(*bit_depth
))
364 *bit_depth
= (png_byte
)(*bit_depth
<< 1);
366 /* Palette images are restricted to 8 bit depth */
369 || (*colour_type
!= 3 && *bit_depth
<= 16)
374 /* Move to the next color type, or return 0 at the end. */
375 switch (*colour_type
)
402 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
404 sample(png_const_bytep row
, png_byte colour_type
, png_byte bit_depth
,
405 png_uint_32 x
, unsigned int sample_index
)
407 png_uint_32 bit_index
, result
;
409 /* Find a sample index for the desired sample: */
413 if ((colour_type
& 1) == 0) /* !palette */
419 bit_index
+= x
; /* Alpha channel */
421 /* Multiple channels; select one: */
422 if (colour_type
& (2+4))
423 bit_index
+= sample_index
* bit_depth
;
426 /* Return the sample from the row as an integer. */
427 row
+= bit_index
>> 3;
433 else if (bit_depth
> 8)
434 return (result
<< 8) + *++row
;
436 /* Less than 8 bits per sample. */
438 return (result
>> (8-bit_index
-bit_depth
)) & ((1U<<bit_depth
)-1);
440 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
442 /* Copy a single pixel, of a given size, from one buffer to another -
443 * while this is basically bit addressed there is an implicit assumption
444 * that pixels 8 or more bits in size are byte aligned and that pixels
445 * do not otherwise cross byte boundaries. (This is, so far as I know,
446 * universally true in bitmap computer graphics. [JCB 20101212])
448 * NOTE: The to and from buffers may be the same.
451 pixel_copy(png_bytep toBuffer
, png_uint_32 toIndex
,
452 png_const_bytep fromBuffer
, png_uint_32 fromIndex
, unsigned int pixelSize
)
454 /* Assume we can multiply by 'size' without overflow because we are
455 * just working in a single buffer.
457 toIndex
*= pixelSize
;
458 fromIndex
*= pixelSize
;
459 if (pixelSize
< 8) /* Sub-byte */
461 /* Mask to select the location of the copied pixel: */
462 unsigned int destMask
= ((1U<<pixelSize
)-1) << (8-pixelSize
-(toIndex
&7));
463 /* The following read the entire pixels and clears the extra: */
464 unsigned int destByte
= toBuffer
[toIndex
>> 3] & ~destMask
;
465 unsigned int sourceByte
= fromBuffer
[fromIndex
>> 3];
467 /* Don't rely on << or >> supporting '0' here, just in case: */
469 if (fromIndex
> 0) sourceByte
<<= fromIndex
;
470 if ((toIndex
& 7) > 0) sourceByte
>>= toIndex
& 7;
472 toBuffer
[toIndex
>> 3] = (png_byte
)(destByte
| (sourceByte
& destMask
));
474 else /* One or more bytes */
475 memmove(toBuffer
+(toIndex
>>3), fromBuffer
+(fromIndex
>>3), pixelSize
>>3);
478 #ifdef PNG_READ_SUPPORTED
479 /* Copy a complete row of pixels, taking into account potential partial
483 row_copy(png_bytep toBuffer
, png_const_bytep fromBuffer
, unsigned int bitWidth
)
485 memcpy(toBuffer
, fromBuffer
, bitWidth
>> 3);
487 if ((bitWidth
& 7) != 0)
491 toBuffer
+= bitWidth
>> 3;
492 fromBuffer
+= bitWidth
>> 3;
493 /* The remaining bits are in the top of the byte, the mask is the bits to
496 mask
= 0xff >> (bitWidth
& 7);
497 *toBuffer
= (png_byte
)((*toBuffer
& mask
) | (*fromBuffer
& ~mask
));
501 /* Compare pixels - they are assumed to start at the first byte in the
505 pixel_cmp(png_const_bytep pa
, png_const_bytep pb
, png_uint_32 bit_width
)
507 #if PNG_LIBPNG_VER < 10506
508 if (memcmp(pa
, pb
, bit_width
>>3) == 0)
512 if ((bit_width
& 7) == 0) return 0;
514 /* Ok, any differences? */
515 p
= pa
[bit_width
>> 3];
516 p
^= pb
[bit_width
>> 3];
518 if (p
== 0) return 0;
520 /* There are, but they may not be significant, remove the bits
521 * after the end (the low order bits in PNG.)
526 if (p
== 0) return 0;
529 /* From libpng-1.5.6 the overwrite should be fixed, so compare the trailing
532 if (memcmp(pa
, pb
, (bit_width
+7)>>3) == 0)
536 /* Return the index of the changed byte. */
538 png_uint_32 where
= 0;
540 while (pa
[where
] == pb
[where
]) ++where
;
544 #endif /* PNG_READ_SUPPORTED */
546 /*************************** BASIC PNG FILE WRITING ***************************/
547 /* A png_store takes data from the sequential writer or provides data
548 * to the sequential reader. It can also store the result of a PNG
549 * write for later retrieval.
551 #define STORE_BUFFER_SIZE 500 /* arbitrary */
552 typedef struct png_store_buffer
554 struct png_store_buffer
* prev
; /* NOTE: stored in reverse order */
555 png_byte buffer
[STORE_BUFFER_SIZE
];
558 #define FILE_NAME_SIZE 64
560 typedef struct store_palette_entry
/* record of a single palette entry */
566 } store_palette_entry
, store_palette
[256];
568 typedef struct png_store_file
570 struct png_store_file
* next
; /* as many as you like... */
571 char name
[FILE_NAME_SIZE
];
572 png_uint_32 id
; /* must be correct (see FILEID) */
573 png_size_t datacount
; /* In this (the last) buffer */
574 png_store_buffer data
; /* Last buffer in file */
575 int npalette
; /* Number of entries in palette */
576 store_palette_entry
* palette
; /* May be NULL */
579 /* The following is a pool of memory allocated by a single libpng read or write
582 typedef struct store_pool
584 struct png_store
*store
; /* Back pointer */
585 struct store_memory
*list
; /* List of allocated memory */
586 png_byte mark
[4]; /* Before and after data */
588 /* Statistics for this run. */
589 png_alloc_size_t max
; /* Maximum single allocation */
590 png_alloc_size_t current
; /* Current allocation */
591 png_alloc_size_t limit
; /* Highest current allocation */
592 png_alloc_size_t total
; /* Total allocation */
594 /* Overall statistics (retained across successive runs). */
595 png_alloc_size_t max_max
;
596 png_alloc_size_t max_limit
;
597 png_alloc_size_t max_total
;
600 typedef struct png_store
602 /* For cexcept.h exception handling - simply store one of these;
603 * the context is a self pointer but it may point to a different
604 * png_store (in fact it never does in this program.)
606 struct exception_context
609 unsigned int verbose
:1;
610 unsigned int treat_warnings_as_errors
:1;
611 unsigned int expect_error
:1;
612 unsigned int expect_warning
:1;
613 unsigned int saw_warning
:1;
614 unsigned int speed
:1;
615 unsigned int progressive
:1; /* use progressive read */
616 unsigned int validated
:1; /* used as a temporary flag */
619 char test
[128]; /* Name of test */
623 png_structp pread
; /* Used to read a saved file */
625 png_store_file
* current
; /* Set when reading */
626 png_store_buffer
* next
; /* Set when reading */
627 png_size_t readpos
; /* Position in *next */
628 png_byte
* image
; /* Buffer for reading interlaced images */
629 png_size_t cb_image
; /* Size of this buffer */
630 png_size_t cb_row
; /* Row size of the image(s) */
631 png_uint_32 image_h
; /* Number of rows in a single image */
632 store_pool read_memory_pool
;
635 png_store_file
* saved
;
636 png_structp pwrite
; /* Used when writing a new file */
638 png_size_t writepos
; /* Position in .new */
639 char wname
[FILE_NAME_SIZE
];
640 png_store_buffer
new; /* The end of the new PNG file being written. */
641 store_pool write_memory_pool
;
642 store_palette_entry
* palette
;
646 /* Initialization and cleanup */
648 store_pool_mark(png_bytep mark
)
650 static png_uint_32 store_seed
[2] = { 0x12345678, 1};
652 make_four_random_bytes(store_seed
, mark
);
655 #ifdef PNG_READ_SUPPORTED
656 /* Use this for random 32 bit values; this function makes sure the result is
668 store_pool_mark(mark
);
669 result
= png_get_uint_32(mark
);
675 #endif /* PNG_READ_SUPPORTED */
678 store_pool_init(png_store
*ps
, store_pool
*pool
)
680 memset(pool
, 0, sizeof *pool
);
684 pool
->max
= pool
->current
= pool
->limit
= pool
->total
= 0;
685 pool
->max_max
= pool
->max_limit
= pool
->max_total
= 0;
686 store_pool_mark(pool
->mark
);
690 store_init(png_store
* ps
)
692 memset(ps
, 0, sizeof *ps
);
693 init_exception_context(&ps
->exception_context
);
694 store_pool_init(ps
, &ps
->read_memory_pool
);
695 store_pool_init(ps
, &ps
->write_memory_pool
);
697 ps
->treat_warnings_as_errors
= 0;
698 ps
->expect_error
= 0;
699 ps
->expect_warning
= 0;
704 ps
->nerrors
= ps
->nwarnings
= 0;
707 ps
->saved
= ps
->current
= NULL
;
723 store_freebuffer(png_store_buffer
* psb
)
727 store_freebuffer(psb
->prev
);
734 store_freenew(png_store
*ps
)
736 store_freebuffer(&ps
->new);
738 if (ps
->palette
!= NULL
)
747 store_storenew(png_store
*ps
)
749 png_store_buffer
*pb
;
751 if (ps
->writepos
!= STORE_BUFFER_SIZE
)
752 png_error(ps
->pwrite
, "invalid store call");
754 pb
= voidcast(png_store_buffer
*, malloc(sizeof *pb
));
757 png_error(ps
->pwrite
, "store new: OOM");
765 store_freefile(png_store_file
**ppf
)
769 store_freefile(&(*ppf
)->next
);
771 store_freebuffer(&(*ppf
)->data
);
772 (*ppf
)->datacount
= 0;
773 if ((*ppf
)->palette
!= NULL
)
775 free((*ppf
)->palette
);
776 (*ppf
)->palette
= NULL
;
777 (*ppf
)->npalette
= 0;
784 /* Main interface to file storeage, after writing a new PNG file (see the API
785 * below) call store_storefile to store the result with the given name and id.
788 store_storefile(png_store
*ps
, png_uint_32 id
)
790 png_store_file
*pf
= voidcast(png_store_file
*, malloc(sizeof *pf
));
792 png_error(ps
->pwrite
, "storefile: OOM");
793 safecat(pf
->name
, sizeof pf
->name
, 0, ps
->wname
);
796 pf
->datacount
= ps
->writepos
;
799 pf
->palette
= ps
->palette
;
800 pf
->npalette
= ps
->npalette
;
805 pf
->next
= ps
->saved
;
809 /* Generate an error message (in the given buffer) */
811 store_message(png_store
*ps
, png_const_structp pp
, char *buffer
, size_t bufsize
,
812 size_t pos
, PNG_CONST
char *msg
)
814 if (pp
!= NULL
&& pp
== ps
->pread
)
817 pos
= safecat(buffer
, bufsize
, pos
, "read: ");
819 if (ps
->current
!= NULL
)
821 pos
= safecat(buffer
, bufsize
, pos
, ps
->current
->name
);
822 pos
= safecat(buffer
, bufsize
, pos
, sep
);
826 else if (pp
!= NULL
&& pp
== ps
->pwrite
)
829 pos
= safecat(buffer
, bufsize
, pos
, "write: ");
830 pos
= safecat(buffer
, bufsize
, pos
, ps
->wname
);
831 pos
= safecat(buffer
, bufsize
, pos
, sep
);
836 /* Neither reading nor writing (or a memory error in struct delete) */
837 pos
= safecat(buffer
, bufsize
, pos
, "pngvalid: ");
840 if (ps
->test
[0] != 0)
842 pos
= safecat(buffer
, bufsize
, pos
, ps
->test
);
843 pos
= safecat(buffer
, bufsize
, pos
, sep
);
845 pos
= safecat(buffer
, bufsize
, pos
, msg
);
849 /* Verbose output to the error stream: */
851 store_verbose(png_store
*ps
, png_const_structp pp
, png_const_charp prefix
,
852 png_const_charp message
)
857 fputs(prefix
, stderr
);
859 (void)store_message(ps
, pp
, buffer
, sizeof buffer
, 0, message
);
860 fputs(buffer
, stderr
);
864 /* Log an error or warning - the relevant count is always incremented. */
866 store_log(png_store
* ps
, png_const_structp pp
, png_const_charp message
,
869 /* The warning is copied to the error buffer if there are no errors and it is
870 * the first warning. The error is copied to the error buffer if it is the
871 * first error (overwriting any prior warnings).
873 if (is_error
? (ps
->nerrors
)++ == 0 :
874 (ps
->nwarnings
)++ == 0 && ps
->nerrors
== 0)
875 store_message(ps
, pp
, ps
->error
, sizeof ps
->error
, 0, message
);
878 store_verbose(ps
, pp
, is_error
? "error: " : "warning: ", message
);
881 #ifdef PNG_READ_SUPPORTED
882 /* Internal error function, called with a png_store but no libpng stuff. */
884 internal_error(png_store
*ps
, png_const_charp message
)
886 store_log(ps
, NULL
, message
, 1 /* error */);
888 /* And finally throw an exception. */
890 struct exception_context
*the_exception_context
= &ps
->exception_context
;
894 #endif /* PNG_READ_SUPPORTED */
896 /* Functions to use as PNG callbacks. */
898 store_error(png_structp ppIn
, png_const_charp message
) /* PNG_NORETURN */
900 png_const_structp pp
= ppIn
;
901 png_store
*ps
= voidcast(png_store
*, png_get_error_ptr(pp
));
903 if (!ps
->expect_error
)
904 store_log(ps
, pp
, message
, 1 /* error */);
906 /* And finally throw an exception. */
908 struct exception_context
*the_exception_context
= &ps
->exception_context
;
914 store_warning(png_structp ppIn
, png_const_charp message
)
916 png_const_structp pp
= ppIn
;
917 png_store
*ps
= voidcast(png_store
*, png_get_error_ptr(pp
));
919 if (!ps
->expect_warning
)
920 store_log(ps
, pp
, message
, 0 /* warning */);
925 /* These somewhat odd functions are used when reading an image to ensure that
926 * the buffer is big enough, the png_structp is for errors.
928 /* Return a single row from the correct image. */
930 store_image_row(PNG_CONST png_store
* ps
, png_const_structp pp
, int nImage
,
933 png_size_t coffset
= (nImage
* ps
->image_h
+ y
) * (ps
->cb_row
+ 5) + 2;
935 if (ps
->image
== NULL
)
936 png_error(pp
, "no allocated image");
938 if (coffset
+ ps
->cb_row
+ 3 > ps
->cb_image
)
939 png_error(pp
, "image too small");
941 return ps
->image
+ coffset
;
945 store_image_free(png_store
*ps
, png_const_structp pp
)
947 if (ps
->image
!= NULL
)
949 png_bytep image
= ps
->image
;
951 if (image
[-1] != 0xed || image
[ps
->cb_image
] != 0xfe)
954 png_error(pp
, "png_store image overwrite (1)");
956 store_log(ps
, NULL
, "png_store image overwrite (2)", 1);
967 store_ensure_image(png_store
*ps
, png_const_structp pp
, int nImages
,
968 png_size_t cbRow
, png_uint_32 cRows
)
970 png_size_t cb
= nImages
* cRows
* (cbRow
+ 5);
972 if (ps
->cb_image
< cb
)
976 store_image_free(ps
, pp
);
978 /* The buffer is deliberately mis-aligned. */
979 image
= voidcast(png_bytep
, malloc(cb
+2));
982 /* Called from the startup - ignore the error for the moment. */
986 png_error(pp
, "OOM allocating image buffer");
989 /* These magic tags are used to detect overwrites above. */
998 /* We have an adequate sized image; lay out the rows. There are 2 bytes at
999 * the start and three at the end of each (this ensures that the row
1000 * alignment starts out odd - 2+1 and changes for larger images on each row.)
1003 ps
->image_h
= cRows
;
1005 /* For error checking, the whole buffer is set to 10110010 (0xb2 - 178).
1006 * This deliberately doesn't match the bits in the size test image which are
1007 * outside the image; these are set to 0xff (all 1). To make the row
1008 * comparison work in the 'size' test case the size rows are pre-initialized
1009 * to the same value prior to calling 'standard_row'.
1011 memset(ps
->image
, 178, cb
);
1013 /* Then put in the marks. */
1014 while (--nImages
>= 0)
1018 for (y
=0; y
<cRows
; ++y
)
1020 png_bytep row
= store_image_row(ps
, pp
, nImages
, y
);
1032 #ifdef PNG_READ_SUPPORTED
1034 store_image_check(PNG_CONST png_store
* ps
, png_const_structp pp
, int iImage
)
1036 png_const_bytep image
= ps
->image
;
1038 if (image
[-1] != 0xed || image
[ps
->cb_image
] != 0xfe)
1039 png_error(pp
, "image overwrite");
1042 png_size_t cbRow
= ps
->cb_row
;
1043 png_uint_32 rows
= ps
->image_h
;
1045 image
+= iImage
* (cbRow
+5) * ps
->image_h
;
1047 image
+= 2; /* skip image first row markers */
1051 if (image
[-2] != 190 || image
[-1] != 239)
1052 png_error(pp
, "row start overwritten");
1054 if (image
[cbRow
] != 222 || image
[cbRow
+1] != 173 ||
1055 image
[cbRow
+2] != 17)
1056 png_error(pp
, "row end overwritten");
1062 #endif /* PNG_READ_SUPPORTED */
1065 store_write(png_structp ppIn
, png_bytep pb
, png_size_t st
)
1067 png_const_structp pp
= ppIn
;
1068 png_store
*ps
= voidcast(png_store
*, png_get_io_ptr(pp
));
1070 if (ps
->pwrite
!= pp
)
1071 png_error(pp
, "store state damaged");
1077 if (ps
->writepos
>= STORE_BUFFER_SIZE
)
1082 if (cb
> STORE_BUFFER_SIZE
- ps
->writepos
)
1083 cb
= STORE_BUFFER_SIZE
- ps
->writepos
;
1085 memcpy(ps
->new.buffer
+ ps
->writepos
, pb
, cb
);
1093 store_flush(png_structp ppIn
)
1095 UNUSED(ppIn
) /*DOES NOTHING*/
1098 #ifdef PNG_READ_SUPPORTED
1100 store_read_buffer_size(png_store
*ps
)
1102 /* Return the bytes available for read in the current buffer. */
1103 if (ps
->next
!= &ps
->current
->data
)
1104 return STORE_BUFFER_SIZE
;
1106 return ps
->current
->datacount
;
1109 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
1110 /* Return total bytes available for read. */
1112 store_read_buffer_avail(png_store
*ps
)
1114 if (ps
->current
!= NULL
&& ps
->next
!= NULL
)
1116 png_store_buffer
*next
= &ps
->current
->data
;
1117 size_t cbAvail
= ps
->current
->datacount
;
1119 while (next
!= ps
->next
&& next
!= NULL
)
1122 cbAvail
+= STORE_BUFFER_SIZE
;
1125 if (next
!= ps
->next
)
1126 png_error(ps
->pread
, "buffer read error");
1128 if (cbAvail
> ps
->readpos
)
1129 return cbAvail
- ps
->readpos
;
1137 store_read_buffer_next(png_store
*ps
)
1139 png_store_buffer
*pbOld
= ps
->next
;
1140 png_store_buffer
*pbNew
= &ps
->current
->data
;
1143 while (pbNew
!= NULL
&& pbNew
->prev
!= pbOld
)
1144 pbNew
= pbNew
->prev
;
1153 png_error(ps
->pread
, "buffer lost");
1156 return 0; /* EOF or error */
1159 /* Need separate implementation and callback to allow use of the same code
1160 * during progressive read, where the io_ptr is set internally by libpng.
1163 store_read_imp(png_store
*ps
, png_bytep pb
, png_size_t st
)
1165 if (ps
->current
== NULL
|| ps
->next
== NULL
)
1166 png_error(ps
->pread
, "store state damaged");
1170 size_t cbAvail
= store_read_buffer_size(ps
) - ps
->readpos
;
1174 if (cbAvail
> st
) cbAvail
= st
;
1175 memcpy(pb
, ps
->next
->buffer
+ ps
->readpos
, cbAvail
);
1178 ps
->readpos
+= cbAvail
;
1181 else if (!store_read_buffer_next(ps
))
1182 png_error(ps
->pread
, "read beyond end of file");
1187 store_read(png_structp ppIn
, png_bytep pb
, png_size_t st
)
1189 png_const_structp pp
= ppIn
;
1190 png_store
*ps
= voidcast(png_store
*, png_get_io_ptr(pp
));
1192 if (ps
== NULL
|| ps
->pread
!= pp
)
1193 png_error(pp
, "bad store read call");
1195 store_read_imp(ps
, pb
, st
);
1199 store_progressive_read(png_store
*ps
, png_structp pp
, png_infop pi
)
1201 /* Notice that a call to store_read will cause this function to fail because
1202 * readpos will be set.
1204 if (ps
->pread
!= pp
|| ps
->current
== NULL
|| ps
->next
== NULL
)
1205 png_error(pp
, "store state damaged (progressive)");
1209 if (ps
->readpos
!= 0)
1210 png_error(pp
, "store_read called during progressive read");
1212 png_process_data(pp
, pi
, ps
->next
->buffer
, store_read_buffer_size(ps
));
1214 while (store_read_buffer_next(ps
));
1216 #endif /* PNG_READ_SUPPORTED */
1218 /* The caller must fill this in: */
1219 static store_palette_entry
*
1220 store_write_palette(png_store
*ps
, int npalette
)
1222 if (ps
->pwrite
== NULL
)
1223 store_log(ps
, NULL
, "attempt to write palette without write stream", 1);
1225 if (ps
->palette
!= NULL
)
1226 png_error(ps
->pwrite
, "multiple store_write_palette calls");
1228 /* This function can only return NULL if called with '0'! */
1231 ps
->palette
= voidcast(store_palette_entry
*, malloc(npalette
*
1232 sizeof *ps
->palette
));
1234 if (ps
->palette
== NULL
)
1235 png_error(ps
->pwrite
, "store new palette: OOM");
1237 ps
->npalette
= npalette
;
1243 #ifdef PNG_READ_SUPPORTED
1244 static store_palette_entry
*
1245 store_current_palette(png_store
*ps
, int *npalette
)
1247 /* This is an internal error (the call has been made outside a read
1250 if (ps
->current
== NULL
)
1251 store_log(ps
, ps
->pread
, "no current stream for palette", 1);
1253 /* The result may be null if there is no palette. */
1254 *npalette
= ps
->current
->npalette
;
1255 return ps
->current
->palette
;
1257 #endif /* PNG_READ_SUPPORTED */
1259 /***************************** MEMORY MANAGEMENT*** ***************************/
1260 /* A store_memory is simply the header for an allocated block of memory. The
1261 * pointer returned to libpng is just after the end of the header block, the
1262 * allocated memory is followed by a second copy of the 'mark'.
1264 typedef struct store_memory
1266 store_pool
*pool
; /* Originating pool */
1267 struct store_memory
*next
; /* Singly linked list */
1268 png_alloc_size_t size
; /* Size of memory allocated */
1269 png_byte mark
[4]; /* ID marker */
1272 /* Handle a fatal error in memory allocation. This calls png_error if the
1273 * libpng struct is non-NULL, else it outputs a message and returns. This means
1274 * that a memory problem while libpng is running will abort (png_error) the
1275 * handling of particular file while one in cleanup (after the destroy of the
1276 * struct has returned) will simply keep going and free (or attempt to free)
1280 store_pool_error(png_store
*ps
, png_const_structp pp
, PNG_CONST
char *msg
)
1285 /* Else we have to do it ourselves. png_error eventually calls store_log,
1286 * above. store_log accepts a NULL png_structp - it just changes what gets
1287 * output by store_message.
1289 store_log(ps
, pp
, msg
, 1 /* error */);
1293 store_memory_free(png_const_structp pp
, store_pool
*pool
, store_memory
*memory
)
1295 /* Note that pp may be NULL (see store_pool_delete below), the caller has
1296 * found 'memory' in pool->list *and* unlinked this entry, so this is a valid
1297 * pointer (for sure), but the contents may have been trashed.
1299 if (memory
->pool
!= pool
)
1300 store_pool_error(pool
->store
, pp
, "memory corrupted (pool)");
1302 else if (memcmp(memory
->mark
, pool
->mark
, sizeof memory
->mark
) != 0)
1303 store_pool_error(pool
->store
, pp
, "memory corrupted (start)");
1305 /* It should be safe to read the size field now. */
1308 png_alloc_size_t cb
= memory
->size
;
1311 store_pool_error(pool
->store
, pp
, "memory corrupted (size)");
1313 else if (memcmp((png_bytep
)(memory
+1)+cb
, pool
->mark
, sizeof pool
->mark
)
1315 store_pool_error(pool
->store
, pp
, "memory corrupted (end)");
1317 /* Finally give the library a chance to find problems too: */
1320 pool
->current
-= cb
;
1327 store_pool_delete(png_store
*ps
, store_pool
*pool
)
1329 if (pool
->list
!= NULL
)
1331 fprintf(stderr
, "%s: %s %s: memory lost (list follows):\n", ps
->test
,
1332 pool
== &ps
->read_memory_pool
? "read" : "write",
1333 pool
== &ps
->read_memory_pool
? (ps
->current
!= NULL
?
1334 ps
->current
->name
: "unknown file") : ps
->wname
);
1339 store_memory
*next
= pool
->list
;
1340 pool
->list
= next
->next
;
1343 fprintf(stderr
, "\t%lu bytes @ %p\n",
1344 (unsigned long)next
->size
, (PNG_CONST
void*)(next
+1));
1345 /* The NULL means this will always return, even if the memory is
1348 store_memory_free(NULL
, pool
, next
);
1350 while (pool
->list
!= NULL
);
1353 /* And reset the other fields too for the next time. */
1354 if (pool
->max
> pool
->max_max
) pool
->max_max
= pool
->max
;
1356 if (pool
->current
!= 0) /* unexpected internal error */
1357 fprintf(stderr
, "%s: %s %s: memory counter mismatch (internal error)\n",
1358 ps
->test
, pool
== &ps
->read_memory_pool
? "read" : "write",
1359 pool
== &ps
->read_memory_pool
? (ps
->current
!= NULL
?
1360 ps
->current
->name
: "unknown file") : ps
->wname
);
1363 if (pool
->limit
> pool
->max_limit
)
1364 pool
->max_limit
= pool
->limit
;
1368 if (pool
->total
> pool
->max_total
)
1369 pool
->max_total
= pool
->total
;
1373 /* Get a new mark too. */
1374 store_pool_mark(pool
->mark
);
1377 /* The memory callbacks: */
1379 store_malloc(png_structp ppIn
, png_alloc_size_t cb
)
1381 png_const_structp pp
= ppIn
;
1382 store_pool
*pool
= voidcast(store_pool
*, png_get_mem_ptr(pp
));
1383 store_memory
*new = voidcast(store_memory
*, malloc(cb
+ (sizeof *new) +
1384 (sizeof pool
->mark
)));
1391 pool
->current
+= cb
;
1393 if (pool
->current
> pool
->limit
)
1394 pool
->limit
= pool
->current
;
1399 memcpy(new->mark
, pool
->mark
, sizeof new->mark
);
1400 memcpy((png_byte
*)(new+1) + cb
, pool
->mark
, sizeof pool
->mark
);
1402 new->next
= pool
->list
;
1409 /* NOTE: the PNG user malloc function cannot use the png_ptr it is passed
1410 * other than to retrieve the allocation pointer! libpng calls the
1411 * store_malloc callback in two basic cases:
1413 * 1) From png_malloc; png_malloc will do a png_error itself if NULL is
1415 * 2) From png_struct or png_info structure creation; png_malloc is
1416 * to return so cleanup can be performed.
1418 * To handle this store_malloc can log a message, but can't do anything
1421 store_log(pool
->store
, pp
, "out of memory", 1 /* is_error */);
1428 store_free(png_structp ppIn
, png_voidp memory
)
1430 png_const_structp pp
= ppIn
;
1431 store_pool
*pool
= voidcast(store_pool
*, png_get_mem_ptr(pp
));
1432 store_memory
*this = voidcast(store_memory
*, memory
), **test
;
1434 /* Because libpng calls store_free with a dummy png_struct when deleting
1435 * png_struct or png_info via png_destroy_struct_2 it is necessary to check
1436 * the passed in png_structp to ensure it is valid, and not pass it to
1437 * png_error if it is not.
1439 if (pp
!= pool
->store
->pread
&& pp
!= pool
->store
->pwrite
)
1442 /* First check that this 'memory' really is valid memory - it must be in the
1443 * pool list. If it is, use the shared memory_free function to free it.
1446 for (test
= &pool
->list
; *test
!= this; test
= &(*test
)->next
)
1450 store_pool_error(pool
->store
, pp
, "bad pointer to free");
1455 /* Unlink this entry, *test == this. */
1458 store_memory_free(pp
, pool
, this);
1461 /* Setup functions. */
1462 /* Cleanup when aborting a write or after storing the new file. */
1464 store_write_reset(png_store
*ps
)
1466 if (ps
->pwrite
!= NULL
)
1471 png_destroy_write_struct(&ps
->pwrite
, &ps
->piwrite
);
1475 /* memory corruption: continue. */
1482 /* And make sure that all the memory has been freed - this will output
1483 * spurious errors in the case of memory corruption above, but this is safe.
1485 store_pool_delete(ps
, &ps
->write_memory_pool
);
1490 /* The following is the main write function, it returns a png_struct and,
1491 * optionally, a png_info suitable for writiing a new PNG file. Use
1492 * store_storefile above to record this file after it has been written. The
1493 * returned libpng structures as destroyed by store_write_reset above.
1496 set_store_for_write(png_store
*ps
, png_infopp ppi
,
1497 PNG_CONST
char * volatile name
)
1503 if (ps
->pwrite
!= NULL
)
1504 png_error(ps
->pwrite
, "write store already in use");
1506 store_write_reset(ps
);
1507 safecat(ps
->wname
, sizeof ps
->wname
, 0, name
);
1509 /* Don't do the slow memory checks if doing a speed test. */
1511 ps
->pwrite
= png_create_write_struct(PNG_LIBPNG_VER_STRING
,
1512 ps
, store_error
, store_warning
);
1515 ps
->pwrite
= png_create_write_struct_2(PNG_LIBPNG_VER_STRING
,
1516 ps
, store_error
, store_warning
, &ps
->write_memory_pool
,
1517 store_malloc
, store_free
);
1519 png_set_write_fn(ps
->pwrite
, ps
, store_write
, store_flush
);
1522 *ppi
= ps
->piwrite
= png_create_info_struct(ps
->pwrite
);
1531 /* Cleanup when finished reading (either due to error or in the success case).
1532 * This routine exists even when there is no read support to make the code
1533 * tidier (avoid a mass of ifdefs) and so easier to maintain.
1536 store_read_reset(png_store
*ps
)
1538 # ifdef PNG_READ_SUPPORTED
1539 if (ps
->pread
!= NULL
)
1544 png_destroy_read_struct(&ps
->pread
, &ps
->piread
, NULL
);
1548 /* error already output: continue */
1556 /* Always do this to be safe. */
1557 store_pool_delete(ps
, &ps
->read_memory_pool
);
1565 #ifdef PNG_READ_SUPPORTED
1567 store_read_set(png_store
*ps
, png_uint_32 id
)
1569 png_store_file
*pf
= ps
->saved
;
1577 store_read_buffer_next(ps
);
1586 char msg
[FILE_NAME_SIZE
+64];
1588 pos
= standard_name_from_id(msg
, sizeof msg
, 0, id
);
1589 pos
= safecat(msg
, sizeof msg
, pos
, ": file not found");
1590 png_error(ps
->pread
, msg
);
1594 /* The main interface for reading a saved file - pass the id number of the file
1595 * to retrieve. Ids must be unique or the earlier file will be hidden. The API
1596 * returns a png_struct and, optionally, a png_info. Both of these will be
1597 * destroyed by store_read_reset above.
1600 set_store_for_read(png_store
*ps
, png_infopp ppi
, png_uint_32 id
,
1601 PNG_CONST
char *name
)
1603 /* Set the name for png_error */
1604 safecat(ps
->test
, sizeof ps
->test
, 0, name
);
1606 if (ps
->pread
!= NULL
)
1607 png_error(ps
->pread
, "read store already in use");
1609 store_read_reset(ps
);
1611 /* Both the create APIs can return NULL if used in their default mode
1612 * (because there is no other way of handling an error because the jmp_buf
1613 * by default is stored in png_struct and that has not been allocated!)
1614 * However, given that store_error works correctly in these circumstances
1615 * we don't ever expect NULL in this program.
1618 ps
->pread
= png_create_read_struct(PNG_LIBPNG_VER_STRING
, ps
,
1619 store_error
, store_warning
);
1622 ps
->pread
= png_create_read_struct_2(PNG_LIBPNG_VER_STRING
, ps
,
1623 store_error
, store_warning
, &ps
->read_memory_pool
, store_malloc
,
1626 if (ps
->pread
== NULL
)
1628 struct exception_context
*the_exception_context
= &ps
->exception_context
;
1630 store_log(ps
, NULL
, "png_create_read_struct returned NULL (unexpected)",
1636 store_read_set(ps
, id
);
1639 *ppi
= ps
->piread
= png_create_info_struct(ps
->pread
);
1643 #endif /* PNG_READ_SUPPORTED */
1645 /* The overall cleanup of a store simply calls the above then removes all the
1646 * saved files. This does not delete the store itself.
1649 store_delete(png_store
*ps
)
1651 store_write_reset(ps
);
1652 store_read_reset(ps
);
1653 store_freefile(&ps
->saved
);
1654 store_image_free(ps
, NULL
);
1657 /*********************** PNG FILE MODIFICATION ON READ ************************/
1658 /* Files may be modified on read. The following structure contains a complete
1659 * png_store together with extra members to handle modification and a special
1660 * read callback for libpng. To use this the 'modifications' field must be set
1661 * to a list of png_modification structures that actually perform the
1662 * modification, otherwise a png_modifier is functionally equivalent to a
1663 * png_store. There is a special read function, set_modifier_for_read, which
1664 * replaces set_store_for_read.
1666 typedef enum modifier_state
1668 modifier_start
, /* Initial value */
1669 modifier_signature
, /* Have a signature */
1670 modifier_IHDR
/* Have an IHDR */
1673 typedef struct CIE_color
1675 /* A single CIE tristimulus value, representing the unique response of a
1676 * standard observer to a variety of light spectra. The observer recognizes
1677 * all spectra that produce this response as the same color, therefore this
1678 * is effectively a description of a color.
1683 typedef struct color_encoding
1685 /* A description of an (R,G,B) encoding of color (as defined above); this
1686 * includes the actual colors of the (R,G,B) triples (1,0,0), (0,1,0) and
1687 * (0,0,1) plus an encoding value that is used to encode the linear
1688 * components R, G and B to give the actual values R^gamma, G^gamma and
1689 * B^gamma that are stored.
1691 double gamma
; /* Encoding (file) gamma of space */
1692 CIE_color red
, green
, blue
; /* End points */
1695 #ifdef PNG_READ_SUPPORTED
1697 chromaticity_x(CIE_color c
)
1699 return c
.X
/ (c
.X
+ c
.Y
+ c
.Z
);
1703 chromaticity_y(CIE_color c
)
1705 return c
.Y
/ (c
.X
+ c
.Y
+ c
.Z
);
1709 white_point(PNG_CONST color_encoding
*encoding
)
1713 white
.X
= encoding
->red
.X
+ encoding
->green
.X
+ encoding
->blue
.X
;
1714 white
.Y
= encoding
->red
.Y
+ encoding
->green
.Y
+ encoding
->blue
.Y
;
1715 white
.Z
= encoding
->red
.Z
+ encoding
->green
.Z
+ encoding
->blue
.Z
;
1720 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
1722 normalize_color_encoding(color_encoding
*encoding
)
1724 PNG_CONST
double whiteY
= encoding
->red
.Y
+ encoding
->green
.Y
+
1729 encoding
->red
.X
/= whiteY
;
1730 encoding
->red
.Y
/= whiteY
;
1731 encoding
->red
.Z
/= whiteY
;
1732 encoding
->green
.X
/= whiteY
;
1733 encoding
->green
.Y
/= whiteY
;
1734 encoding
->green
.Z
/= whiteY
;
1735 encoding
->blue
.X
/= whiteY
;
1736 encoding
->blue
.Y
/= whiteY
;
1737 encoding
->blue
.Z
/= whiteY
;
1743 safecat_color_encoding(char *buffer
, size_t bufsize
, size_t pos
,
1744 PNG_CONST color_encoding
*e
, double encoding_gamma
)
1748 if (encoding_gamma
!= 0)
1749 pos
= safecat(buffer
, bufsize
, pos
, "(");
1750 pos
= safecat(buffer
, bufsize
, pos
, "R(");
1751 pos
= safecatd(buffer
, bufsize
, pos
, e
->red
.X
, 4);
1752 pos
= safecat(buffer
, bufsize
, pos
, ",");
1753 pos
= safecatd(buffer
, bufsize
, pos
, e
->red
.Y
, 4);
1754 pos
= safecat(buffer
, bufsize
, pos
, ",");
1755 pos
= safecatd(buffer
, bufsize
, pos
, e
->red
.Z
, 4);
1756 pos
= safecat(buffer
, bufsize
, pos
, "),G(");
1757 pos
= safecatd(buffer
, bufsize
, pos
, e
->green
.X
, 4);
1758 pos
= safecat(buffer
, bufsize
, pos
, ",");
1759 pos
= safecatd(buffer
, bufsize
, pos
, e
->green
.Y
, 4);
1760 pos
= safecat(buffer
, bufsize
, pos
, ",");
1761 pos
= safecatd(buffer
, bufsize
, pos
, e
->green
.Z
, 4);
1762 pos
= safecat(buffer
, bufsize
, pos
, "),B(");
1763 pos
= safecatd(buffer
, bufsize
, pos
, e
->blue
.X
, 4);
1764 pos
= safecat(buffer
, bufsize
, pos
, ",");
1765 pos
= safecatd(buffer
, bufsize
, pos
, e
->blue
.Y
, 4);
1766 pos
= safecat(buffer
, bufsize
, pos
, ",");
1767 pos
= safecatd(buffer
, bufsize
, pos
, e
->blue
.Z
, 4);
1768 pos
= safecat(buffer
, bufsize
, pos
, ")");
1769 if (encoding_gamma
!= 0)
1770 pos
= safecat(buffer
, bufsize
, pos
, ")");
1773 if (encoding_gamma
!= 0)
1775 pos
= safecat(buffer
, bufsize
, pos
, "^");
1776 pos
= safecatd(buffer
, bufsize
, pos
, encoding_gamma
, 5);
1781 #endif /* PNG_READ_SUPPORTED */
1783 typedef struct png_modifier
1785 png_store
this; /* I am a png_store */
1786 struct png_modification
*modifications
; /* Changes to make */
1788 modifier_state state
; /* My state */
1790 /* Information from IHDR: */
1791 png_byte bit_depth
; /* From IHDR */
1792 png_byte colour_type
; /* From IHDR */
1794 /* While handling PLTE, IDAT and IEND these chunks may be pended to allow
1795 * other chunks to be inserted.
1797 png_uint_32 pending_len
;
1798 png_uint_32 pending_chunk
;
1802 unsigned int ngammas
;
1803 unsigned int ngamma_tests
; /* Number of gamma tests to run*/
1804 double current_gamma
; /* 0 if not set */
1805 PNG_CONST color_encoding
*encodings
;
1806 unsigned int nencodings
;
1807 PNG_CONST color_encoding
*current_encoding
; /* If an encoding has been set */
1808 unsigned int encoding_counter
; /* For iteration */
1809 int encoding_ignored
; /* Something overwrote it */
1811 /* Control variables used to iterate through possible encodings, the
1812 * following must be set to 0 and tested by the function that uses the
1813 * png_modifier because the modifier only sets it to 1 (true.)
1815 unsigned int repeat
:1; /* Repeat this transform test. */
1816 unsigned int test_uses_encoding
:1;
1818 /* Lowest sbit to test (libpng fails for sbit < 8) */
1821 /* Error control - these are the limits on errors accepted by the gamma tests
1824 double maxout8
; /* Maximum output value error */
1825 double maxabs8
; /* Absolute sample error 0..1 */
1826 double maxcalc8
; /* Absolute sample error 0..1 */
1827 double maxpc8
; /* Percentage sample error 0..100% */
1828 double maxout16
; /* Maximum output value error */
1829 double maxabs16
; /* Absolute sample error 0..1 */
1830 double maxcalc16
;/* Absolute sample error 0..1 */
1831 double maxpc16
; /* Percentage sample error 0..100% */
1833 /* This is set by transforms that need to allow a higher limit, it is an
1834 * internal check on pngvalid to ensure that the calculated error limits are
1835 * not ridiculous; without this it is too easy to make a mistake in pngvalid
1836 * that allows any value through.
1838 double limit
; /* limit on error values, normally 4E-3 */
1840 /* Log limits - values above this are logged, but not necessarily
1843 double log8
; /* Absolute error in 8 bits to log */
1844 double log16
; /* Absolute error in 16 bits to log */
1846 /* Logged 8 and 16 bit errors ('output' values): */
1847 double error_gray_2
;
1848 double error_gray_4
;
1849 double error_gray_8
;
1850 double error_gray_16
;
1851 double error_color_8
;
1852 double error_color_16
;
1853 double error_indexed
;
1856 /* Whether to call png_read_update_info, not png_read_start_image, and how
1857 * many times to call it.
1859 int use_update_info
;
1861 /* Whether or not to interlace. */
1862 int interlace_type
:9; /* int, but must store '1' */
1864 /* Run the standard tests? */
1865 unsigned int test_standard
:1;
1867 /* Run the odd-sized image and interlace read/write tests? */
1868 unsigned int test_size
:1;
1870 /* Run tests on reading with a combiniation of transforms, */
1871 unsigned int test_transform
:1;
1873 /* When to use the use_input_precision option: */
1874 unsigned int use_input_precision
:1;
1875 unsigned int use_input_precision_sbit
:1;
1876 unsigned int use_input_precision_16to8
:1;
1878 /* If set assume that the calculation bit depth is set by the input
1879 * precision, not the output precision.
1881 unsigned int calculations_use_input_precision
:1;
1883 /* If set assume that the calculations are done in 16 bits even if both input
1884 * and output are 8 bit or less.
1886 unsigned int assume_16_bit_calculations
:1;
1888 /* Which gamma tests to run: */
1889 unsigned int test_gamma_threshold
:1;
1890 unsigned int test_gamma_transform
:1; /* main tests */
1891 unsigned int test_gamma_sbit
:1;
1892 unsigned int test_gamma_scale16
:1;
1893 unsigned int test_gamma_background
:1;
1894 unsigned int test_gamma_alpha_mode
:1;
1895 unsigned int test_gamma_expand16
:1;
1896 unsigned int test_exhaustive
:1;
1898 unsigned int log
:1; /* Log max error */
1900 /* Buffer information, the buffer size limits the size of the chunks that can
1901 * be modified - they must fit (including header and CRC) into the buffer!
1903 size_t flush
; /* Count of bytes to flush */
1904 size_t buffer_count
; /* Bytes in buffer */
1905 size_t buffer_position
; /* Position in buffer */
1906 png_byte buffer
[1024];
1909 /* This returns true if the test should be stopped now because it has already
1910 * failed and it is running silently.
1912 static int fail(png_modifier
*pm
)
1914 return !pm
->log
&& !pm
->this.verbose
&& (pm
->this.nerrors
> 0 ||
1915 (pm
->this.treat_warnings_as_errors
&& pm
->this.nwarnings
> 0));
1919 modifier_init(png_modifier
*pm
)
1921 memset(pm
, 0, sizeof *pm
);
1922 store_init(&pm
->this);
1923 pm
->modifications
= NULL
;
1924 pm
->state
= modifier_start
;
1927 pm
->ngamma_tests
= 0;
1929 pm
->current_gamma
= 0;
1932 pm
->current_encoding
= 0;
1933 pm
->encoding_counter
= 0;
1934 pm
->encoding_ignored
= 0;
1936 pm
->test_uses_encoding
= 0;
1937 pm
->maxout8
= pm
->maxpc8
= pm
->maxabs8
= pm
->maxcalc8
= 0;
1938 pm
->maxout16
= pm
->maxpc16
= pm
->maxabs16
= pm
->maxcalc16
= 0;
1940 pm
->log8
= pm
->log16
= 0; /* Means 'off' */
1941 pm
->error_gray_2
= pm
->error_gray_4
= pm
->error_gray_8
= 0;
1942 pm
->error_gray_16
= pm
->error_color_8
= pm
->error_color_16
= 0;
1943 pm
->error_indexed
= 0;
1944 pm
->use_update_info
= 0;
1945 pm
->interlace_type
= PNG_INTERLACE_NONE
;
1946 pm
->test_standard
= 0;
1948 pm
->test_transform
= 0;
1949 pm
->use_input_precision
= 0;
1950 pm
->use_input_precision_sbit
= 0;
1951 pm
->use_input_precision_16to8
= 0;
1952 pm
->calculations_use_input_precision
= 0;
1953 pm
->test_gamma_threshold
= 0;
1954 pm
->test_gamma_transform
= 0;
1955 pm
->test_gamma_sbit
= 0;
1956 pm
->test_gamma_scale16
= 0;
1957 pm
->test_gamma_background
= 0;
1958 pm
->test_gamma_alpha_mode
= 0;
1959 pm
->test_gamma_expand16
= 0;
1960 pm
->test_exhaustive
= 0;
1963 /* Rely on the memset for all the other fields - there are no pointers */
1966 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
1967 /* If pm->calculations_use_input_precision is set then operations will happen
1968 * with only 8 bit precision unless both the input and output bit depth are 16.
1970 * If pm->assume_16_bit_calculations is set then even 8 bit calculations use 16
1971 * bit precision. This only affects those of the following limits that pertain
1972 * to a calculation - not a digitization operation - unless the following API is
1975 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
1976 static double digitize(PNG_CONST png_modifier
*pm
, double value
,
1977 int sample_depth
, int do_round
)
1979 /* 'value' is in the range 0 to 1, the result is the same value rounded to a
1980 * multiple of the digitization factor - 8 or 16 bits depending on both the
1981 * sample depth and the 'assume' setting. Digitization is normally by
1982 * rounding and 'do_round' should be 1, if it is 0 the digitized value will
1985 PNG_CONST
unsigned int digitization_factor
=
1986 (pm
->assume_16_bit_calculations
|| sample_depth
== 16) ? 65535 : 255;
1988 /* Limiting the range is done as a convenience to the caller - it's easier to
1989 * do it once here than every time at the call site.
1993 else if (value
>= 1)
1996 value
*= digitization_factor
;
1997 if (do_round
) value
+= .5;
1998 return floor(value
)/digitization_factor
;
2002 #if defined(PNG_READ_GAMMA_SUPPORTED) ||\
2003 defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
2004 static double abserr(PNG_CONST png_modifier
*pm
, int in_depth
, int out_depth
)
2006 /* Absolute error permitted in linear values - affected by the bit depth of
2009 if (pm
->assume_16_bit_calculations
|| (out_depth
== 16 && (in_depth
== 16 ||
2010 !pm
->calculations_use_input_precision
)))
2011 return pm
->maxabs16
;
2017 #ifdef PNG_READ_GAMMA_SUPPORTED
2018 static double calcerr(PNG_CONST png_modifier
*pm
, int in_depth
, int out_depth
)
2020 /* Error in the linear composition arithmetic - only relevant when
2021 * composition actually happens (0 < alpha < 1).
2023 if (pm
->assume_16_bit_calculations
|| (out_depth
== 16 && (in_depth
== 16 ||
2024 !pm
->calculations_use_input_precision
)))
2025 return pm
->maxcalc16
;
2027 return pm
->maxcalc8
;
2030 static double pcerr(PNG_CONST png_modifier
*pm
, int in_depth
, int out_depth
)
2032 /* Percentage error permitted in the linear values. Note that the specified
2033 * value is a percentage but this routine returns a simple number.
2035 if (pm
->assume_16_bit_calculations
|| (out_depth
== 16 && (in_depth
== 16 ||
2036 !pm
->calculations_use_input_precision
)))
2037 return pm
->maxpc16
* .01;
2039 return pm
->maxpc8
* .01;
2042 /* Output error - the error in the encoded value. This is determined by the
2043 * digitization of the output so can be +/-0.5 in the actual output value. In
2044 * the expand_16 case with the current code in libpng the expand happens after
2045 * all the calculations are done in 8 bit arithmetic, so even though the output
2046 * depth is 16 the output error is determined by the 8 bit calculation.
2048 * This limit is not determined by the bit depth of internal calculations.
2050 * The specified parameter does *not* include the base .5 digitization error but
2053 static double outerr(PNG_CONST png_modifier
*pm
, int in_depth
, int out_depth
)
2055 /* There is a serious error in the 2 and 4 bit grayscale transform because
2056 * the gamma table value (8 bits) is simply shifted, not rounded, so the
2057 * error in 4 bit grayscale gamma is up to the value below. This is a hack
2058 * to allow pngvalid to succeed:
2060 * TODO: fix this in libpng
2068 if (out_depth
== 16 && (in_depth
== 16 ||
2069 !pm
->calculations_use_input_precision
))
2070 return pm
->maxout16
;
2072 /* This is the case where the value was calculated at 8-bit precision then
2073 * scaled to 16 bits.
2075 else if (out_depth
== 16)
2076 return pm
->maxout8
* 257;
2082 /* This does the same thing as the above however it returns the value to log,
2083 * rather than raising a warning. This is useful for debugging to track down
2084 * exactly what set of parameters cause high error values.
2086 static double outlog(PNG_CONST png_modifier
*pm
, int in_depth
, int out_depth
)
2088 /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535)
2089 * and so must be adjusted for low bit depth grayscale:
2093 if (pm
->log8
== 0) /* switched off */
2097 return pm
->log8
/ 255 * ((1<<out_depth
)-1);
2102 if (out_depth
== 16 && (in_depth
== 16 ||
2103 !pm
->calculations_use_input_precision
))
2111 /* This is the case where the value was calculated at 8-bit precision then
2112 * scaled to 16 bits.
2117 return pm
->log8
* 257;
2120 /* This complements the above by providing the appropriate quantization for the
2121 * final value. Normally this would just be quantization to an integral value,
2122 * but in the 8 bit calculation case it's actually quantization to a multiple of
2125 static int output_quantization_factor(PNG_CONST png_modifier
*pm
, int in_depth
,
2128 if (out_depth
== 16 && in_depth
!= 16
2129 && pm
->calculations_use_input_precision
)
2134 #endif /* PNG_READ_GAMMA_SUPPORTED */
2136 /* One modification structure must be provided for each chunk to be modified (in
2137 * fact more than one can be provided if multiple separate changes are desired
2138 * for a single chunk.) Modifications include adding a new chunk when a
2139 * suitable chunk does not exist.
2141 * The caller of modify_fn will reset the CRC of the chunk and record 'modified'
2142 * or 'added' as appropriate if the modify_fn returns 1 (true). If the
2143 * modify_fn is NULL the chunk is simply removed.
2145 typedef struct png_modification
2147 struct png_modification
*next
;
2150 /* If the following is NULL all matching chunks will be removed: */
2151 int (*modify_fn
)(struct png_modifier
*pm
,
2152 struct png_modification
*me
, int add
);
2154 /* If the following is set to PLTE, IDAT or IEND and the chunk has not been
2155 * found and modified (and there is a modify_fn) the modify_fn will be called
2156 * to add the chunk before the relevant chunk.
2159 unsigned int modified
:1; /* Chunk was modified */
2160 unsigned int added
:1; /* Chunk was added */
2161 unsigned int removed
:1; /* Chunk was removed */
2165 modification_reset(png_modification
*pmm
)
2172 modification_reset(pmm
->next
);
2177 modification_init(png_modification
*pmm
)
2179 memset(pmm
, 0, sizeof *pmm
);
2182 pmm
->modify_fn
= NULL
;
2184 modification_reset(pmm
);
2187 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
2189 modifier_current_encoding(PNG_CONST png_modifier
*pm
, color_encoding
*ce
)
2191 if (pm
->current_encoding
!= 0)
2192 *ce
= *pm
->current_encoding
;
2195 memset(ce
, 0, sizeof *ce
);
2197 ce
->gamma
= pm
->current_gamma
;
2202 safecat_current_encoding(char *buffer
, size_t bufsize
, size_t pos
,
2203 PNG_CONST png_modifier
*pm
)
2205 pos
= safecat_color_encoding(buffer
, bufsize
, pos
, pm
->current_encoding
,
2208 if (pm
->encoding_ignored
)
2209 pos
= safecat(buffer
, bufsize
, pos
, "[overridden]");
2214 /* Iterate through the usefully testable color encodings. An encoding is one
2217 * 1) Nothing (no color space, no gamma).
2218 * 2) Just a gamma value from the gamma array (including 1.0)
2219 * 3) A color space from the encodings array with the corresponding gamma.
2220 * 4) The same, but with gamma 1.0 (only really useful with 16 bit calculations)
2222 * The iterator selects these in turn, the randomizer selects one at random,
2223 * which is used depends on the setting of the 'test_exhaustive' flag. Notice
2224 * that this function changes the colour space encoding so it must only be
2225 * called on completion of the previous test. This is what 'modifier_reset'
2228 * After the function has been called the 'repeat' flag will still be set; the
2229 * caller of modifier_reset must reset it at the start of each run of the test!
2232 modifier_total_encodings(PNG_CONST png_modifier
*pm
)
2234 return 1 + /* (1) nothing */
2235 pm
->ngammas
+ /* (2) gamma values to test */
2236 pm
->nencodings
+ /* (3) total number of encodings */
2237 /* The following test only works after the first time through the
2238 * png_modifier code because 'bit_depth' is set when the IHDR is read.
2239 * modifier_reset, below, preserves the setting until after it has called
2240 * the iterate function (also below.)
2242 * For this reason do not rely on this function outside a call to
2245 ((pm
->bit_depth
== 16 || pm
->assume_16_bit_calculations
) ?
2246 pm
->nencodings
: 0); /* (4) encodings with gamma == 1.0 */
2250 modifier_encoding_iterate(png_modifier
*pm
)
2252 if (!pm
->repeat
&& /* Else something needs the current encoding again. */
2253 pm
->test_uses_encoding
) /* Some transform is encoding dependent */
2255 if (pm
->test_exhaustive
)
2257 if (++pm
->encoding_counter
>= modifier_total_encodings(pm
))
2258 pm
->encoding_counter
= 0; /* This will stop the repeat */
2263 /* Not exhaustive - choose an encoding at random; generate a number in
2264 * the range 1..(max-1), so the result is always non-zero:
2266 if (pm
->encoding_counter
== 0)
2267 pm
->encoding_counter
= random_mod(modifier_total_encodings(pm
)-1)+1;
2269 pm
->encoding_counter
= 0;
2272 if (pm
->encoding_counter
> 0)
2276 else if (!pm
->repeat
)
2277 pm
->encoding_counter
= 0;
2281 modifier_reset(png_modifier
*pm
)
2283 store_read_reset(&pm
->this);
2285 pm
->pending_len
= pm
->pending_chunk
= 0;
2286 pm
->flush
= pm
->buffer_count
= pm
->buffer_position
= 0;
2287 pm
->modifications
= NULL
;
2288 pm
->state
= modifier_start
;
2289 modifier_encoding_iterate(pm
);
2290 /* The following must be set in the next run. In particular
2291 * test_uses_encodings must be set in the _ini function of each transform
2292 * that looks at the encodings. (Not the 'add' function!)
2294 pm
->test_uses_encoding
= 0;
2295 pm
->current_gamma
= 0;
2296 pm
->current_encoding
= 0;
2297 pm
->encoding_ignored
= 0;
2298 /* These only become value after IHDR is read: */
2299 pm
->bit_depth
= pm
->colour_type
= 0;
2302 /* The following must be called before anything else to get the encoding set up
2303 * on the modifier. In particular it must be called before the transform init
2304 * functions are called.
2307 modifier_set_encoding(png_modifier
*pm
)
2309 /* Set the encoding to the one specified by the current encoding counter,
2310 * first clear out all the settings - this corresponds to an encoding_counter
2313 pm
->current_gamma
= 0;
2314 pm
->current_encoding
= 0;
2315 pm
->encoding_ignored
= 0; /* not ignored yet - happens in _ini functions. */
2317 /* Now, if required, set the gamma and encoding fields. */
2318 if (pm
->encoding_counter
> 0)
2320 /* The gammas[] array is an array of screen gammas, not encoding gammas,
2321 * so we need the inverse:
2323 if (pm
->encoding_counter
<= pm
->ngammas
)
2324 pm
->current_gamma
= 1/pm
->gammas
[pm
->encoding_counter
-1];
2328 unsigned int i
= pm
->encoding_counter
- pm
->ngammas
;
2330 if (i
>= pm
->nencodings
)
2332 i
%= pm
->nencodings
;
2333 pm
->current_gamma
= 1; /* Linear, only in the 16 bit case */
2337 pm
->current_gamma
= pm
->encodings
[i
].gamma
;
2339 pm
->current_encoding
= pm
->encodings
+ i
;
2344 /* Enquiry functions to find out what is set. Notice that there is an implicit
2345 * assumption below that the first encoding in the list is the one for sRGB.
2348 modifier_color_encoding_is_sRGB(PNG_CONST png_modifier
*pm
)
2350 return pm
->current_encoding
!= 0 && pm
->current_encoding
== pm
->encodings
&&
2351 pm
->current_encoding
->gamma
== pm
->current_gamma
;
2355 modifier_color_encoding_is_set(PNG_CONST png_modifier
*pm
)
2357 return pm
->current_gamma
!= 0;
2360 /* Convenience macros. */
2361 #define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d))
2362 #define CHUNK_IHDR CHUNK(73,72,68,82)
2363 #define CHUNK_PLTE CHUNK(80,76,84,69)
2364 #define CHUNK_IDAT CHUNK(73,68,65,84)
2365 #define CHUNK_IEND CHUNK(73,69,78,68)
2366 #define CHUNK_cHRM CHUNK(99,72,82,77)
2367 #define CHUNK_gAMA CHUNK(103,65,77,65)
2368 #define CHUNK_sBIT CHUNK(115,66,73,84)
2369 #define CHUNK_sRGB CHUNK(115,82,71,66)
2371 /* The guts of modification are performed during a read. */
2373 modifier_crc(png_bytep buffer
)
2375 /* Recalculate the chunk CRC - a complete chunk must be in
2376 * the buffer, at the start.
2378 uInt datalen
= png_get_uint_32(buffer
);
2379 uLong crc
= crc32(0, buffer
+4, datalen
+4);
2380 /* The cast to png_uint_32 is safe because a crc32 is always a 32 bit value.
2382 png_save_uint_32(buffer
+datalen
+8, (png_uint_32
)crc
);
2386 modifier_setbuffer(png_modifier
*pm
)
2388 modifier_crc(pm
->buffer
);
2389 pm
->buffer_count
= png_get_uint_32(pm
->buffer
)+12;
2390 pm
->buffer_position
= 0;
2393 /* Separate the callback into the actual implementation (which is passed the
2394 * png_modifier explicitly) and the callback, which gets the modifier from the
2398 modifier_read_imp(png_modifier
*pm
, png_bytep pb
, png_size_t st
)
2403 png_uint_32 len
, chunk
;
2404 png_modification
*mod
;
2406 if (pm
->buffer_position
>= pm
->buffer_count
) switch (pm
->state
)
2408 static png_byte sign
[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
2409 case modifier_start
:
2410 store_read_imp(&pm
->this, pm
->buffer
, 8); /* size of signature. */
2411 pm
->buffer_count
= 8;
2412 pm
->buffer_position
= 0;
2414 if (memcmp(pm
->buffer
, sign
, 8) != 0)
2415 png_error(pm
->this.pread
, "invalid PNG file signature");
2416 pm
->state
= modifier_signature
;
2419 case modifier_signature
:
2420 store_read_imp(&pm
->this, pm
->buffer
, 13+12); /* size of IHDR */
2421 pm
->buffer_count
= 13+12;
2422 pm
->buffer_position
= 0;
2424 if (png_get_uint_32(pm
->buffer
) != 13 ||
2425 png_get_uint_32(pm
->buffer
+4) != CHUNK_IHDR
)
2426 png_error(pm
->this.pread
, "invalid IHDR");
2428 /* Check the list of modifiers for modifications to the IHDR. */
2429 mod
= pm
->modifications
;
2432 if (mod
->chunk
== CHUNK_IHDR
&& mod
->modify_fn
&&
2433 (*mod
->modify_fn
)(pm
, mod
, 0))
2436 modifier_setbuffer(pm
);
2439 /* Ignore removal or add if IHDR! */
2443 /* Cache information from the IHDR (the modified one.) */
2444 pm
->bit_depth
= pm
->buffer
[8+8];
2445 pm
->colour_type
= pm
->buffer
[8+8+1];
2447 pm
->state
= modifier_IHDR
;
2453 /* Read a new chunk and process it until we see PLTE, IDAT or
2454 * IEND. 'flush' indicates that there is still some data to
2455 * output from the preceding chunk.
2457 if ((cb
= pm
->flush
) > 0)
2459 if (cb
> st
) cb
= st
;
2461 store_read_imp(&pm
->this, pb
, cb
);
2464 if (st
== 0) return;
2467 /* No more bytes to flush, read a header, or handle a pending
2470 if (pm
->pending_chunk
!= 0)
2472 png_save_uint_32(pm
->buffer
, pm
->pending_len
);
2473 png_save_uint_32(pm
->buffer
+4, pm
->pending_chunk
);
2474 pm
->pending_len
= 0;
2475 pm
->pending_chunk
= 0;
2478 store_read_imp(&pm
->this, pm
->buffer
, 8);
2480 pm
->buffer_count
= 8;
2481 pm
->buffer_position
= 0;
2483 /* Check for something to modify or a terminator chunk. */
2484 len
= png_get_uint_32(pm
->buffer
);
2485 chunk
= png_get_uint_32(pm
->buffer
+4);
2487 /* Terminators first, they may have to be delayed for added
2490 if (chunk
== CHUNK_PLTE
|| chunk
== CHUNK_IDAT
||
2491 chunk
== CHUNK_IEND
)
2493 mod
= pm
->modifications
;
2497 if ((mod
->add
== chunk
||
2498 (mod
->add
== CHUNK_PLTE
&& chunk
== CHUNK_IDAT
)) &&
2499 mod
->modify_fn
!= NULL
&& !mod
->modified
&& !mod
->added
)
2501 /* Regardless of what the modify function does do not run
2506 if ((*mod
->modify_fn
)(pm
, mod
, 1 /*add*/))
2508 /* Reset the CRC on a new chunk */
2509 if (pm
->buffer_count
> 0)
2510 modifier_setbuffer(pm
);
2514 pm
->buffer_position
= 0;
2518 /* The buffer has been filled with something (we assume)
2519 * so output this. Pend the current chunk.
2521 pm
->pending_len
= len
;
2522 pm
->pending_chunk
= chunk
;
2523 break; /* out of while */
2530 /* Don't do any further processing if the buffer was modified -
2531 * otherwise the code will end up modifying a chunk that was
2535 break; /* out of switch */
2538 /* If we get to here then this chunk may need to be modified. To
2539 * do this it must be less than 1024 bytes in total size, otherwise
2540 * it just gets flushed.
2542 if (len
+12 <= sizeof pm
->buffer
)
2544 store_read_imp(&pm
->this, pm
->buffer
+pm
->buffer_count
,
2545 len
+12-pm
->buffer_count
);
2546 pm
->buffer_count
= len
+12;
2548 /* Check for a modification, else leave it be. */
2549 mod
= pm
->modifications
;
2552 if (mod
->chunk
== chunk
)
2554 if (mod
->modify_fn
== NULL
)
2556 /* Remove this chunk */
2557 pm
->buffer_count
= pm
->buffer_position
= 0;
2559 break; /* Terminate the while loop */
2562 else if ((*mod
->modify_fn
)(pm
, mod
, 0))
2565 /* The chunk may have been removed: */
2566 if (pm
->buffer_count
== 0)
2568 pm
->buffer_position
= 0;
2571 modifier_setbuffer(pm
);
2580 pm
->flush
= len
+12 - pm
->buffer_count
; /* data + crc */
2582 /* Take the data from the buffer (if there is any). */
2586 /* Here to read from the modifier buffer (not directly from
2587 * the store, as in the flush case above.)
2589 cb
= pm
->buffer_count
- pm
->buffer_position
;
2594 memcpy(pb
, pm
->buffer
+ pm
->buffer_position
, cb
);
2597 pm
->buffer_position
+= cb
;
2603 modifier_read(png_structp ppIn
, png_bytep pb
, png_size_t st
)
2605 png_const_structp pp
= ppIn
;
2606 png_modifier
*pm
= voidcast(png_modifier
*, png_get_io_ptr(pp
));
2608 if (pm
== NULL
|| pm
->this.pread
!= pp
)
2609 png_error(pp
, "bad modifier_read call");
2611 modifier_read_imp(pm
, pb
, st
);
2614 /* Like store_progressive_read but the data is getting changed as we go so we
2615 * need a local buffer.
2618 modifier_progressive_read(png_modifier
*pm
, png_structp pp
, png_infop pi
)
2620 if (pm
->this.pread
!= pp
|| pm
->this.current
== NULL
||
2621 pm
->this.next
== NULL
)
2622 png_error(pp
, "store state damaged (progressive)");
2624 /* This is another Horowitz and Hill random noise generator. In this case
2625 * the aim is to stress the progressive reader with truly horrible variable
2626 * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers
2627 * is generated. We could probably just count from 1 to 32767 and get as
2632 static png_uint_32 noise
= 1;
2633 png_size_t cb
, cbAvail
;
2634 png_byte buffer
[512];
2636 /* Generate 15 more bits of stuff: */
2637 noise
= (noise
<< 9) | ((noise
^ (noise
>> (9-5))) & 0x1ff);
2640 /* Check that this number of bytes are available (in the current buffer.)
2641 * (This doesn't quite work - the modifier might delete a chunk; unlikely
2642 * but possible, it doesn't happen at present because the modifier only
2643 * adds chunks to standard images.)
2645 cbAvail
= store_read_buffer_avail(&pm
->this);
2646 if (pm
->buffer_count
> pm
->buffer_position
)
2647 cbAvail
+= pm
->buffer_count
- pm
->buffer_position
;
2651 /* Check for EOF: */
2658 modifier_read_imp(pm
, buffer
, cb
);
2659 png_process_data(pp
, pi
, buffer
, cb
);
2662 /* Check the invariants at the end (if this fails it's a problem in this
2665 if (pm
->buffer_count
> pm
->buffer_position
||
2666 pm
->this.next
!= &pm
->this.current
->data
||
2667 pm
->this.readpos
< pm
->this.current
->datacount
)
2668 png_error(pp
, "progressive read implementation error");
2671 /* Set up a modifier. */
2673 set_modifier_for_read(png_modifier
*pm
, png_infopp ppi
, png_uint_32 id
,
2674 PNG_CONST
char *name
)
2676 /* Do this first so that the modifier fields are cleared even if an error
2677 * happens allocating the png_struct. No allocation is done here so no
2678 * cleanup is required.
2680 pm
->state
= modifier_start
;
2682 pm
->colour_type
= 255;
2684 pm
->pending_len
= 0;
2685 pm
->pending_chunk
= 0;
2687 pm
->buffer_count
= 0;
2688 pm
->buffer_position
= 0;
2690 return set_store_for_read(&pm
->this, ppi
, id
, name
);
2694 /******************************** MODIFICATIONS *******************************/
2695 /* Standard modifications to add chunks. These do not require the _SUPPORTED
2696 * macros because the chunks can be there regardless of whether this specific
2697 * libpng supports them.
2699 typedef struct gama_modification
2701 png_modification
this;
2702 png_fixed_point gamma
;
2703 } gama_modification
;
2706 gama_modify(png_modifier
*pm
, png_modification
*me
, int add
)
2709 /* This simply dumps the given gamma value into the buffer. */
2710 png_save_uint_32(pm
->buffer
, 4);
2711 png_save_uint_32(pm
->buffer
+4, CHUNK_gAMA
);
2712 png_save_uint_32(pm
->buffer
+8, ((gama_modification
*)me
)->gamma
);
2717 gama_modification_init(gama_modification
*me
, png_modifier
*pm
, double gammad
)
2721 modification_init(&me
->this);
2722 me
->this.chunk
= CHUNK_gAMA
;
2723 me
->this.modify_fn
= gama_modify
;
2724 me
->this.add
= CHUNK_PLTE
;
2726 me
->gamma
= (png_fixed_point
)g
;
2727 me
->this.next
= pm
->modifications
;
2728 pm
->modifications
= &me
->this;
2731 typedef struct chrm_modification
2733 png_modification
this;
2734 PNG_CONST color_encoding
*encoding
;
2735 png_fixed_point wx
, wy
, rx
, ry
, gx
, gy
, bx
, by
;
2736 } chrm_modification
;
2739 chrm_modify(png_modifier
*pm
, png_modification
*me
, int add
)
2742 /* As with gAMA this just adds the required cHRM chunk to the buffer. */
2743 png_save_uint_32(pm
->buffer
, 32);
2744 png_save_uint_32(pm
->buffer
+ 4, CHUNK_cHRM
);
2745 png_save_uint_32(pm
->buffer
+ 8, ((chrm_modification
*)me
)->wx
);
2746 png_save_uint_32(pm
->buffer
+12, ((chrm_modification
*)me
)->wy
);
2747 png_save_uint_32(pm
->buffer
+16, ((chrm_modification
*)me
)->rx
);
2748 png_save_uint_32(pm
->buffer
+20, ((chrm_modification
*)me
)->ry
);
2749 png_save_uint_32(pm
->buffer
+24, ((chrm_modification
*)me
)->gx
);
2750 png_save_uint_32(pm
->buffer
+28, ((chrm_modification
*)me
)->gy
);
2751 png_save_uint_32(pm
->buffer
+32, ((chrm_modification
*)me
)->bx
);
2752 png_save_uint_32(pm
->buffer
+36, ((chrm_modification
*)me
)->by
);
2757 chrm_modification_init(chrm_modification
*me
, png_modifier
*pm
,
2758 PNG_CONST color_encoding
*encoding
)
2760 CIE_color white
= white_point(encoding
);
2762 /* Original end points: */
2763 me
->encoding
= encoding
;
2765 /* Chromaticities (in fixed point): */
2766 me
->wx
= fix(chromaticity_x(white
));
2767 me
->wy
= fix(chromaticity_y(white
));
2769 me
->rx
= fix(chromaticity_x(encoding
->red
));
2770 me
->ry
= fix(chromaticity_y(encoding
->red
));
2771 me
->gx
= fix(chromaticity_x(encoding
->green
));
2772 me
->gy
= fix(chromaticity_y(encoding
->green
));
2773 me
->bx
= fix(chromaticity_x(encoding
->blue
));
2774 me
->by
= fix(chromaticity_y(encoding
->blue
));
2776 modification_init(&me
->this);
2777 me
->this.chunk
= CHUNK_cHRM
;
2778 me
->this.modify_fn
= chrm_modify
;
2779 me
->this.add
= CHUNK_PLTE
;
2780 me
->this.next
= pm
->modifications
;
2781 pm
->modifications
= &me
->this;
2784 typedef struct srgb_modification
2786 png_modification
this;
2788 } srgb_modification
;
2791 srgb_modify(png_modifier
*pm
, png_modification
*me
, int add
)
2794 /* As above, ignore add and just make a new chunk */
2795 png_save_uint_32(pm
->buffer
, 1);
2796 png_save_uint_32(pm
->buffer
+4, CHUNK_sRGB
);
2797 pm
->buffer
[8] = ((srgb_modification
*)me
)->intent
;
2802 srgb_modification_init(srgb_modification
*me
, png_modifier
*pm
, png_byte intent
)
2804 modification_init(&me
->this);
2805 me
->this.chunk
= CHUNK_sBIT
;
2807 if (intent
<= 3) /* if valid, else *delete* sRGB chunks */
2809 me
->this.modify_fn
= srgb_modify
;
2810 me
->this.add
= CHUNK_PLTE
;
2811 me
->intent
= intent
;
2816 me
->this.modify_fn
= 0;
2821 me
->this.next
= pm
->modifications
;
2822 pm
->modifications
= &me
->this;
2825 #ifdef PNG_READ_GAMMA_SUPPORTED
2826 typedef struct sbit_modification
2828 png_modification
this;
2830 } sbit_modification
;
2833 sbit_modify(png_modifier
*pm
, png_modification
*me
, int add
)
2835 png_byte sbit
= ((sbit_modification
*)me
)->sbit
;
2836 if (pm
->bit_depth
> sbit
)
2839 switch (pm
->colour_type
)
2859 png_error(pm
->this.pread
,
2860 "unexpected colour type in sBIT modification");
2863 png_save_uint_32(pm
->buffer
, cb
);
2864 png_save_uint_32(pm
->buffer
+4, CHUNK_sBIT
);
2867 (pm
->buffer
+8)[--cb
] = sbit
;
2873 /* Remove the sBIT chunk */
2874 pm
->buffer_count
= pm
->buffer_position
= 0;
2878 return 0; /* do nothing */
2882 sbit_modification_init(sbit_modification
*me
, png_modifier
*pm
, png_byte sbit
)
2884 modification_init(&me
->this);
2885 me
->this.chunk
= CHUNK_sBIT
;
2886 me
->this.modify_fn
= sbit_modify
;
2887 me
->this.add
= CHUNK_PLTE
;
2889 me
->this.next
= pm
->modifications
;
2890 pm
->modifications
= &me
->this;
2892 #endif /* PNG_READ_GAMMA_SUPPORTED */
2893 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
2895 /***************************** STANDARD PNG FILES *****************************/
2896 /* Standard files - write and save standard files. */
2897 /* There are two basic forms of standard images. Those which attempt to have
2898 * all the possible pixel values (not possible for 16bpp images, but a range of
2899 * values are produced) and those which have a range of image sizes. The former
2900 * are used for testing transforms, in particular gamma correction and bit
2901 * reduction and increase. The latter are reserved for testing the behavior of
2902 * libpng with respect to 'odd' image sizes - particularly small images where
2903 * rows become 1 byte and interlace passes disappear.
2905 * The first, most useful, set are the 'transform' images, the second set of
2906 * small images are the 'size' images.
2908 * The transform files are constructed with rows which fit into a 1024 byte row
2909 * buffer. This makes allocation easier below. Further regardless of the file
2910 * format every row has 128 pixels (giving 1024 bytes for 64bpp formats).
2912 * Files are stored with no gAMA or sBIT chunks, with a PLTE only when needed
2913 * and with an ID derived from the colour type, bit depth and interlace type
2914 * as above (FILEID). The width (128) and height (variable) are not stored in
2915 * the FILEID - instead the fields are set to 0, indicating a transform file.
2917 * The size files ar constructed with rows a maximum of 128 bytes wide, allowing
2918 * a maximum width of 16 pixels (for the 64bpp case.) They also have a maximum
2919 * height of 16 rows. The width and height are stored in the FILEID and, being
2920 * non-zero, indicate a size file.
2922 * For palette image (colour type 3) multiple transform images are stored with
2923 * the same bit depth to allow testing of more colour combinations -
2924 * particularly important for testing the gamma code because libpng uses a
2925 * different code path for palette images. For size images a single palette is
2929 /* Make a 'standard' palette. Because there are only 256 entries in a palette
2930 * (maximum) this actually makes a random palette in the hope that enough tests
2931 * will catch enough errors. (Note that the same palette isn't produced every
2932 * time for the same test - it depends on what previous tests have been run -
2933 * but a given set of arguments to pngvalid will always produce the same palette
2934 * at the same test! This is why pseudo-random number generators are useful for
2937 * The store must be open for write when this is called, otherwise an internal
2938 * error will occur. This routine contains its own magic number seed, so the
2939 * palettes generated don't change if there are intervening errors (changing the
2940 * calls to the store_mark seed.)
2942 static store_palette_entry
*
2943 make_standard_palette(png_store
* ps
, int npalette
, int do_tRNS
)
2945 static png_uint_32 palette_seed
[2] = { 0x87654321, 9 };
2948 png_byte values
[256][4];
2950 /* Always put in black and white plus the six primary and secondary colors.
2954 values
[i
][1] = (png_byte
)((i
&1) ? 255U : 0U);
2955 values
[i
][2] = (png_byte
)((i
&2) ? 255U : 0U);
2956 values
[i
][3] = (png_byte
)((i
&4) ? 255U : 0U);
2959 /* Then add 62 grays (one quarter of the remaining 256 slots). */
2962 png_byte random_bytes
[4];
2965 need
[0] = 0; /*got black*/
2966 memset(need
+1, 1, (sizeof need
)-2); /*need these*/
2967 need
[255] = 0; /*but not white*/
2975 make_four_random_bytes(palette_seed
, random_bytes
);
2979 b
= random_bytes
[--j
];
2989 /* Finally add 192 colors at random - don't worry about matches to things we
2990 * already have, chance is less than 1/65536. Don't worry about grays,
2991 * chance is the same, so we get a duplicate or extra gray less than 1 time
2995 make_four_random_bytes(palette_seed
, values
[i
]);
2997 /* Fill in the alpha values in the first byte. Just use all possible values
2998 * (0..255) in an apparently random order:
3001 store_palette_entry
*palette
;
3002 png_byte selector
[4];
3004 make_four_random_bytes(palette_seed
, selector
);
3007 for (i
=0; i
<256; ++i
)
3008 values
[i
][0] = (png_byte
)(i
^ selector
[0]);
3011 for (i
=0; i
<256; ++i
)
3012 values
[i
][0] = 255; /* no transparency/tRNS chunk */
3014 /* 'values' contains 256 ARGB values, but we only need 'npalette'.
3015 * 'npalette' will always be a power of 2: 2, 4, 16 or 256. In the low
3016 * bit depth cases select colors at random, else it is difficult to have
3017 * a set of low bit depth palette test with any chance of a reasonable
3018 * range of colors. Do this by randomly permuting values into the low
3019 * 'npalette' entries using an XOR mask generated here. This also
3020 * permutes the npalette == 256 case in a potentially useful way (there is
3021 * no relationship between palette index and the color value therein!)
3023 palette
= store_write_palette(ps
, npalette
);
3025 for (i
=0; i
<npalette
; ++i
)
3027 palette
[i
].alpha
= values
[i
^ selector
[1]][0];
3028 palette
[i
].red
= values
[i
^ selector
[1]][1];
3029 palette
[i
].green
= values
[i
^ selector
[1]][2];
3030 palette
[i
].blue
= values
[i
^ selector
[1]][3];
3037 /* Initialize a standard palette on a write stream. The 'do_tRNS' argument
3038 * indicates whether or not to also set the tRNS chunk.
3040 /* TODO: the png_structp here can probably be 'const' in the future */
3042 init_standard_palette(png_store
*ps
, png_structp pp
, png_infop pi
, int npalette
,
3045 store_palette_entry
*ppal
= make_standard_palette(ps
, npalette
, do_tRNS
);
3049 png_color palette
[256];
3051 /* Set all entries to detect overread errors. */
3052 for (i
=0; i
<npalette
; ++i
)
3054 palette
[i
].red
= ppal
[i
].red
;
3055 palette
[i
].green
= ppal
[i
].green
;
3056 palette
[i
].blue
= ppal
[i
].blue
;
3059 /* Just in case fill in the rest with detectable values: */
3061 palette
[i
].red
= palette
[i
].green
= palette
[i
].blue
= 42;
3063 png_set_PLTE(pp
, pi
, palette
, npalette
);
3071 /* Set all the entries, but skip trailing opaque entries */
3072 for (i
=j
=0; i
<npalette
; ++i
)
3073 if ((tRNS
[i
] = ppal
[i
].alpha
) < 255)
3076 /* Fill in the remainder with a detectable value: */
3081 png_set_tRNS(pp
, pi
, tRNS
, j
, 0/*color*/);
3085 /* The number of passes is related to the interlace type. There was no libpng
3086 * API to determine this prior to 1.5, so we need an inquiry function:
3089 npasses_from_interlace_type(png_const_structp pp
, int interlace_type
)
3091 switch (interlace_type
)
3094 png_error(pp
, "invalid interlace type");
3096 case PNG_INTERLACE_NONE
:
3099 case PNG_INTERLACE_ADAM7
:
3100 return PNG_INTERLACE_ADAM7_PASSES
;
3105 bit_size(png_const_structp pp
, png_byte colour_type
, png_byte bit_depth
)
3107 switch (colour_type
)
3109 default: png_error(pp
, "invalid color type");
3111 case 0: return bit_depth
;
3113 case 2: return 3*bit_depth
;
3115 case 3: return bit_depth
;
3117 case 4: return 2*bit_depth
;
3119 case 6: return 4*bit_depth
;
3123 #define TRANSFORM_WIDTH 128U
3124 #define TRANSFORM_ROWMAX (TRANSFORM_WIDTH*8U)
3125 #define SIZE_ROWMAX (16*8U) /* 16 pixels, max 8 bytes each - 128 bytes */
3126 #define STANDARD_ROWMAX TRANSFORM_ROWMAX /* The larger of the two */
3127 #define SIZE_HEIGHTMAX 16 /* Maximum range of size images */
3130 transform_rowsize(png_const_structp pp
, png_byte colour_type
,
3133 return (TRANSFORM_WIDTH
* bit_size(pp
, colour_type
, bit_depth
)) / 8;
3136 /* transform_width(pp, colour_type, bit_depth) current returns the same number
3137 * every time, so just use a macro:
3139 #define transform_width(pp, colour_type, bit_depth) TRANSFORM_WIDTH
3142 transform_height(png_const_structp pp
, png_byte colour_type
, png_byte bit_depth
)
3144 switch (bit_size(pp
, colour_type
, bit_depth
))
3149 return 1; /* Total of 128 pixels */
3152 return 2; /* Total of 256 pixels/bytes */
3155 return 512; /* Total of 65536 pixels */
3159 return 512; /* 65536 pixels */
3163 return 2048;/* 4 x 65536 pixels. */
3164 # define TRANSFORM_HEIGHTMAX 2048
3167 return 0; /* Error, will be caught later */
3171 #ifdef PNG_READ_SUPPORTED
3172 /* The following can only be defined here, now we have the definitions
3173 * of the transform image sizes.
3176 standard_width(png_const_structp pp
, png_uint_32 id
)
3178 png_uint_32 width
= WIDTH_FROM_ID(id
);
3182 width
= transform_width(pp
, COL_FROM_ID(id
), DEPTH_FROM_ID(id
));
3188 standard_height(png_const_structp pp
, png_uint_32 id
)
3190 png_uint_32 height
= HEIGHT_FROM_ID(id
);
3193 height
= transform_height(pp
, COL_FROM_ID(id
), DEPTH_FROM_ID(id
));
3199 standard_rowsize(png_const_structp pp
, png_uint_32 id
)
3201 png_uint_32 width
= standard_width(pp
, id
);
3203 /* This won't overflow: */
3204 width
*= bit_size(pp
, COL_FROM_ID(id
), DEPTH_FROM_ID(id
));
3205 return (width
+ 7) / 8;
3207 #endif /* PNG_READ_SUPPORTED */
3210 transform_row(png_const_structp pp
, png_byte buffer
[TRANSFORM_ROWMAX
],
3211 png_byte colour_type
, png_byte bit_depth
, png_uint_32 y
)
3213 png_uint_32 v
= y
<< 7;
3216 switch (bit_size(pp
, colour_type
, bit_depth
))
3219 while (i
<128/8) buffer
[i
] = (png_byte
)(v
& 0xff), v
+= 17, ++i
;
3223 while (i
<128/4) buffer
[i
] = (png_byte
)(v
& 0xff), v
+= 33, ++i
;
3227 while (i
<128/2) buffer
[i
] = (png_byte
)(v
& 0xff), v
+= 65, ++i
;
3231 /* 256 bytes total, 128 bytes in each row set as follows: */
3232 while (i
<128) buffer
[i
] = (png_byte
)(v
& 0xff), ++v
, ++i
;
3236 /* Generate all 65536 pixel values in order, which includes the 8 bit
3237 * GA case as well as the 16 bit G case.
3241 buffer
[2*i
] = (png_byte
)((v
>>8) & 0xff);
3242 buffer
[2*i
+1] = (png_byte
)(v
& 0xff);
3250 /* 65535 pixels, but rotate the values. */
3253 /* Three bytes per pixel, r, g, b, make b by r^g */
3254 buffer
[3*i
+0] = (png_byte
)((v
>> 8) & 0xff);
3255 buffer
[3*i
+1] = (png_byte
)(v
& 0xff);
3256 buffer
[3*i
+2] = (png_byte
)(((v
>> 8) ^ v
) & 0xff);
3264 /* 65535 pixels, r, g, b, a; just replicate */
3267 buffer
[4*i
+0] = (png_byte
)((v
>> 8) & 0xff);
3268 buffer
[4*i
+1] = (png_byte
)(v
& 0xff);
3269 buffer
[4*i
+2] = (png_byte
)((v
>> 8) & 0xff);
3270 buffer
[4*i
+3] = (png_byte
)(v
& 0xff);
3278 /* y is maximum 2047, giving 4x65536 pixels, make 'r' increase by 1 at
3279 * each pixel, g increase by 257 (0x101) and 'b' by 0x1111:
3283 png_uint_32 t
= v
++;
3284 buffer
[6*i
+0] = (png_byte
)((t
>> 8) & 0xff);
3285 buffer
[6*i
+1] = (png_byte
)(t
& 0xff);
3287 buffer
[6*i
+2] = (png_byte
)((t
>> 8) & 0xff);
3288 buffer
[6*i
+3] = (png_byte
)(t
& 0xff);
3290 buffer
[6*i
+4] = (png_byte
)((t
>> 8) & 0xff);
3291 buffer
[6*i
+5] = (png_byte
)(t
& 0xff);
3298 /* As above in the 32 bit case. */
3301 png_uint_32 t
= v
++;
3302 buffer
[8*i
+0] = (png_byte
)((t
>> 8) & 0xff);
3303 buffer
[8*i
+1] = (png_byte
)(t
& 0xff);
3304 buffer
[8*i
+4] = (png_byte
)((t
>> 8) & 0xff);
3305 buffer
[8*i
+5] = (png_byte
)(t
& 0xff);
3307 buffer
[8*i
+2] = (png_byte
)((t
>> 8) & 0xff);
3308 buffer
[8*i
+3] = (png_byte
)(t
& 0xff);
3309 buffer
[8*i
+6] = (png_byte
)((t
>> 8) & 0xff);
3310 buffer
[8*i
+7] = (png_byte
)(t
& 0xff);
3319 png_error(pp
, "internal error");
3322 /* This is just to do the right cast - could be changed to a function to check
3323 * 'bd' but there isn't much point.
3325 #define DEPTH(bd) ((png_byte)(1U << (bd)))
3327 /* Make a standardized image given a an image colour type, bit depth and
3328 * interlace type. The standard images have a very restricted range of
3329 * rows and heights and are used for testing transforms rather than image
3330 * layout details. See make_size_images below for a way to make images
3331 * that test odd sizes along with the libpng interlace handling.
3334 make_transform_image(png_store
* PNG_CONST ps
, png_byte PNG_CONST colour_type
,
3335 png_byte PNG_CONST bit_depth
, unsigned int palette_number
,
3336 int interlace_type
, png_const_charp name
)
3343 png_structp pp
= set_store_for_write(ps
, &pi
, name
);
3346 /* In the event of a problem return control to the Catch statement below
3347 * to do the clean up - it is not possible to 'return' directly from a Try
3353 h
= transform_height(pp
, colour_type
, bit_depth
);
3355 png_set_IHDR(pp
, pi
, transform_width(pp
, colour_type
, bit_depth
), h
,
3356 bit_depth
, colour_type
, interlace_type
,
3357 PNG_COMPRESSION_TYPE_BASE
, PNG_FILTER_TYPE_BASE
);
3359 #ifdef PNG_TEXT_SUPPORTED
3360 # if defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED)
3361 # define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_zTXt
3363 # define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_NONE
3366 static char key
[] = "image name"; /* must be writeable */
3369 char copy
[FILE_NAME_SIZE
];
3371 /* Use a compressed text string to test the correct interaction of text
3372 * compression and IDAT compression.
3374 text
.compression
= TEXT_COMPRESSION
;
3376 /* Yuck: the text must be writable! */
3377 pos
= safecat(copy
, sizeof copy
, 0, ps
->wname
);
3379 text
.text_length
= pos
;
3380 text
.itxt_length
= 0;
3384 png_set_text(pp
, pi
, &text
, 1);
3388 if (colour_type
== 3) /* palette */
3389 init_standard_palette(ps
, pp
, pi
, 1U << bit_depth
, 1/*do tRNS*/);
3391 png_write_info(pp
, pi
);
3393 if (png_get_rowbytes(pp
, pi
) !=
3394 transform_rowsize(pp
, colour_type
, bit_depth
))
3395 png_error(pp
, "row size incorrect");
3399 /* Somewhat confusingly this must be called *after* png_write_info
3400 * because if it is called before, the information in *pp has not been
3401 * updated to reflect the interlaced image.
3403 int npasses
= png_set_interlace_handling(pp
);
3406 if (npasses
!= npasses_from_interlace_type(pp
, interlace_type
))
3407 png_error(pp
, "write: png_set_interlace_handling failed");
3409 for (pass
=0; pass
<npasses
; ++pass
)
3415 png_byte buffer
[TRANSFORM_ROWMAX
];
3417 transform_row(pp
, buffer
, colour_type
, bit_depth
, y
);
3418 png_write_row(pp
, buffer
);
3423 #ifdef PNG_TEXT_SUPPORTED
3425 static char key
[] = "end marker";
3426 static char comment
[] = "end";
3429 /* Use a compressed text string to test the correct interaction of text
3430 * compression and IDAT compression.
3432 text
.compression
= TEXT_COMPRESSION
;
3434 text
.text
= comment
;
3435 text
.text_length
= (sizeof comment
)-1;
3436 text
.itxt_length
= 0;
3440 png_set_text(pp
, pi
, &text
, 1);
3444 png_write_end(pp
, pi
);
3446 /* And store this under the appropriate id, then clean up. */
3447 store_storefile(ps
, FILEID(colour_type
, bit_depth
, palette_number
,
3448 interlace_type
, 0, 0, 0));
3450 store_write_reset(ps
);
3455 /* Use the png_store returned by the exception. This may help the compiler
3456 * because 'ps' is not used in this branch of the setjmp. Note that fault
3457 * and ps will always be the same value.
3459 store_write_reset(fault
);
3464 make_transform_images(png_store
*ps
)
3466 png_byte colour_type
= 0;
3467 png_byte bit_depth
= 0;
3468 unsigned int palette_number
= 0;
3470 /* This is in case of errors. */
3471 safecat(ps
->test
, sizeof ps
->test
, 0, "make standard images");
3473 /* Use next_format to enumerate all the combinations we test, including
3474 * generating multiple low bit depth palette images.
3476 while (next_format(&colour_type
, &bit_depth
, &palette_number
))
3480 for (interlace_type
= PNG_INTERLACE_NONE
;
3481 interlace_type
< PNG_INTERLACE_LAST
; ++interlace_type
)
3483 char name
[FILE_NAME_SIZE
];
3485 standard_name(name
, sizeof name
, 0, colour_type
, bit_depth
,
3486 palette_number
, interlace_type
, 0, 0, 0);
3487 make_transform_image(ps
, colour_type
, bit_depth
, palette_number
,
3488 interlace_type
, name
);
3493 /* The following two routines use the PNG interlace support macros from
3494 * png.h to interlace or deinterlace rows.
3497 interlace_row(png_bytep buffer
, png_const_bytep imageRow
,
3498 unsigned int pixel_size
, png_uint_32 w
, int pass
)
3500 png_uint_32 xin
, xout
, xstep
;
3502 /* Note that this can, trivially, be optimized to a memcpy on pass 7, the
3503 * code is presented this way to make it easier to understand. In practice
3504 * consult the code in the libpng source to see other ways of doing this.
3506 xin
= PNG_PASS_START_COL(pass
);
3507 xstep
= 1U<<PNG_PASS_COL_SHIFT(pass
);
3509 for (xout
=0; xin
<w
; xin
+=xstep
)
3511 pixel_copy(buffer
, xout
, imageRow
, xin
, pixel_size
);
3516 #ifdef PNG_READ_SUPPORTED
3518 deinterlace_row(png_bytep buffer
, png_const_bytep row
,
3519 unsigned int pixel_size
, png_uint_32 w
, int pass
)
3521 /* The inverse of the above, 'row' is part of row 'y' of the output image,
3522 * in 'buffer'. The image is 'w' wide and this is pass 'pass', distribute
3523 * the pixels of row into buffer and return the number written (to allow
3524 * this to be checked).
3526 png_uint_32 xin
, xout
, xstep
;
3528 xout
= PNG_PASS_START_COL(pass
);
3529 xstep
= 1U<<PNG_PASS_COL_SHIFT(pass
);
3531 for (xin
=0; xout
<w
; xout
+=xstep
)
3533 pixel_copy(buffer
, xout
, row
, xin
, pixel_size
);
3537 #endif /* PNG_READ_SUPPORTED */
3539 /* Build a single row for the 'size' test images; this fills in only the
3540 * first bit_width bits of the sample row.
3543 size_row(png_byte buffer
[SIZE_ROWMAX
], png_uint_32 bit_width
, png_uint_32 y
)
3545 /* height is in the range 1 to 16, so: */
3546 y
= ((y
& 1) << 7) + ((y
& 2) << 6) + ((y
& 4) << 5) + ((y
& 8) << 4);
3547 /* the following ensures bits are set in small images: */
3550 while (bit_width
>= 8)
3551 *buffer
++ = (png_byte
)y
++, bit_width
-= 8;
3553 /* There may be up to 7 remaining bits, these go in the most significant
3558 png_uint_32 mask
= (1U<<(8-bit_width
))-1;
3559 *buffer
= (png_byte
)((*buffer
& mask
) | (y
& ~mask
));
3564 make_size_image(png_store
* PNG_CONST ps
, png_byte PNG_CONST colour_type
,
3565 png_byte PNG_CONST bit_depth
, int PNG_CONST interlace_type
,
3566 png_uint_32 PNG_CONST w
, png_uint_32 PNG_CONST h
,
3567 int PNG_CONST do_interlace
)
3575 unsigned int pixel_size
;
3577 /* Make a name and get an appropriate id for the store: */
3578 char name
[FILE_NAME_SIZE
];
3579 PNG_CONST png_uint_32 id
= FILEID(colour_type
, bit_depth
, 0/*palette*/,
3580 interlace_type
, w
, h
, do_interlace
);
3582 standard_name_from_id(name
, sizeof name
, 0, id
);
3583 pp
= set_store_for_write(ps
, &pi
, name
);
3585 /* In the event of a problem return control to the Catch statement below
3586 * to do the clean up - it is not possible to 'return' directly from a Try
3592 png_set_IHDR(pp
, pi
, w
, h
, bit_depth
, colour_type
, interlace_type
,
3593 PNG_COMPRESSION_TYPE_BASE
, PNG_FILTER_TYPE_BASE
);
3595 #ifdef PNG_TEXT_SUPPORTED
3597 static char key
[] = "image name"; /* must be writeable */
3600 char copy
[FILE_NAME_SIZE
];
3602 /* Use a compressed text string to test the correct interaction of text
3603 * compression and IDAT compression.
3605 text
.compression
= TEXT_COMPRESSION
;
3607 /* Yuck: the text must be writable! */
3608 pos
= safecat(copy
, sizeof copy
, 0, ps
->wname
);
3610 text
.text_length
= pos
;
3611 text
.itxt_length
= 0;
3615 png_set_text(pp
, pi
, &text
, 1);
3619 if (colour_type
== 3) /* palette */
3620 init_standard_palette(ps
, pp
, pi
, 1U << bit_depth
, 0/*do tRNS*/);
3622 png_write_info(pp
, pi
);
3624 /* Calculate the bit size, divide by 8 to get the byte size - this won't
3625 * overflow because we know the w values are all small enough even for
3626 * a system where 'unsigned int' is only 16 bits.
3628 pixel_size
= bit_size(pp
, colour_type
, bit_depth
);
3629 if (png_get_rowbytes(pp
, pi
) != ((w
* pixel_size
) + 7) / 8)
3630 png_error(pp
, "row size incorrect");
3634 int npasses
= npasses_from_interlace_type(pp
, interlace_type
);
3637 png_byte image
[16][SIZE_ROWMAX
];
3639 /* To help consistent error detection make the parts of this buffer
3640 * that aren't set below all '1':
3642 memset(image
, 0xff, sizeof image
);
3644 if (!do_interlace
&& npasses
!= png_set_interlace_handling(pp
))
3645 png_error(pp
, "write: png_set_interlace_handling failed");
3647 /* Prepare the whole image first to avoid making it 7 times: */
3649 size_row(image
[y
], w
* pixel_size
, y
);
3651 for (pass
=0; pass
<npasses
; ++pass
)
3653 /* The following two are for checking the macros: */
3654 PNG_CONST png_uint_32 wPass
= PNG_PASS_COLS(w
, pass
);
3656 /* If do_interlace is set we don't call png_write_row for every
3657 * row because some of them are empty. In fact, for a 1x1 image,
3658 * most of them are empty!
3662 png_const_bytep row
= image
[y
];
3663 png_byte tempRow
[SIZE_ROWMAX
];
3665 /* If do_interlace *and* the image is interlaced we
3666 * need a reduced interlace row; this may be reduced
3669 if (do_interlace
&& interlace_type
== PNG_INTERLACE_ADAM7
)
3671 /* The row must not be written if it doesn't exist, notice
3672 * that there are two conditions here, either the row isn't
3673 * ever in the pass or the row would be but isn't wide
3674 * enough to contribute any pixels. In fact the wPass test
3675 * can be used to skip the whole y loop in this case.
3677 if (PNG_ROW_IN_INTERLACE_PASS(y
, pass
) && wPass
> 0)
3679 /* Set to all 1's for error detection (libpng tends to
3680 * set unset things to 0).
3682 memset(tempRow
, 0xff, sizeof tempRow
);
3683 interlace_row(tempRow
, row
, pixel_size
, w
, pass
);
3690 /* Only get to here if the row has some pixels in it. */
3691 png_write_row(pp
, row
);
3696 #ifdef PNG_TEXT_SUPPORTED
3698 static char key
[] = "end marker";
3699 static char comment
[] = "end";
3702 /* Use a compressed text string to test the correct interaction of text
3703 * compression and IDAT compression.
3705 text
.compression
= TEXT_COMPRESSION
;
3707 text
.text
= comment
;
3708 text
.text_length
= (sizeof comment
)-1;
3709 text
.itxt_length
= 0;
3713 png_set_text(pp
, pi
, &text
, 1);
3717 png_write_end(pp
, pi
);
3719 /* And store this under the appropriate id, then clean up. */
3720 store_storefile(ps
, id
);
3722 store_write_reset(ps
);
3727 /* Use the png_store returned by the exception. This may help the compiler
3728 * because 'ps' is not used in this branch of the setjmp. Note that fault
3729 * and ps will always be the same value.
3731 store_write_reset(fault
);
3736 make_size(png_store
* PNG_CONST ps
, png_byte PNG_CONST colour_type
, int bdlo
,
3739 for (; bdlo
<= bdhi
; ++bdlo
)
3743 for (width
= 1; width
<= 16; ++width
)
3747 for (height
= 1; height
<= 16; ++height
)
3749 /* The four combinations of DIY interlace and interlace or not -
3750 * no interlace + DIY should be identical to no interlace with
3753 make_size_image(ps
, colour_type
, DEPTH(bdlo
), PNG_INTERLACE_NONE
,
3755 make_size_image(ps
, colour_type
, DEPTH(bdlo
), PNG_INTERLACE_NONE
,
3757 make_size_image(ps
, colour_type
, DEPTH(bdlo
), PNG_INTERLACE_ADAM7
,
3759 make_size_image(ps
, colour_type
, DEPTH(bdlo
), PNG_INTERLACE_ADAM7
,
3767 make_size_images(png_store
*ps
)
3769 /* This is in case of errors. */
3770 safecat(ps
->test
, sizeof ps
->test
, 0, "make size images");
3772 /* Arguments are colour_type, low bit depth, high bit depth
3774 make_size(ps
, 0, 0, WRITE_BDHI
);
3775 make_size(ps
, 2, 3, WRITE_BDHI
);
3776 make_size(ps
, 3, 0, 3 /*palette: max 8 bits*/);
3777 make_size(ps
, 4, 3, WRITE_BDHI
);
3778 make_size(ps
, 6, 3, WRITE_BDHI
);
3781 #ifdef PNG_READ_SUPPORTED
3782 /* Return a row based on image id and 'y' for checking: */
3784 standard_row(png_const_structp pp
, png_byte std
[STANDARD_ROWMAX
],
3785 png_uint_32 id
, png_uint_32 y
)
3787 if (WIDTH_FROM_ID(id
) == 0)
3788 transform_row(pp
, std
, COL_FROM_ID(id
), DEPTH_FROM_ID(id
), y
);
3790 size_row(std
, WIDTH_FROM_ID(id
) * bit_size(pp
, COL_FROM_ID(id
),
3791 DEPTH_FROM_ID(id
)), y
);
3793 #endif /* PNG_READ_SUPPORTED */
3795 /* Tests - individual test cases */
3796 /* Like 'make_standard' but errors are deliberately introduced into the calls
3797 * to ensure that they get detected - it should not be possible to write an
3798 * invalid image with libpng!
3800 /* TODO: the 'set' functions can probably all be made to take a
3801 * png_const_structp rather than a modifiable one.
3803 #ifdef PNG_WARNINGS_SUPPORTED
3805 sBIT0_error_fn(png_structp pp
, png_infop pi
)
3807 /* 0 is invalid... */
3809 bad
.red
= bad
.green
= bad
.blue
= bad
.gray
= bad
.alpha
= 0;
3810 png_set_sBIT(pp
, pi
, &bad
);
3814 sBIT_error_fn(png_structp pp
, png_infop pi
)
3819 if (png_get_color_type(pp
, pi
) == PNG_COLOR_TYPE_PALETTE
)
3823 bit_depth
= png_get_bit_depth(pp
, pi
);
3825 /* Now we know the bit depth we can easily generate an invalid sBIT entry */
3826 bad
.red
= bad
.green
= bad
.blue
= bad
.gray
= bad
.alpha
=
3827 (png_byte
)(bit_depth
+1);
3828 png_set_sBIT(pp
, pi
, &bad
);
3831 static PNG_CONST
struct
3833 void (*fn
)(png_structp
, png_infop
);
3834 PNG_CONST
char *msg
;
3835 unsigned int warning
:1; /* the error is a warning... */
3838 /* no warnings makes these errors undetectable. */
3839 { sBIT0_error_fn
, "sBIT(0): failed to detect error", 1 },
3840 { sBIT_error_fn
, "sBIT(too big): failed to detect error", 1 },
3844 make_error(png_store
* volatile psIn
, png_byte PNG_CONST colour_type
,
3845 png_byte bit_depth
, int interlace_type
, int test
, png_const_charp name
)
3847 png_store
* volatile ps
= psIn
;
3856 pp
= set_store_for_write(ps
, &pi
, name
);
3861 png_set_IHDR(pp
, pi
, transform_width(pp
, colour_type
, bit_depth
),
3862 transform_height(pp
, colour_type
, bit_depth
), bit_depth
, colour_type
,
3863 interlace_type
, PNG_COMPRESSION_TYPE_BASE
, PNG_FILTER_TYPE_BASE
);
3865 if (colour_type
== 3) /* palette */
3866 init_standard_palette(ps
, pp
, pi
, 1U << bit_depth
, 0/*do tRNS*/);
3868 /* Time for a few errors; these are in various optional chunks, the
3869 * standard tests test the standard chunks pretty well.
3871 # define exception__prev exception_prev_1
3872 # define exception__env exception_env_1
3875 /* Expect this to throw: */
3876 ps
->expect_error
= !error_test
[test
].warning
;
3877 ps
->expect_warning
= error_test
[test
].warning
;
3878 ps
->saw_warning
= 0;
3879 error_test
[test
].fn(pp
, pi
);
3881 /* Normally the error is only detected here: */
3882 png_write_info(pp
, pi
);
3884 /* And handle the case where it was only a warning: */
3885 if (ps
->expect_warning
&& ps
->saw_warning
)
3888 /* If we get here there is a problem, we have success - no error or
3889 * no warning - when we shouldn't have success. Log an error.
3891 store_log(ps
, pp
, error_test
[test
].msg
, 1 /*error*/);
3895 ps
= fault
; /* expected exit, make sure ps is not clobbered */
3896 #undef exception__prev
3897 #undef exception__env
3899 /* And clear these flags */
3900 ps
->expect_error
= 0;
3901 ps
->expect_warning
= 0;
3903 /* Now write the whole image, just to make sure that the detected, or
3904 * undetected, errro has not created problems inside libpng.
3906 if (png_get_rowbytes(pp
, pi
) !=
3907 transform_rowsize(pp
, colour_type
, bit_depth
))
3908 png_error(pp
, "row size incorrect");
3912 png_uint_32 h
= transform_height(pp
, colour_type
, bit_depth
);
3913 int npasses
= png_set_interlace_handling(pp
);
3916 if (npasses
!= npasses_from_interlace_type(pp
, interlace_type
))
3917 png_error(pp
, "write: png_set_interlace_handling failed");
3919 for (pass
=0; pass
<npasses
; ++pass
)
3925 png_byte buffer
[TRANSFORM_ROWMAX
];
3927 transform_row(pp
, buffer
, colour_type
, bit_depth
, y
);
3928 png_write_row(pp
, buffer
);
3933 png_write_end(pp
, pi
);
3935 /* The following deletes the file that was just written. */
3936 store_write_reset(ps
);
3941 store_write_reset(fault
);
3946 make_errors(png_modifier
* PNG_CONST pm
, png_byte PNG_CONST colour_type
,
3947 int bdlo
, int PNG_CONST bdhi
)
3949 for (; bdlo
<= bdhi
; ++bdlo
)
3953 for (interlace_type
= PNG_INTERLACE_NONE
;
3954 interlace_type
< PNG_INTERLACE_LAST
; ++interlace_type
)
3957 char name
[FILE_NAME_SIZE
];
3959 standard_name(name
, sizeof name
, 0, colour_type
, 1<<bdlo
, 0,
3960 interlace_type
, 0, 0, 0);
3962 for (test
=0; test
<(sizeof error_test
)/(sizeof error_test
[0]); ++test
)
3964 make_error(&pm
->this, colour_type
, DEPTH(bdlo
), interlace_type
,
3973 return 1; /* keep going */
3978 perform_error_test(png_modifier
*pm
)
3980 #ifdef PNG_WARNINGS_SUPPORTED /* else there are no cases that work! */
3981 /* Need to do this here because we just write in this test. */
3982 safecat(pm
->this.test
, sizeof pm
->this.test
, 0, "error test");
3984 if (!make_errors(pm
, 0, 0, WRITE_BDHI
))
3987 if (!make_errors(pm
, 2, 3, WRITE_BDHI
))
3990 if (!make_errors(pm
, 3, 0, 3))
3993 if (!make_errors(pm
, 4, 3, WRITE_BDHI
))
3996 if (!make_errors(pm
, 6, 3, WRITE_BDHI
))
4003 /* This is just to validate the internal PNG formatting code - if this fails
4004 * then the warning messages the library outputs will probably be garbage.
4007 perform_formatting_test(png_store
*volatile ps
)
4009 #ifdef PNG_TIME_RFC1123_SUPPORTED
4010 /* The handle into the formatting code is the RFC1123 support; this test does
4011 * nothing if that is compiled out.
4017 png_const_charp correct
= "29 Aug 2079 13:53:60 +0000";
4018 png_const_charp result
;
4019 # if PNG_LIBPNG_VER >= 10600
4020 char timestring
[29];
4025 pp
= set_store_for_write(ps
, NULL
, "libpng formatting test");
4031 /* Arbitrary settings: */
4037 pt
.second
= 60; /* a leap second */
4039 # if PNG_LIBPNG_VER < 10600
4040 result
= png_convert_to_rfc1123(pp
, &pt
);
4042 if (png_convert_to_rfc1123_buffer(timestring
, &pt
))
4043 result
= timestring
;
4050 png_error(pp
, "png_convert_to_rfc1123 failed");
4052 if (strcmp(result
, correct
) != 0)
4057 pos
= safecat(msg
, sizeof msg
, pos
, "png_convert_to_rfc1123(");
4058 pos
= safecat(msg
, sizeof msg
, pos
, correct
);
4059 pos
= safecat(msg
, sizeof msg
, pos
, ") returned: '");
4060 pos
= safecat(msg
, sizeof msg
, pos
, result
);
4061 pos
= safecat(msg
, sizeof msg
, pos
, "'");
4066 store_write_reset(ps
);
4071 store_write_reset(fault
);
4078 #ifdef PNG_READ_SUPPORTED
4079 /* Because we want to use the same code in both the progressive reader and the
4080 * sequential reader it is necessary to deal with the fact that the progressive
4081 * reader callbacks only have one parameter (png_get_progressive_ptr()), so this
4082 * must contain all the test parameters and all the local variables directly
4083 * accessible to the sequential reader implementation.
4085 * The technique adopted is to reinvent part of what Dijkstra termed a
4086 * 'display'; an array of pointers to the stack frames of enclosing functions so
4087 * that a nested function definition can access the local (C auto) variables of
4088 * the functions that contain its definition. In fact C provides the first
4089 * pointer (the local variables - the stack frame pointer) and the last (the
4090 * global variables - the BCPL global vector typically implemented as global
4091 * addresses), this code requires one more pointer to make the display - the
4092 * local variables (and function call parameters) of the function that actually
4093 * invokes either the progressive or sequential reader.
4095 * Perhaps confusingly this technique is confounded with classes - the
4096 * 'standard_display' defined here is sub-classed as the 'gamma_display' below.
4097 * A gamma_display is a standard_display, taking advantage of the ANSI-C
4098 * requirement that the pointer to the first member of a structure must be the
4099 * same as the pointer to the structure. This allows us to reuse standard_
4100 * functions in the gamma test code; something that could not be done with
4103 typedef struct standard_display
4105 png_store
* ps
; /* Test parameters (passed to the function) */
4106 png_byte colour_type
;
4108 png_byte red_sBIT
; /* Input data sBIT values. */
4109 png_byte green_sBIT
;
4111 png_byte alpha_sBIT
;
4113 png_uint_32 id
; /* Calculated file ID */
4114 png_uint_32 w
; /* Width of image */
4115 png_uint_32 h
; /* Height of image */
4116 int npasses
; /* Number of interlaced passes */
4117 png_uint_32 pixel_size
; /* Width of one pixel in bits */
4118 png_uint_32 bit_width
; /* Width of output row in bits */
4119 size_t cbRow
; /* Bytes in a row of the output image */
4120 int do_interlace
; /* Do interlacing internally */
4121 int is_transparent
; /* Transparency information was present. */
4122 int speed
; /* Doing a speed test */
4123 int use_update_info
;/* Call update_info, not start_image */
4129 } transparent
; /* The transparent color, if set. */
4130 int npalette
; /* Number of entries in the palette. */
4136 standard_display_init(standard_display
*dp
, png_store
* ps
, png_uint_32 id
,
4137 int do_interlace
, int use_update_info
)
4139 memset(dp
, 0, sizeof *dp
);
4142 dp
->colour_type
= COL_FROM_ID(id
);
4143 dp
->bit_depth
= DEPTH_FROM_ID(id
);
4144 if (dp
->bit_depth
< 1 || dp
->bit_depth
> 16)
4145 internal_error(ps
, "internal: bad bit depth");
4146 if (dp
->colour_type
== 3)
4147 dp
->red_sBIT
= dp
->blue_sBIT
= dp
->green_sBIT
= dp
->alpha_sBIT
= 8;
4149 dp
->red_sBIT
= dp
->blue_sBIT
= dp
->green_sBIT
= dp
->alpha_sBIT
=
4151 dp
->interlace_type
= INTERLACE_FROM_ID(id
);
4153 /* All the rest are filled in after the read_info: */
4160 dp
->do_interlace
= do_interlace
;
4161 dp
->is_transparent
= 0;
4162 dp
->speed
= ps
->speed
;
4163 dp
->use_update_info
= use_update_info
;
4165 /* Preset the transparent color to black: */
4166 memset(&dp
->transparent
, 0, sizeof dp
->transparent
);
4167 /* Preset the palette to full intensity/opaque througout: */
4168 memset(dp
->palette
, 0xff, sizeof dp
->palette
);
4171 /* Initialize the palette fields - this must be done later because the palette
4172 * comes from the particular png_store_file that is selected.
4175 standard_palette_init(standard_display
*dp
)
4177 store_palette_entry
*palette
= store_current_palette(dp
->ps
, &dp
->npalette
);
4179 /* The remaining entries remain white/opaque. */
4180 if (dp
->npalette
> 0)
4182 int i
= dp
->npalette
;
4183 memcpy(dp
->palette
, palette
, i
* sizeof *palette
);
4185 /* Check for a non-opaque palette entry: */
4187 if (palette
[i
].alpha
< 255)
4191 /* GCC can't handle the more obviously optimizable version. */
4193 dp
->is_transparent
= 1;
4195 dp
->is_transparent
= 0;
4197 dp
->is_transparent
= (i
>= 0);
4202 /* Utility to read the palette from the PNG file and convert it into
4203 * store_palette format. This returns 1 if there is any transparency in the
4204 * palette (it does not check for a transparent colour in the non-palette case.)
4207 read_palette(store_palette palette
, int *npalette
, png_const_structp pp
,
4211 png_bytep trans_alpha
;
4217 if (png_get_PLTE(pp
, pi
, &pal
, npalette
) & PNG_INFO_PLTE
)
4221 if (i
<= 0 || i
> 256)
4222 png_error(pp
, "validate: invalid PLTE count");
4226 palette
[i
].red
= pal
[i
].red
;
4227 palette
[i
].green
= pal
[i
].green
;
4228 palette
[i
].blue
= pal
[i
].blue
;
4231 /* Mark the remainder of the entries with a flag value (other than
4232 * white/opaque which is the flag value stored above.)
4234 memset(palette
+ *npalette
, 126, (256-*npalette
) * sizeof *palette
);
4237 else /* !png_get_PLTE */
4239 if (*npalette
!= (-1))
4240 png_error(pp
, "validate: invalid PLTE result");
4241 /* But there is no palette, so record this: */
4243 memset(palette
, 113, sizeof (store_palette
));
4247 num
= 2; /* force error below */
4248 if ((png_get_tRNS(pp
, pi
, &trans_alpha
, &num
, 0) & PNG_INFO_tRNS
) != 0 &&
4249 (trans_alpha
!= NULL
|| num
!= 1/*returns 1 for a transparent color*/) &&
4250 /* Oops, if a palette tRNS gets expanded png_read_update_info (at least so
4251 * far as 1.5.4) does not remove the trans_alpha pointer, only num_trans,
4252 * so in the above call we get a success, we get a pointer (who knows what
4253 * to) and we get num_trans == 0:
4255 !(trans_alpha
!= NULL
&& num
== 0)) /* TODO: fix this in libpng. */
4259 /* Any of these are crash-worthy - given the implementation of
4260 * png_get_tRNS up to 1.5 an app won't crash if it just checks the
4261 * result above and fails to check that the variables it passed have
4262 * actually been filled in! Note that if the app were to pass the
4263 * last, png_color_16p, variable too it couldn't rely on this.
4265 if (trans_alpha
== NULL
|| num
<= 0 || num
> 256 || num
> *npalette
)
4266 png_error(pp
, "validate: unexpected png_get_tRNS (palette) result");
4268 for (i
=0; i
<num
; ++i
)
4269 palette
[i
].alpha
= trans_alpha
[i
];
4271 for (num
=*npalette
; i
<num
; ++i
)
4272 palette
[i
].alpha
= 255;
4275 palette
[i
].alpha
= 33; /* flag value */
4277 return 1; /* transparency */
4282 /* No palette transparency - just set the alpha channel to opaque. */
4285 for (i
=0, num
=*npalette
; i
<num
; ++i
)
4286 palette
[i
].alpha
= 255;
4289 palette
[i
].alpha
= 55; /* flag value */
4291 return 0; /* no transparency */
4295 /* Utility to validate the palette if it should not have changed (the
4296 * non-transform case).
4299 standard_palette_validate(standard_display
*dp
, png_const_structp pp
,
4303 store_palette palette
;
4305 if (read_palette(palette
, &npalette
, pp
, pi
) != dp
->is_transparent
)
4306 png_error(pp
, "validate: palette transparency changed");
4308 if (npalette
!= dp
->npalette
)
4313 pos
= safecat(msg
, sizeof msg
, pos
, "validate: palette size changed: ");
4314 pos
= safecatn(msg
, sizeof msg
, pos
, dp
->npalette
);
4315 pos
= safecat(msg
, sizeof msg
, pos
, " -> ");
4316 pos
= safecatn(msg
, sizeof msg
, pos
, npalette
);
4321 int i
= npalette
; /* npalette is aliased */
4324 if (palette
[i
].red
!= dp
->palette
[i
].red
||
4325 palette
[i
].green
!= dp
->palette
[i
].green
||
4326 palette
[i
].blue
!= dp
->palette
[i
].blue
||
4327 palette
[i
].alpha
!= dp
->palette
[i
].alpha
)
4328 png_error(pp
, "validate: PLTE or tRNS chunk changed");
4332 /* By passing a 'standard_display' the progressive callbacks can be used
4333 * directly by the sequential code, the functions suffixed "_imp" are the
4334 * implementations, the functions without the suffix are the callbacks.
4336 * The code for the info callback is split into two because this callback calls
4337 * png_read_update_info or png_start_read_image and what gets called depends on
4338 * whether the info needs updating (we want to test both calls in pngvalid.)
4341 standard_info_part1(standard_display
*dp
, png_structp pp
, png_infop pi
)
4343 if (png_get_bit_depth(pp
, pi
) != dp
->bit_depth
)
4344 png_error(pp
, "validate: bit depth changed");
4346 if (png_get_color_type(pp
, pi
) != dp
->colour_type
)
4347 png_error(pp
, "validate: color type changed");
4349 if (png_get_filter_type(pp
, pi
) != PNG_FILTER_TYPE_BASE
)
4350 png_error(pp
, "validate: filter type changed");
4352 if (png_get_interlace_type(pp
, pi
) != dp
->interlace_type
)
4353 png_error(pp
, "validate: interlacing changed");
4355 if (png_get_compression_type(pp
, pi
) != PNG_COMPRESSION_TYPE_BASE
)
4356 png_error(pp
, "validate: compression type changed");
4358 dp
->w
= png_get_image_width(pp
, pi
);
4360 if (dp
->w
!= standard_width(pp
, dp
->id
))
4361 png_error(pp
, "validate: image width changed");
4363 dp
->h
= png_get_image_height(pp
, pi
);
4365 if (dp
->h
!= standard_height(pp
, dp
->id
))
4366 png_error(pp
, "validate: image height changed");
4368 /* Record (but don't check at present) the input sBIT according to the colour
4372 png_color_8p sBIT
= 0;
4374 if (png_get_sBIT(pp
, pi
, &sBIT
) & PNG_INFO_sBIT
)
4376 int sBIT_invalid
= 0;
4379 png_error(pp
, "validate: unexpected png_get_sBIT result");
4381 if (dp
->colour_type
& PNG_COLOR_MASK_COLOR
)
4383 if (sBIT
->red
== 0 || sBIT
->red
> dp
->bit_depth
)
4386 dp
->red_sBIT
= sBIT
->red
;
4388 if (sBIT
->green
== 0 || sBIT
->green
> dp
->bit_depth
)
4391 dp
->green_sBIT
= sBIT
->green
;
4393 if (sBIT
->blue
== 0 || sBIT
->blue
> dp
->bit_depth
)
4396 dp
->blue_sBIT
= sBIT
->blue
;
4401 if (sBIT
->gray
== 0 || sBIT
->gray
> dp
->bit_depth
)
4404 dp
->blue_sBIT
= dp
->green_sBIT
= dp
->red_sBIT
= sBIT
->gray
;
4407 /* All 8 bits in tRNS for a palette image are significant - see the
4410 if (dp
->colour_type
& PNG_COLOR_MASK_ALPHA
)
4412 if (sBIT
->alpha
== 0 || sBIT
->alpha
> dp
->bit_depth
)
4415 dp
->alpha_sBIT
= sBIT
->alpha
;
4419 png_error(pp
, "validate: sBIT value out of range");
4423 /* Important: this is validating the value *before* any transforms have been
4424 * put in place. It doesn't matter for the standard tests, where there are
4425 * no transforms, but it does for other tests where rowbytes may change after
4426 * png_read_update_info.
4428 if (png_get_rowbytes(pp
, pi
) != standard_rowsize(pp
, dp
->id
))
4429 png_error(pp
, "validate: row size changed");
4431 /* Validate the colour type 3 palette (this can be present on other color
4434 standard_palette_validate(dp
, pp
, pi
);
4436 /* In any case always check for a tranparent color (notice that the
4437 * colour type 3 case must not give a successful return on the get_tRNS call
4438 * with these arguments!)
4441 png_color_16p trans_color
= 0;
4443 if (png_get_tRNS(pp
, pi
, 0, 0, &trans_color
) & PNG_INFO_tRNS
)
4445 if (trans_color
== 0)
4446 png_error(pp
, "validate: unexpected png_get_tRNS (color) result");
4448 switch (dp
->colour_type
)
4451 dp
->transparent
.red
= dp
->transparent
.green
= dp
->transparent
.blue
=
4453 dp
->is_transparent
= 1;
4457 dp
->transparent
.red
= trans_color
->red
;
4458 dp
->transparent
.green
= trans_color
->green
;
4459 dp
->transparent
.blue
= trans_color
->blue
;
4460 dp
->is_transparent
= 1;
4464 /* Not expected because it should result in the array case
4467 png_error(pp
, "validate: unexpected png_get_tRNS result");
4471 png_error(pp
, "validate: invalid tRNS chunk with alpha image");
4476 /* Read the number of passes - expected to match the value used when
4477 * creating the image (interlaced or not). This has the side effect of
4478 * turning on interlace handling (if do_interlace is not set.)
4480 dp
->npasses
= npasses_from_interlace_type(pp
, dp
->interlace_type
);
4481 if (!dp
->do_interlace
&& dp
->npasses
!= png_set_interlace_handling(pp
))
4482 png_error(pp
, "validate: file changed interlace type");
4484 /* Caller calls png_read_update_info or png_start_read_image now, then calls
4489 /* This must be called *after* the png_read_update_info call to get the correct
4490 * 'rowbytes' value, otherwise png_get_rowbytes will refer to the untransformed
4494 standard_info_part2(standard_display
*dp
, png_const_structp pp
,
4495 png_const_infop pi
, int nImages
)
4497 /* Record cbRow now that it can be found. */
4498 dp
->pixel_size
= bit_size(pp
, png_get_color_type(pp
, pi
),
4499 png_get_bit_depth(pp
, pi
));
4500 dp
->bit_width
= png_get_image_width(pp
, pi
) * dp
->pixel_size
;
4501 dp
->cbRow
= png_get_rowbytes(pp
, pi
);
4503 /* Validate the rowbytes here again. */
4504 if (dp
->cbRow
!= (dp
->bit_width
+7)/8)
4505 png_error(pp
, "bad png_get_rowbytes calculation");
4507 /* Then ensure there is enough space for the output image(s). */
4508 store_ensure_image(dp
->ps
, pp
, nImages
, dp
->cbRow
, dp
->h
);
4512 standard_info_imp(standard_display
*dp
, png_structp pp
, png_infop pi
,
4515 /* Note that the validation routine has the side effect of turning on
4516 * interlace handling in the subsequent code.
4518 standard_info_part1(dp
, pp
, pi
);
4520 /* And the info callback has to call this (or png_read_update_info - see
4521 * below in the png_modifier code for that variant.
4523 if (dp
->use_update_info
)
4525 /* For debugging the effect of multiple calls: */
4526 int i
= dp
->use_update_info
;
4528 png_read_update_info(pp
, pi
);
4532 png_start_read_image(pp
);
4534 /* Validate the height, width and rowbytes plus ensure that sufficient buffer
4535 * exists for decoding the image.
4537 standard_info_part2(dp
, pp
, pi
, nImages
);
4541 standard_info(png_structp pp
, png_infop pi
)
4543 standard_display
*dp
= voidcast(standard_display
*,
4544 png_get_progressive_ptr(pp
));
4546 /* Call with nImages==1 because the progressive reader can only produce one
4549 standard_info_imp(dp
, pp
, pi
, 1 /*only one image*/);
4553 progressive_row(png_structp ppIn
, png_bytep new_row
, png_uint_32 y
, int pass
)
4555 png_const_structp pp
= ppIn
;
4556 PNG_CONST standard_display
*dp
= voidcast(standard_display
*,
4557 png_get_progressive_ptr(pp
));
4559 /* When handling interlacing some rows will be absent in each pass, the
4560 * callback still gets called, but with a NULL pointer. This is checked
4561 * in the 'else' clause below. We need our own 'cbRow', but we can't call
4562 * png_get_rowbytes because we got no info structure.
4564 if (new_row
!= NULL
)
4568 /* In the case where the reader doesn't do the interlace it gives
4569 * us the y in the sub-image:
4571 if (dp
->do_interlace
&& dp
->interlace_type
== PNG_INTERLACE_ADAM7
)
4573 #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED
4574 /* Use this opportunity to validate the png 'current' APIs: */
4575 if (y
!= png_get_current_row_number(pp
))
4576 png_error(pp
, "png_get_current_row_number is broken");
4578 if (pass
!= png_get_current_pass_number(pp
))
4579 png_error(pp
, "png_get_current_pass_number is broken");
4582 y
= PNG_ROW_FROM_PASS_ROW(y
, pass
);
4585 /* Validate this just in case. */
4587 png_error(pp
, "invalid y to progressive row callback");
4589 row
= store_image_row(dp
->ps
, pp
, 0, y
);
4591 #ifdef PNG_READ_INTERLACING_SUPPORTED
4592 /* Combine the new row into the old: */
4593 if (dp
->do_interlace
)
4595 if (dp
->interlace_type
== PNG_INTERLACE_ADAM7
)
4596 deinterlace_row(row
, new_row
, dp
->pixel_size
, dp
->w
, pass
);
4598 row_copy(row
, new_row
, dp
->pixel_size
* dp
->w
);
4601 png_progressive_combine_row(pp
, row
, new_row
);
4602 #endif /* PNG_READ_INTERLACING_SUPPORTED */
4605 #ifdef PNG_READ_INTERLACING_SUPPORTED
4606 else if (dp
->interlace_type
== PNG_INTERLACE_ADAM7
&&
4607 PNG_ROW_IN_INTERLACE_PASS(y
, pass
) &&
4608 PNG_PASS_COLS(dp
->w
, pass
) > 0)
4609 png_error(pp
, "missing row in progressive de-interlacing");
4610 #endif /* PNG_READ_INTERLACING_SUPPORTED */
4614 sequential_row(standard_display
*dp
, png_structp pp
, png_infop pi
,
4615 PNG_CONST
int iImage
, PNG_CONST
int iDisplay
)
4617 PNG_CONST
int npasses
= dp
->npasses
;
4618 PNG_CONST
int do_interlace
= dp
->do_interlace
&&
4619 dp
->interlace_type
== PNG_INTERLACE_ADAM7
;
4620 PNG_CONST png_uint_32 height
= standard_height(pp
, dp
->id
);
4621 PNG_CONST png_uint_32 width
= standard_width(pp
, dp
->id
);
4622 PNG_CONST png_store
* ps
= dp
->ps
;
4625 for (pass
=0; pass
<npasses
; ++pass
)
4628 png_uint_32 wPass
= PNG_PASS_COLS(width
, pass
);
4630 for (y
=0; y
<height
; ++y
)
4634 /* wPass may be zero or this row may not be in this pass.
4635 * png_read_row must not be called in either case.
4637 if (wPass
> 0 && PNG_ROW_IN_INTERLACE_PASS(y
, pass
))
4639 /* Read the row into a pair of temporary buffers, then do the
4640 * merge here into the output rows.
4642 png_byte row
[STANDARD_ROWMAX
], display
[STANDARD_ROWMAX
];
4644 /* The following aids (to some extent) error detection - we can
4645 * see where png_read_row wrote. Use opposite values in row and
4646 * display to make this easier. Don't use 0xff (which is used in
4647 * the image write code to fill unused bits) or 0 (which is a
4648 * likely value to overwrite unused bits with).
4650 memset(row
, 0xc5, sizeof row
);
4651 memset(display
, 0x5c, sizeof display
);
4653 png_read_row(pp
, row
, display
);
4656 deinterlace_row(store_image_row(ps
, pp
, iImage
, y
), row
,
4657 dp
->pixel_size
, dp
->w
, pass
);
4660 deinterlace_row(store_image_row(ps
, pp
, iDisplay
, y
), display
,
4661 dp
->pixel_size
, dp
->w
, pass
);
4666 iImage
>= 0 ? store_image_row(ps
, pp
, iImage
, y
) : NULL
,
4667 iDisplay
>= 0 ? store_image_row(ps
, pp
, iDisplay
, y
) : NULL
);
4671 /* And finish the read operation (only really necessary if the caller wants
4672 * to find additional data in png_info from chunks after the last IDAT.)
4674 png_read_end(pp
, pi
);
4677 #ifdef PNG_TEXT_SUPPORTED
4679 standard_check_text(png_const_structp pp
, png_const_textp tp
,
4680 png_const_charp keyword
, png_const_charp text
)
4683 size_t pos
= safecat(msg
, sizeof msg
, 0, "text: ");
4686 pos
= safecat(msg
, sizeof msg
, pos
, keyword
);
4687 pos
= safecat(msg
, sizeof msg
, pos
, ": ");
4690 if (tp
->compression
!= TEXT_COMPRESSION
)
4694 sprintf(buf
, "compression [%d->%d], ", TEXT_COMPRESSION
,
4696 pos
= safecat(msg
, sizeof msg
, pos
, buf
);
4699 if (tp
->key
== NULL
|| strcmp(tp
->key
, keyword
) != 0)
4701 pos
= safecat(msg
, sizeof msg
, pos
, "keyword \"");
4702 if (tp
->key
!= NULL
)
4704 pos
= safecat(msg
, sizeof msg
, pos
, tp
->key
);
4705 pos
= safecat(msg
, sizeof msg
, pos
, "\", ");
4709 pos
= safecat(msg
, sizeof msg
, pos
, "null, ");
4712 if (tp
->text
== NULL
)
4713 pos
= safecat(msg
, sizeof msg
, pos
, "text lost, ");
4717 if (tp
->text_length
!= strlen(text
))
4720 sprintf(buf
, "text length changed[%lu->%lu], ",
4721 (unsigned long)strlen(text
), (unsigned long)tp
->text_length
);
4722 pos
= safecat(msg
, sizeof msg
, pos
, buf
);
4725 if (strcmp(tp
->text
, text
) != 0)
4727 pos
= safecat(msg
, sizeof msg
, pos
, "text becomes \"");
4728 pos
= safecat(msg
, sizeof msg
, pos
, tp
->text
);
4729 pos
= safecat(msg
, sizeof msg
, pos
, "\" (was \"");
4730 pos
= safecat(msg
, sizeof msg
, pos
, text
);
4731 pos
= safecat(msg
, sizeof msg
, pos
, "\"), ");
4735 if (tp
->itxt_length
!= 0)
4736 pos
= safecat(msg
, sizeof msg
, pos
, "iTXt length set, ");
4738 if (tp
->lang
!= NULL
)
4740 pos
= safecat(msg
, sizeof msg
, pos
, "iTXt language \"");
4741 pos
= safecat(msg
, sizeof msg
, pos
, tp
->lang
);
4742 pos
= safecat(msg
, sizeof msg
, pos
, "\", ");
4745 if (tp
->lang_key
!= NULL
)
4747 pos
= safecat(msg
, sizeof msg
, pos
, "iTXt keyword \"");
4748 pos
= safecat(msg
, sizeof msg
, pos
, tp
->lang_key
);
4749 pos
= safecat(msg
, sizeof msg
, pos
, "\", ");
4754 msg
[pos
-2] = '\0'; /* Remove the ", " at the end */
4760 standard_text_validate(standard_display
*dp
, png_const_structp pp
,
4763 png_textp tp
= NULL
;
4764 png_uint_32 num_text
= png_get_text(pp
, pi
, &tp
, NULL
);
4766 if (num_text
== 2 && tp
!= NULL
)
4768 standard_check_text(pp
, tp
, "image name", dp
->ps
->current
->name
);
4769 standard_check_text(pp
, tp
+1, "end marker", "end");
4776 sprintf(msg
, "expected two text items, got %lu",
4777 (unsigned long)num_text
);
4782 # define standard_text_validate(dp,pp,pi) ((void)0)
4786 standard_row_validate(standard_display
*dp
, png_const_structp pp
,
4787 int iImage
, int iDisplay
, png_uint_32 y
)
4790 png_byte std
[STANDARD_ROWMAX
];
4792 /* The row must be pre-initialized to the magic number here for the size
4795 memset(std
, 178, sizeof std
);
4796 standard_row(pp
, std
, dp
->id
, y
);
4798 /* At the end both the 'row' and 'display' arrays should end up identical.
4799 * In earlier passes 'row' will be partially filled in, with only the pixels
4800 * that have been read so far, but 'display' will have those pixels
4801 * replicated to fill the unread pixels while reading an interlaced image.
4802 #if PNG_LIBPNG_VER < 10506
4803 * The side effect inside the libpng sequential reader is that the 'row'
4804 * array retains the correct values for unwritten pixels within the row
4805 * bytes, while the 'display' array gets bits off the end of the image (in
4806 * the last byte) trashed. Unfortunately in the progressive reader the
4807 * row bytes are always trashed, so we always do a pixel_cmp here even though
4808 * a memcmp of all cbRow bytes will succeed for the sequential reader.
4812 (where
= pixel_cmp(std
, store_image_row(dp
->ps
, pp
, iImage
, y
),
4813 dp
->bit_width
)) != 0)
4816 sprintf(msg
, "PNG image row[%lu][%d] changed from %.2x to %.2x",
4817 (unsigned long)y
, where
-1, std
[where
-1],
4818 store_image_row(dp
->ps
, pp
, iImage
, y
)[where
-1]);
4822 #if PNG_LIBPNG_VER < 10506
4823 /* In this case use pixel_cmp because we need to compare a partial
4824 * byte at the end of the row if the row is not an exact multiple
4825 * of 8 bits wide. (This is fixed in libpng-1.5.6 and pixel_cmp is
4826 * changed to match!)
4829 if (iDisplay
>= 0 &&
4830 (where
= pixel_cmp(std
, store_image_row(dp
->ps
, pp
, iDisplay
, y
),
4831 dp
->bit_width
)) != 0)
4834 sprintf(msg
, "display row[%lu][%d] changed from %.2x to %.2x",
4835 (unsigned long)y
, where
-1, std
[where
-1],
4836 store_image_row(dp
->ps
, pp
, iDisplay
, y
)[where
-1]);
4842 standard_image_validate(standard_display
*dp
, png_const_structp pp
, int iImage
,
4848 store_image_check(dp
->ps
, pp
, iImage
);
4851 store_image_check(dp
->ps
, pp
, iDisplay
);
4853 for (y
=0; y
<dp
->h
; ++y
)
4854 standard_row_validate(dp
, pp
, iImage
, iDisplay
, y
);
4856 /* This avoids false positives if the validation code is never called! */
4857 dp
->ps
->validated
= 1;
4861 standard_end(png_structp ppIn
, png_infop pi
)
4863 png_const_structp pp
= ppIn
;
4864 standard_display
*dp
= voidcast(standard_display
*,
4865 png_get_progressive_ptr(pp
));
4869 /* Validate the image - progressive reading only produces one variant for
4870 * interlaced images.
4872 standard_text_validate(dp
, pp
, pi
);
4873 standard_image_validate(dp
, pp
, 0, -1);
4876 /* A single test run checking the standard image to ensure it is not damaged. */
4878 standard_test(png_store
* PNG_CONST psIn
, png_uint_32 PNG_CONST id
,
4879 int do_interlace
, int use_update_info
)
4882 context(psIn
, fault
);
4884 /* Set up the display (stack frame) variables from the arguments to the
4885 * function and initialize the locals that are filled in later.
4887 standard_display_init(&d
, psIn
, id
, do_interlace
, use_update_info
);
4889 /* Everything is protected by a Try/Catch. The functions called also
4890 * typically have local Try/Catch blocks.
4897 /* Get a png_struct for reading the image. This will throw an error if it
4898 * fails, so we don't need to check the result.
4900 pp
= set_store_for_read(d
.ps
, &pi
, d
.id
,
4901 d
.do_interlace
? (d
.ps
->progressive
?
4902 "pngvalid progressive deinterlacer" :
4903 "pngvalid sequential deinterlacer") : (d
.ps
->progressive
?
4904 "progressive reader" : "sequential reader"));
4906 /* Initialize the palette correctly from the png_store_file. */
4907 standard_palette_init(&d
);
4909 /* Introduce the correct read function. */
4910 if (d
.ps
->progressive
)
4912 png_set_progressive_read_fn(pp
, &d
, standard_info
, progressive_row
,
4915 /* Now feed data into the reader until we reach the end: */
4916 store_progressive_read(d
.ps
, pp
, pi
);
4920 /* Note that this takes the store, not the display. */
4921 png_set_read_fn(pp
, d
.ps
, store_read
);
4923 /* Check the header values: */
4924 png_read_info(pp
, pi
);
4926 /* The code tests both versions of the images that the sequential
4927 * reader can produce.
4929 standard_info_imp(&d
, pp
, pi
, 2 /*images*/);
4931 /* Need the total bytes in the image below; we can't get to this point
4932 * unless the PNG file values have been checked against the expected
4936 sequential_row(&d
, pp
, pi
, 0, 1);
4938 /* After the last pass loop over the rows again to check that the
4943 standard_text_validate(&d
, pp
, pi
);
4944 standard_image_validate(&d
, pp
, 0, 1);
4947 d
.ps
->validated
= 1;
4951 /* Check for validation. */
4952 if (!d
.ps
->validated
)
4953 png_error(pp
, "image read failed silently");
4955 /* Successful completion. */
4959 d
.ps
= fault
; /* make sure this hasn't been clobbered. */
4961 /* In either case clean up the store. */
4962 store_read_reset(d
.ps
);
4966 test_standard(png_modifier
* PNG_CONST pm
, png_byte PNG_CONST colour_type
,
4967 int bdlo
, int PNG_CONST bdhi
)
4969 for (; bdlo
<= bdhi
; ++bdlo
)
4973 for (interlace_type
= PNG_INTERLACE_NONE
;
4974 interlace_type
< PNG_INTERLACE_LAST
; ++interlace_type
)
4976 standard_test(&pm
->this, FILEID(colour_type
, DEPTH(bdlo
), 0/*palette*/,
4977 interlace_type
, 0, 0, 0), 0/*do_interlace*/, pm
->use_update_info
);
4984 return 1; /* keep going */
4988 perform_standard_test(png_modifier
*pm
)
4990 /* Test each colour type over the valid range of bit depths (expressed as
4991 * log2(bit_depth) in turn, stop as soon as any error is detected.
4993 if (!test_standard(pm
, 0, 0, READ_BDHI
))
4996 if (!test_standard(pm
, 2, 3, READ_BDHI
))
4999 if (!test_standard(pm
, 3, 0, 3))
5002 if (!test_standard(pm
, 4, 3, READ_BDHI
))
5005 if (!test_standard(pm
, 6, 3, READ_BDHI
))
5010 /********************************** SIZE TESTS ********************************/
5012 test_size(png_modifier
* PNG_CONST pm
, png_byte PNG_CONST colour_type
,
5013 int bdlo
, int PNG_CONST bdhi
)
5015 /* Run the tests on each combination.
5017 * NOTE: on my 32 bit x86 each of the following blocks takes
5018 * a total of 3.5 seconds if done across every combo of bit depth
5019 * width and height. This is a waste of time in practice, hence the
5020 * hinc and winc stuff:
5022 static PNG_CONST png_byte hinc
[] = {1, 3, 11, 1, 5};
5023 static PNG_CONST png_byte winc
[] = {1, 9, 5, 7, 1};
5024 for (; bdlo
<= bdhi
; ++bdlo
)
5028 for (h
=1; h
<=16; h
+=hinc
[bdlo
]) for (w
=1; w
<=16; w
+=winc
[bdlo
])
5030 /* First test all the 'size' images against the sequential
5031 * reader using libpng to deinterlace (where required.) This
5032 * validates the write side of libpng. There are four possibilities
5035 standard_test(&pm
->this, FILEID(colour_type
, DEPTH(bdlo
), 0/*palette*/,
5036 PNG_INTERLACE_NONE
, w
, h
, 0), 0/*do_interlace*/,
5037 pm
->use_update_info
);
5042 standard_test(&pm
->this, FILEID(colour_type
, DEPTH(bdlo
), 0/*palette*/,
5043 PNG_INTERLACE_NONE
, w
, h
, 1), 0/*do_interlace*/,
5044 pm
->use_update_info
);
5049 standard_test(&pm
->this, FILEID(colour_type
, DEPTH(bdlo
), 0/*palette*/,
5050 PNG_INTERLACE_ADAM7
, w
, h
, 0), 0/*do_interlace*/,
5051 pm
->use_update_info
);
5056 standard_test(&pm
->this, FILEID(colour_type
, DEPTH(bdlo
), 0/*palette*/,
5057 PNG_INTERLACE_ADAM7
, w
, h
, 1), 0/*do_interlace*/,
5058 pm
->use_update_info
);
5063 /* Now validate the interlaced read side - do_interlace true,
5064 * in the progressive case this does actually make a difference
5065 * to the code used in the non-interlaced case too.
5067 standard_test(&pm
->this, FILEID(colour_type
, DEPTH(bdlo
), 0/*palette*/,
5068 PNG_INTERLACE_NONE
, w
, h
, 0), 1/*do_interlace*/,
5069 pm
->use_update_info
);
5074 standard_test(&pm
->this, FILEID(colour_type
, DEPTH(bdlo
), 0/*palette*/,
5075 PNG_INTERLACE_ADAM7
, w
, h
, 0), 1/*do_interlace*/,
5076 pm
->use_update_info
);
5083 return 1; /* keep going */
5087 perform_size_test(png_modifier
*pm
)
5089 /* Test each colour type over the valid range of bit depths (expressed as
5090 * log2(bit_depth) in turn, stop as soon as any error is detected.
5092 if (!test_size(pm
, 0, 0, READ_BDHI
))
5095 if (!test_size(pm
, 2, 3, READ_BDHI
))
5098 /* For the moment don't do the palette test - it's a waste of time when
5099 * compared to the grayscale test.
5102 if (!test_size(pm
, 3, 0, 3))
5106 if (!test_size(pm
, 4, 3, READ_BDHI
))
5109 if (!test_size(pm
, 6, 3, READ_BDHI
))
5114 /******************************* TRANSFORM TESTS ******************************/
5115 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
5116 /* A set of tests to validate libpng image transforms. The possibilities here
5117 * are legion because the transforms can be combined in a combinatorial
5118 * fashion. To deal with this some measure of restraint is required, otherwise
5119 * the tests would take forever.
5121 typedef struct image_pixel
5123 /* A local (pngvalid) representation of a PNG pixel, in all its
5126 unsigned int red
, green
, blue
, alpha
; /* For non-palette images. */
5127 unsigned int palette_index
; /* For a palette image. */
5128 png_byte colour_type
; /* As in the spec. */
5129 png_byte bit_depth
; /* Defines bit size in row */
5130 png_byte sample_depth
; /* Scale of samples */
5131 int have_tRNS
; /* tRNS chunk may need processing */
5133 /* For checking the code calculates double precision floating point values
5134 * along with an error value, accumulated from the transforms. Because an
5135 * sBIT setting allows larger error bounds (indeed, by the spec, apparently
5136 * up to just less than +/-1 in the scaled value) the *lowest* sBIT for each
5137 * channel is stored. This sBIT value is folded in to the stored error value
5138 * at the end of the application of the transforms to the pixel.
5140 double redf
, greenf
, bluef
, alphaf
;
5141 double rede
, greene
, bluee
, alphae
;
5142 png_byte red_sBIT
, green_sBIT
, blue_sBIT
, alpha_sBIT
;
5145 /* Shared utility function, see below. */
5147 image_pixel_setf(image_pixel
*this, unsigned int max
)
5149 this->redf
= this->red
/ (double)max
;
5150 this->greenf
= this->green
/ (double)max
;
5151 this->bluef
= this->blue
/ (double)max
;
5152 this->alphaf
= this->alpha
/ (double)max
;
5154 if (this->red
< max
)
5155 this->rede
= this->redf
* DBL_EPSILON
;
5158 if (this->green
< max
)
5159 this->greene
= this->greenf
* DBL_EPSILON
;
5162 if (this->blue
< max
)
5163 this->bluee
= this->bluef
* DBL_EPSILON
;
5166 if (this->alpha
< max
)
5167 this->alphae
= this->alphaf
* DBL_EPSILON
;
5172 /* Initialize the structure for the next pixel - call this before doing any
5173 * transforms and call it for each pixel since all the fields may need to be
5177 image_pixel_init(image_pixel
*this, png_const_bytep row
, png_byte colour_type
,
5178 png_byte bit_depth
, png_uint_32 x
, store_palette palette
)
5180 PNG_CONST png_byte sample_depth
= (png_byte
)(colour_type
==
5181 PNG_COLOR_TYPE_PALETTE
? 8 : bit_depth
);
5182 PNG_CONST
unsigned int max
= (1U<<sample_depth
)-1;
5184 /* Initially just set everything to the same number and the alpha to opaque.
5185 * Note that this currently assumes a simple palette where entry x has colour
5188 this->palette_index
= this->red
= this->green
= this->blue
=
5189 sample(row
, colour_type
, bit_depth
, x
, 0);
5191 this->red_sBIT
= this->green_sBIT
= this->blue_sBIT
= this->alpha_sBIT
=
5194 /* Then override as appropriate: */
5195 if (colour_type
== 3) /* palette */
5197 /* This permits the caller to default to the sample value. */
5200 PNG_CONST
unsigned int i
= this->palette_index
;
5202 this->red
= palette
[i
].red
;
5203 this->green
= palette
[i
].green
;
5204 this->blue
= palette
[i
].blue
;
5205 this->alpha
= palette
[i
].alpha
;
5209 else /* not palette */
5213 if (colour_type
& 2)
5215 this->green
= sample(row
, colour_type
, bit_depth
, x
, 1);
5216 this->blue
= sample(row
, colour_type
, bit_depth
, x
, 2);
5219 if (colour_type
& 4)
5220 this->alpha
= sample(row
, colour_type
, bit_depth
, x
, ++i
);
5223 /* Calculate the scaled values, these are simply the values divided by
5224 * 'max' and the error is initialized to the double precision epsilon value
5225 * from the header file.
5227 image_pixel_setf(this, max
);
5229 /* Store the input information for use in the transforms - these will
5230 * modify the information.
5232 this->colour_type
= colour_type
;
5233 this->bit_depth
= bit_depth
;
5234 this->sample_depth
= sample_depth
;
5235 this->have_tRNS
= 0;
5238 /* Convert a palette image to an rgb image. This necessarily converts the tRNS
5239 * chunk at the same time, because the tRNS will be in palette form. The way
5240 * palette validation works means that the original palette is never updated,
5241 * instead the image_pixel value from the row contains the RGB of the
5242 * corresponding palette entry and *this* is updated. Consequently this routine
5243 * only needs to change the colour type information.
5246 image_pixel_convert_PLTE(image_pixel
*this)
5248 if (this->colour_type
== PNG_COLOR_TYPE_PALETTE
)
5250 if (this->have_tRNS
)
5252 this->colour_type
= PNG_COLOR_TYPE_RGB_ALPHA
;
5253 this->have_tRNS
= 0;
5256 this->colour_type
= PNG_COLOR_TYPE_RGB
;
5258 /* The bit depth of the row changes at this point too (notice that this is
5259 * the row format, not the sample depth, which is separate.)
5261 this->bit_depth
= 8;
5265 /* Add an alpha channel; this will import the tRNS information because tRNS is
5266 * not valid in an alpha image. The bit depth will invariably be set to at
5267 * least 8. Palette images will be converted to alpha (using the above API).
5270 image_pixel_add_alpha(image_pixel
*this, PNG_CONST standard_display
*display
)
5272 if (this->colour_type
== PNG_COLOR_TYPE_PALETTE
)
5273 image_pixel_convert_PLTE(this);
5275 if ((this->colour_type
& PNG_COLOR_MASK_ALPHA
) == 0)
5277 if (this->colour_type
== PNG_COLOR_TYPE_GRAY
)
5279 if (this->bit_depth
< 8)
5280 this->bit_depth
= 8;
5282 if (this->have_tRNS
)
5284 this->have_tRNS
= 0;
5286 /* Check the input, original, channel value here against the
5287 * original tRNS gray chunk valie.
5289 if (this->red
== display
->transparent
.red
)
5297 this->colour_type
= PNG_COLOR_TYPE_GRAY_ALPHA
;
5300 else if (this->colour_type
== PNG_COLOR_TYPE_RGB
)
5302 if (this->have_tRNS
)
5304 this->have_tRNS
= 0;
5306 /* Again, check the exact input values, not the current transformed
5309 if (this->red
== display
->transparent
.red
&&
5310 this->green
== display
->transparent
.green
&&
5311 this->blue
== display
->transparent
.blue
)
5316 this->colour_type
= PNG_COLOR_TYPE_RGB_ALPHA
;
5320 /* The error in the alpha is zero and the sBIT value comes from the
5321 * original sBIT data (actually it will always be the original bit depth).
5324 this->alpha_sBIT
= display
->alpha_sBIT
;
5328 struct transform_display
;
5329 typedef struct image_transform
5331 /* The name of this transform: a string. */
5332 PNG_CONST
char *name
;
5334 /* Each transform can be disabled from the command line: */
5337 /* The global list of transforms; read only. */
5338 struct image_transform
*PNG_CONST list
;
5340 /* The global count of the number of times this transform has been set on an
5343 unsigned int global_use
;
5345 /* The local count of the number of times this transform has been set. */
5346 unsigned int local_use
;
5348 /* The next transform in the list, each transform must call its own next
5349 * transform after it has processed the pixel successfully.
5351 PNG_CONST
struct image_transform
*next
;
5353 /* A single transform for the image, expressed as a series of function
5354 * callbacks and some space for values.
5356 * First a callback to add any required modifications to the png_modifier;
5357 * this gets called just before the modifier is set up for read.
5359 void (*ini
)(PNG_CONST
struct image_transform
*this,
5360 struct transform_display
*that
);
5362 /* And a callback to set the transform on the current png_read_struct:
5364 void (*set
)(PNG_CONST
struct image_transform
*this,
5365 struct transform_display
*that
, png_structp pp
, png_infop pi
);
5367 /* Then a transform that takes an input pixel in one PNG format or another
5368 * and modifies it by a pngvalid implementation of the transform (thus
5369 * duplicating the libpng intent without, we hope, duplicating the bugs
5370 * in the libpng implementation!) The png_structp is solely to allow error
5371 * reporting via png_error and png_warning.
5373 void (*mod
)(PNG_CONST
struct image_transform
*this, image_pixel
*that
,
5374 png_const_structp pp
, PNG_CONST
struct transform_display
*display
);
5376 /* Add this transform to the list and return true if the transform is
5377 * meaningful for this colour type and bit depth - if false then the
5378 * transform should have no effect on the image so there's not a lot of
5381 int (*add
)(struct image_transform
*this,
5382 PNG_CONST
struct image_transform
**that
, png_byte colour_type
,
5383 png_byte bit_depth
);
5386 typedef struct transform_display
5388 standard_display
this;
5392 PNG_CONST image_transform
* transform_list
;
5394 /* Local variables */
5395 png_byte output_colour_type
;
5396 png_byte output_bit_depth
;
5398 /* Modifications (not necessarily used.) */
5399 gama_modification gama_mod
;
5400 chrm_modification chrm_mod
;
5401 srgb_modification srgb_mod
;
5402 } transform_display
;
5404 /* Set sRGB, cHRM and gAMA transforms as required by the current encoding. */
5406 transform_set_encoding(transform_display
*this)
5408 /* Set up the png_modifier '_current' fields then use these to determine how
5409 * to add appropriate chunks.
5411 png_modifier
*pm
= this->pm
;
5413 modifier_set_encoding(pm
);
5415 if (modifier_color_encoding_is_set(pm
))
5417 if (modifier_color_encoding_is_sRGB(pm
))
5418 srgb_modification_init(&this->srgb_mod
, pm
, PNG_sRGB_INTENT_ABSOLUTE
);
5422 /* Set gAMA and cHRM separately. */
5423 gama_modification_init(&this->gama_mod
, pm
, pm
->current_gamma
);
5425 if (pm
->current_encoding
!= 0)
5426 chrm_modification_init(&this->chrm_mod
, pm
, pm
->current_encoding
);
5431 /* Three functions to end the list: */
5433 image_transform_ini_end(PNG_CONST image_transform
*this,
5434 transform_display
*that
)
5441 image_transform_set_end(PNG_CONST image_transform
*this,
5442 transform_display
*that
, png_structp pp
, png_infop pi
)
5450 /* At the end of the list recalculate the output image pixel value from the
5451 * double precision values set up by the preceding 'mod' calls:
5454 sample_scale(double sample_value
, unsigned int scale
)
5456 sample_value
= floor(sample_value
* scale
+ .5);
5458 /* Return NaN as 0: */
5459 if (!(sample_value
> 0))
5461 else if (sample_value
> scale
)
5462 sample_value
= scale
;
5464 return (unsigned int)sample_value
;
5468 image_transform_mod_end(PNG_CONST image_transform
*this, image_pixel
*that
,
5469 png_const_structp pp
, PNG_CONST transform_display
*display
)
5471 PNG_CONST
unsigned int scale
= (1U<<that
->sample_depth
)-1;
5477 /* At the end recalculate the digitized red green and blue values according
5478 * to the current sample_depth of the pixel.
5480 * The sample value is simply scaled to the maximum, checking for over
5481 * and underflow (which can both happen for some image transforms,
5482 * including simple size scaling, though libpng doesn't do that at present.
5484 that
->red
= sample_scale(that
->redf
, scale
);
5486 /* The error value is increased, at the end, according to the lowest sBIT
5487 * value seen. Common sense tells us that the intermediate integer
5488 * representations are no more accurate than +/- 0.5 in the integral values,
5489 * the sBIT allows the implementation to be worse than this. In addition the
5490 * PNG specification actually permits any error within the range (-1..+1),
5491 * but that is ignored here. Instead the final digitized value is compared,
5492 * below to the digitized value of the error limits - this has the net effect
5493 * of allowing (almost) +/-1 in the output value. It's difficult to see how
5494 * any algorithm that digitizes intermediate results can be more accurate.
5496 that
->rede
+= 1./(2*((1U<<that
->red_sBIT
)-1));
5498 if (that
->colour_type
& PNG_COLOR_MASK_COLOR
)
5500 that
->green
= sample_scale(that
->greenf
, scale
);
5501 that
->blue
= sample_scale(that
->bluef
, scale
);
5502 that
->greene
+= 1./(2*((1U<<that
->green_sBIT
)-1));
5503 that
->bluee
+= 1./(2*((1U<<that
->blue_sBIT
)-1));
5507 that
->blue
= that
->green
= that
->red
;
5508 that
->bluef
= that
->greenf
= that
->redf
;
5509 that
->bluee
= that
->greene
= that
->rede
;
5512 if ((that
->colour_type
& PNG_COLOR_MASK_ALPHA
) ||
5513 that
->colour_type
== PNG_COLOR_TYPE_PALETTE
)
5515 that
->alpha
= sample_scale(that
->alphaf
, scale
);
5516 that
->alphae
+= 1./(2*((1U<<that
->alpha_sBIT
)-1));
5520 that
->alpha
= scale
; /* opaque */
5521 that
->alpha
= 1; /* Override this. */
5522 that
->alphae
= 0; /* It's exact ;-) */
5526 /* Static 'end' structure: */
5527 static image_transform image_transform_end
=
5535 image_transform_ini_end
,
5536 image_transform_set_end
,
5537 image_transform_mod_end
,
5538 0 /* never called, I want it to crash if it is! */
5541 /* Reader callbacks and implementations, where they differ from the standard
5545 transform_display_init(transform_display
*dp
, png_modifier
*pm
, png_uint_32 id
,
5546 PNG_CONST image_transform
*transform_list
)
5548 memset(dp
, 0, sizeof *dp
);
5550 /* Standard fields */
5551 standard_display_init(&dp
->this, &pm
->this, id
, 0/*do_interlace*/,
5552 pm
->use_update_info
);
5554 /* Parameter fields */
5556 dp
->transform_list
= transform_list
;
5558 /* Local variable fields */
5559 dp
->output_colour_type
= 255; /* invalid */
5560 dp
->output_bit_depth
= 255; /* invalid */
5564 transform_info_imp(transform_display
*dp
, png_structp pp
, png_infop pi
)
5566 /* Reuse the standard stuff as appropriate. */
5567 standard_info_part1(&dp
->this, pp
, pi
);
5569 /* Now set the list of transforms. */
5570 dp
->transform_list
->set(dp
->transform_list
, dp
, pp
, pi
);
5572 /* Update the info structure for these transforms: */
5574 int i
= dp
->this.use_update_info
;
5575 /* Always do one call, even if use_update_info is 0. */
5577 png_read_update_info(pp
, pi
);
5581 /* And get the output information into the standard_display */
5582 standard_info_part2(&dp
->this, pp
, pi
, 1/*images*/);
5584 /* Plus the extra stuff we need for the transform tests: */
5585 dp
->output_colour_type
= png_get_color_type(pp
, pi
);
5586 dp
->output_bit_depth
= png_get_bit_depth(pp
, pi
);
5588 /* Validate the combination of colour type and bit depth that we are getting
5589 * out of libpng; the semantics of something not in the PNG spec are, at
5592 switch (dp
->output_colour_type
)
5594 case PNG_COLOR_TYPE_PALETTE
:
5595 if (dp
->output_bit_depth
> 8) goto error
;
5597 case PNG_COLOR_TYPE_GRAY
:
5598 if (dp
->output_bit_depth
== 1 || dp
->output_bit_depth
== 2 ||
5599 dp
->output_bit_depth
== 4)
5603 if (dp
->output_bit_depth
== 8 || dp
->output_bit_depth
== 16)
5611 pos
= safecat(message
, sizeof message
, 0,
5612 "invalid final bit depth: colour type(");
5613 pos
= safecatn(message
, sizeof message
, pos
, dp
->output_colour_type
);
5614 pos
= safecat(message
, sizeof message
, pos
, ") with bit depth: ");
5615 pos
= safecatn(message
, sizeof message
, pos
, dp
->output_bit_depth
);
5617 png_error(pp
, message
);
5621 /* Use a test pixel to check that the output agrees with what we expect -
5622 * this avoids running the whole test if the output is unexpected.
5625 image_pixel test_pixel
;
5627 memset(&test_pixel
, 0, sizeof test_pixel
);
5628 test_pixel
.colour_type
= dp
->this.colour_type
; /* input */
5629 test_pixel
.bit_depth
= dp
->this.bit_depth
;
5630 if (test_pixel
.colour_type
== PNG_COLOR_TYPE_PALETTE
)
5631 test_pixel
.sample_depth
= 8;
5633 test_pixel
.sample_depth
= test_pixel
.bit_depth
;
5634 /* Don't need sBIT here, but it must be set to non-zero to avoid
5635 * arithmetic overflows.
5637 test_pixel
.have_tRNS
= dp
->this.is_transparent
;
5638 test_pixel
.red_sBIT
= test_pixel
.green_sBIT
= test_pixel
.blue_sBIT
=
5639 test_pixel
.alpha_sBIT
= test_pixel
.sample_depth
;
5641 dp
->transform_list
->mod(dp
->transform_list
, &test_pixel
, pp
, dp
);
5643 if (test_pixel
.colour_type
!= dp
->output_colour_type
)
5646 size_t pos
= safecat(message
, sizeof message
, 0, "colour type ");
5648 pos
= safecatn(message
, sizeof message
, pos
, dp
->output_colour_type
);
5649 pos
= safecat(message
, sizeof message
, pos
, " expected ");
5650 pos
= safecatn(message
, sizeof message
, pos
, test_pixel
.colour_type
);
5652 png_error(pp
, message
);
5655 if (test_pixel
.bit_depth
!= dp
->output_bit_depth
)
5658 size_t pos
= safecat(message
, sizeof message
, 0, "bit depth ");
5660 pos
= safecatn(message
, sizeof message
, pos
, dp
->output_bit_depth
);
5661 pos
= safecat(message
, sizeof message
, pos
, " expected ");
5662 pos
= safecatn(message
, sizeof message
, pos
, test_pixel
.bit_depth
);
5664 png_error(pp
, message
);
5667 /* If both bit depth and colour type are correct check the sample depth.
5668 * I believe these are both internal errors.
5670 if (test_pixel
.colour_type
== PNG_COLOR_TYPE_PALETTE
)
5672 if (test_pixel
.sample_depth
!= 8) /* oops - internal error! */
5673 png_error(pp
, "pngvalid: internal: palette sample depth not 8");
5675 else if (test_pixel
.sample_depth
!= dp
->output_bit_depth
)
5678 size_t pos
= safecat(message
, sizeof message
, 0,
5679 "internal: sample depth ");
5681 pos
= safecatn(message
, sizeof message
, pos
, dp
->output_bit_depth
);
5682 pos
= safecat(message
, sizeof message
, pos
, " expected ");
5683 pos
= safecatn(message
, sizeof message
, pos
, test_pixel
.sample_depth
);
5685 png_error(pp
, message
);
5691 transform_info(png_structp pp
, png_infop pi
)
5693 transform_info_imp(voidcast(transform_display
*, png_get_progressive_ptr(pp
)),
5698 transform_range_check(png_const_structp pp
, unsigned int r
, unsigned int g
,
5699 unsigned int b
, unsigned int a
, unsigned int in_digitized
, double in
,
5700 unsigned int out
, png_byte sample_depth
, double err
, double limit
,
5701 PNG_CONST
char *name
, double digitization_error
)
5703 /* Compare the scaled, digitzed, values of our local calculation (in+-err)
5704 * with the digitized values libpng produced; 'sample_depth' is the actual
5705 * digitization depth of the libpng output colors (the bit depth except for
5706 * palette images where it is always 8.) The check on 'err' is to detect
5707 * internal errors in pngvalid itself.
5709 unsigned int max
= (1U<<sample_depth
)-1;
5710 double in_min
= ceil((in
-err
)*max
- digitization_error
);
5711 double in_max
= floor((in
+err
)*max
+ digitization_error
);
5712 if (err
> limit
|| !(out
>= in_min
&& out
<= in_max
))
5717 pos
= safecat(message
, sizeof message
, 0, name
);
5718 pos
= safecat(message
, sizeof message
, pos
, " output value error: rgba(");
5719 pos
= safecatn(message
, sizeof message
, pos
, r
);
5720 pos
= safecat(message
, sizeof message
, pos
, ",");
5721 pos
= safecatn(message
, sizeof message
, pos
, g
);
5722 pos
= safecat(message
, sizeof message
, pos
, ",");
5723 pos
= safecatn(message
, sizeof message
, pos
, b
);
5724 pos
= safecat(message
, sizeof message
, pos
, ",");
5725 pos
= safecatn(message
, sizeof message
, pos
, a
);
5726 pos
= safecat(message
, sizeof message
, pos
, "): ");
5727 pos
= safecatn(message
, sizeof message
, pos
, out
);
5728 pos
= safecat(message
, sizeof message
, pos
, " expected: ");
5729 pos
= safecatn(message
, sizeof message
, pos
, in_digitized
);
5730 pos
= safecat(message
, sizeof message
, pos
, " (");
5731 pos
= safecatd(message
, sizeof message
, pos
, (in
-err
)*max
, 3);
5732 pos
= safecat(message
, sizeof message
, pos
, "..");
5733 pos
= safecatd(message
, sizeof message
, pos
, (in
+err
)*max
, 3);
5734 pos
= safecat(message
, sizeof message
, pos
, ")");
5736 png_error(pp
, message
);
5741 transform_image_validate(transform_display
*dp
, png_const_structp pp
,
5744 /* Constants for the loop below: */
5745 PNG_CONST png_store
* PNG_CONST ps
= dp
->this.ps
;
5746 PNG_CONST png_byte in_ct
= dp
->this.colour_type
;
5747 PNG_CONST png_byte in_bd
= dp
->this.bit_depth
;
5748 PNG_CONST png_uint_32 w
= dp
->this.w
;
5749 PNG_CONST png_uint_32 h
= dp
->this.h
;
5750 PNG_CONST png_byte out_ct
= dp
->output_colour_type
;
5751 PNG_CONST png_byte out_bd
= dp
->output_bit_depth
;
5752 PNG_CONST png_byte sample_depth
= (png_byte
)(out_ct
==
5753 PNG_COLOR_TYPE_PALETTE
? 8 : out_bd
);
5754 PNG_CONST png_byte red_sBIT
= dp
->this.red_sBIT
;
5755 PNG_CONST png_byte green_sBIT
= dp
->this.green_sBIT
;
5756 PNG_CONST png_byte blue_sBIT
= dp
->this.blue_sBIT
;
5757 PNG_CONST png_byte alpha_sBIT
= dp
->this.alpha_sBIT
;
5758 PNG_CONST
int have_tRNS
= dp
->this.is_transparent
;
5759 double digitization_error
;
5761 store_palette out_palette
;
5766 /* Check for row overwrite errors */
5767 store_image_check(dp
->this.ps
, pp
, 0);
5769 /* Read the palette corresponding to the output if the output colour type
5770 * indicates a palette, othewise set out_palette to garbage.
5772 if (out_ct
== PNG_COLOR_TYPE_PALETTE
)
5774 /* Validate that the palette count itself has not changed - this is not
5777 int npalette
= (-1);
5779 (void)read_palette(out_palette
, &npalette
, pp
, pi
);
5780 if (npalette
!= dp
->this.npalette
)
5781 png_error(pp
, "unexpected change in palette size");
5783 digitization_error
= .5;
5787 png_byte in_sample_depth
;
5789 memset(out_palette
, 0x5e, sizeof out_palette
);
5791 /* assume-8-bit-calculations means assume that if the input has 8 bit
5792 * (or less) samples and the output has 16 bit samples the calculations
5793 * will be done with 8 bit precision, not 16.
5795 * TODO: fix this in libpng; png_set_expand_16 should cause 16 bit
5796 * calculations to be used throughout.
5798 if (in_ct
== PNG_COLOR_TYPE_PALETTE
|| in_bd
< 16)
5799 in_sample_depth
= 8;
5801 in_sample_depth
= in_bd
;
5803 if (sample_depth
!= 16 || in_sample_depth
> 8 ||
5804 !dp
->pm
->calculations_use_input_precision
)
5805 digitization_error
= .5;
5807 /* Else errors are at 8 bit precision, scale .5 in 8 bits to the 16 bits:
5810 digitization_error
= .5 * 257;
5815 png_const_bytep PNG_CONST pRow
= store_image_row(ps
, pp
, 0, y
);
5818 /* The original, standard, row pre-transforms. */
5819 png_byte std
[STANDARD_ROWMAX
];
5821 transform_row(pp
, std
, in_ct
, in_bd
, y
);
5823 /* Go through each original pixel transforming it and comparing with what
5824 * libpng did to the same pixel.
5828 image_pixel in_pixel
, out_pixel
;
5829 unsigned int r
, g
, b
, a
;
5831 /* Find out what we think the pixel should be: */
5832 image_pixel_init(&in_pixel
, std
, in_ct
, in_bd
, x
, dp
->this.palette
);
5834 in_pixel
.red_sBIT
= red_sBIT
;
5835 in_pixel
.green_sBIT
= green_sBIT
;
5836 in_pixel
.blue_sBIT
= blue_sBIT
;
5837 in_pixel
.alpha_sBIT
= alpha_sBIT
;
5838 in_pixel
.have_tRNS
= have_tRNS
;
5840 /* For error detection, below. */
5846 dp
->transform_list
->mod(dp
->transform_list
, &in_pixel
, pp
, dp
);
5848 /* Read the output pixel and compare it to what we got, we don't
5849 * use the error field here, so no need to update sBIT.
5851 image_pixel_init(&out_pixel
, pRow
, out_ct
, out_bd
, x
, out_palette
);
5853 /* We don't expect changes to the index here even if the bit depth is
5856 if (in_ct
== PNG_COLOR_TYPE_PALETTE
&&
5857 out_ct
== PNG_COLOR_TYPE_PALETTE
)
5859 if (in_pixel
.palette_index
!= out_pixel
.palette_index
)
5860 png_error(pp
, "unexpected transformed palette index");
5863 /* Check the colours for palette images too - in fact the palette could
5864 * be separately verified itself in most cases.
5866 if (in_pixel
.red
!= out_pixel
.red
)
5867 transform_range_check(pp
, r
, g
, b
, a
, in_pixel
.red
, in_pixel
.redf
,
5868 out_pixel
.red
, sample_depth
, in_pixel
.rede
,
5869 dp
->pm
->limit
+ 1./(2*((1U<<in_pixel
.red_sBIT
)-1)), "red/gray",
5870 digitization_error
);
5872 if ((out_ct
& PNG_COLOR_MASK_COLOR
) != 0 &&
5873 in_pixel
.green
!= out_pixel
.green
)
5874 transform_range_check(pp
, r
, g
, b
, a
, in_pixel
.green
,
5875 in_pixel
.greenf
, out_pixel
.green
, sample_depth
, in_pixel
.greene
,
5876 dp
->pm
->limit
+ 1./(2*((1U<<in_pixel
.green_sBIT
)-1)), "green",
5877 digitization_error
);
5879 if ((out_ct
& PNG_COLOR_MASK_COLOR
) != 0 &&
5880 in_pixel
.blue
!= out_pixel
.blue
)
5881 transform_range_check(pp
, r
, g
, b
, a
, in_pixel
.blue
, in_pixel
.bluef
,
5882 out_pixel
.blue
, sample_depth
, in_pixel
.bluee
,
5883 dp
->pm
->limit
+ 1./(2*((1U<<in_pixel
.blue_sBIT
)-1)), "blue",
5884 digitization_error
);
5886 if ((out_ct
& PNG_COLOR_MASK_ALPHA
) != 0 &&
5887 in_pixel
.alpha
!= out_pixel
.alpha
)
5888 transform_range_check(pp
, r
, g
, b
, a
, in_pixel
.alpha
,
5889 in_pixel
.alphaf
, out_pixel
.alpha
, sample_depth
, in_pixel
.alphae
,
5890 dp
->pm
->limit
+ 1./(2*((1U<<in_pixel
.alpha_sBIT
)-1)), "alpha",
5891 digitization_error
);
5892 } /* pixel (x) loop */
5893 } /* row (y) loop */
5895 /* Record that something was actually checked to avoid a false positive. */
5896 dp
->this.ps
->validated
= 1;
5900 transform_end(png_structp ppIn
, png_infop pi
)
5902 png_const_structp pp
= ppIn
;
5903 transform_display
*dp
= voidcast(transform_display
*,
5904 png_get_progressive_ptr(pp
));
5906 if (!dp
->this.speed
)
5907 transform_image_validate(dp
, pp
, pi
);
5909 dp
->this.ps
->validated
= 1;
5912 /* A single test run. */
5914 transform_test(png_modifier
*pmIn
, PNG_CONST png_uint_32 idIn
,
5915 PNG_CONST image_transform
* transform_listIn
, PNG_CONST
char * volatile name
)
5917 transform_display d
;
5918 context(&pmIn
->this, fault
);
5920 transform_display_init(&d
, pmIn
, idIn
, transform_listIn
);
5927 char full_name
[256];
5929 /* Make sure the encoding fields are correct and enter the required
5932 transform_set_encoding(&d
);
5934 /* Add any modifications required by the transform list. */
5935 d
.transform_list
->ini(d
.transform_list
, &d
);
5937 /* Add the color space information, if any, to the name. */
5938 pos
= safecat(full_name
, sizeof full_name
, pos
, name
);
5939 pos
= safecat_current_encoding(full_name
, sizeof full_name
, pos
, d
.pm
);
5941 /* Get a png_struct for reading the image. */
5942 pp
= set_modifier_for_read(d
.pm
, &pi
, d
.this.id
, full_name
);
5943 standard_palette_init(&d
.this);
5946 /* Logging (debugging only) */
5950 (void)store_message(&d
.pm
->this, pp
, buffer
, sizeof buffer
, 0,
5953 fprintf(stderr
, "%s\n", buffer
);
5957 /* Introduce the correct read function. */
5958 if (d
.pm
->this.progressive
)
5960 /* Share the row function with the standard implementation. */
5961 png_set_progressive_read_fn(pp
, &d
, transform_info
, progressive_row
,
5964 /* Now feed data into the reader until we reach the end: */
5965 modifier_progressive_read(d
.pm
, pp
, pi
);
5969 /* modifier_read expects a png_modifier* */
5970 png_set_read_fn(pp
, d
.pm
, modifier_read
);
5972 /* Check the header values: */
5973 png_read_info(pp
, pi
);
5975 /* Process the 'info' requirements. Only one image is generated */
5976 transform_info_imp(&d
, pp
, pi
);
5978 sequential_row(&d
.this, pp
, pi
, -1, 0);
5981 transform_image_validate(&d
, pp
, pi
);
5983 d
.this.ps
->validated
= 1;
5986 modifier_reset(d
.pm
);
5991 modifier_reset((png_modifier
*)fault
);
5995 /* The transforms: */
5996 #define ITSTRUCT(name) image_transform_##name
5997 #define ITDATA(name) image_transform_data_##name
5998 #define image_transform_ini image_transform_default_ini
6000 static image_transform ITSTRUCT(name) =\
6008 image_transform_ini,\
6009 image_transform_png_set_##name##_set,\
6010 image_transform_png_set_##name##_mod,\
6011 image_transform_png_set_##name##_add\
6013 #define PT ITSTRUCT(end) /* stores the previous transform */
6017 image_transform_default_ini(PNG_CONST image_transform
*this,
6018 transform_display
*that
)
6020 this->next
->ini(this->next
, that
);
6023 #ifdef PNG_READ_BACKGROUND_SUPPORTED
6025 image_transform_default_add(image_transform
*this,
6026 PNG_CONST image_transform
**that
, png_byte colour_type
, png_byte bit_depth
)
6038 #ifdef PNG_READ_EXPAND_SUPPORTED
6039 /* png_set_palette_to_rgb */
6041 image_transform_png_set_palette_to_rgb_set(PNG_CONST image_transform
*this,
6042 transform_display
*that
, png_structp pp
, png_infop pi
)
6044 png_set_palette_to_rgb(pp
);
6045 this->next
->set(this->next
, that
, pp
, pi
);
6049 image_transform_png_set_palette_to_rgb_mod(PNG_CONST image_transform
*this,
6050 image_pixel
*that
, png_const_structp pp
,
6051 PNG_CONST transform_display
*display
)
6053 if (that
->colour_type
== PNG_COLOR_TYPE_PALETTE
)
6054 image_pixel_convert_PLTE(that
);
6056 this->next
->mod(this->next
, that
, pp
, display
);
6060 image_transform_png_set_palette_to_rgb_add(image_transform
*this,
6061 PNG_CONST image_transform
**that
, png_byte colour_type
, png_byte bit_depth
)
6068 return colour_type
== PNG_COLOR_TYPE_PALETTE
;
6073 #define PT ITSTRUCT(palette_to_rgb)
6074 #endif /* PNG_READ_EXPAND_SUPPORTED */
6076 #ifdef PNG_READ_EXPAND_SUPPORTED
6077 /* png_set_tRNS_to_alpha */
6079 image_transform_png_set_tRNS_to_alpha_set(PNG_CONST image_transform
*this,
6080 transform_display
*that
, png_structp pp
, png_infop pi
)
6082 png_set_tRNS_to_alpha(pp
);
6083 this->next
->set(this->next
, that
, pp
, pi
);
6087 image_transform_png_set_tRNS_to_alpha_mod(PNG_CONST image_transform
*this,
6088 image_pixel
*that
, png_const_structp pp
,
6089 PNG_CONST transform_display
*display
)
6091 /* LIBPNG BUG: this always forces palette images to RGB. */
6092 if (that
->colour_type
== PNG_COLOR_TYPE_PALETTE
)
6093 image_pixel_convert_PLTE(that
);
6095 /* This effectively does an 'expand' only if there is some transparency to
6096 * convert to an alpha channel.
6098 if (that
->have_tRNS
)
6099 image_pixel_add_alpha(that
, &display
->this);
6101 /* LIBPNG BUG: otherwise libpng still expands to 8 bits! */
6104 if (that
->bit_depth
< 8)
6106 if (that
->sample_depth
< 8)
6107 that
->sample_depth
= 8;
6110 this->next
->mod(this->next
, that
, pp
, display
);
6114 image_transform_png_set_tRNS_to_alpha_add(image_transform
*this,
6115 PNG_CONST image_transform
**that
, png_byte colour_type
, png_byte bit_depth
)
6122 /* We don't know yet whether there will be a tRNS chunk, but we know that
6123 * this transformation should do nothing if there already is an alpha
6126 return (colour_type
& PNG_COLOR_MASK_ALPHA
) == 0;
6131 #define PT ITSTRUCT(tRNS_to_alpha)
6132 #endif /* PNG_READ_EXPAND_SUPPORTED */
6134 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
6135 /* png_set_gray_to_rgb */
6137 image_transform_png_set_gray_to_rgb_set(PNG_CONST image_transform
*this,
6138 transform_display
*that
, png_structp pp
, png_infop pi
)
6140 png_set_gray_to_rgb(pp
);
6141 this->next
->set(this->next
, that
, pp
, pi
);
6145 image_transform_png_set_gray_to_rgb_mod(PNG_CONST image_transform
*this,
6146 image_pixel
*that
, png_const_structp pp
,
6147 PNG_CONST transform_display
*display
)
6149 /* NOTE: we can actually pend the tRNS processing at this point because we
6150 * can correctly recognize the original pixel value even though we have
6151 * mapped the one gray channel to the three RGB ones, but in fact libpng
6152 * doesn't do this, so we don't either.
6154 if ((that
->colour_type
& PNG_COLOR_MASK_COLOR
) == 0 && that
->have_tRNS
)
6155 image_pixel_add_alpha(that
, &display
->this);
6157 /* Simply expand the bit depth and alter the colour type as required. */
6158 if (that
->colour_type
== PNG_COLOR_TYPE_GRAY
)
6160 /* RGB images have a bit depth at least equal to '8' */
6161 if (that
->bit_depth
< 8)
6162 that
->sample_depth
= that
->bit_depth
= 8;
6164 /* And just changing the colour type works here because the green and blue
6165 * channels are being maintained in lock-step with the red/gray:
6167 that
->colour_type
= PNG_COLOR_TYPE_RGB
;
6170 else if (that
->colour_type
== PNG_COLOR_TYPE_GRAY_ALPHA
)
6171 that
->colour_type
= PNG_COLOR_TYPE_RGB_ALPHA
;
6173 this->next
->mod(this->next
, that
, pp
, display
);
6177 image_transform_png_set_gray_to_rgb_add(image_transform
*this,
6178 PNG_CONST image_transform
**that
, png_byte colour_type
, png_byte bit_depth
)
6185 return (colour_type
& PNG_COLOR_MASK_COLOR
) == 0;
6190 #define PT ITSTRUCT(gray_to_rgb)
6191 #endif /* PNG_READ_GRAY_TO_RGB_SUPPORTED */
6193 #ifdef PNG_READ_EXPAND_SUPPORTED
6194 /* png_set_expand */
6196 image_transform_png_set_expand_set(PNG_CONST image_transform
*this,
6197 transform_display
*that
, png_structp pp
, png_infop pi
)
6200 this->next
->set(this->next
, that
, pp
, pi
);
6204 image_transform_png_set_expand_mod(PNG_CONST image_transform
*this,
6205 image_pixel
*that
, png_const_structp pp
,
6206 PNG_CONST transform_display
*display
)
6208 /* The general expand case depends on what the colour type is: */
6209 if (that
->colour_type
== PNG_COLOR_TYPE_PALETTE
)
6210 image_pixel_convert_PLTE(that
);
6211 else if (that
->bit_depth
< 8) /* grayscale */
6212 that
->sample_depth
= that
->bit_depth
= 8;
6214 if (that
->have_tRNS
)
6215 image_pixel_add_alpha(that
, &display
->this);
6217 this->next
->mod(this->next
, that
, pp
, display
);
6221 image_transform_png_set_expand_add(image_transform
*this,
6222 PNG_CONST image_transform
**that
, png_byte colour_type
, png_byte bit_depth
)
6229 /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit
6230 * depth is at least 8 already.
6232 return (colour_type
& PNG_COLOR_MASK_ALPHA
) == 0;
6237 #define PT ITSTRUCT(expand)
6238 #endif /* PNG_READ_EXPAND_SUPPORTED */
6240 #ifdef PNG_READ_EXPAND_SUPPORTED
6241 /* png_set_expand_gray_1_2_4_to_8
6242 * LIBPNG BUG: this just does an 'expand'
6245 image_transform_png_set_expand_gray_1_2_4_to_8_set(
6246 PNG_CONST image_transform
*this, transform_display
*that
, png_structp pp
,
6249 png_set_expand_gray_1_2_4_to_8(pp
);
6250 this->next
->set(this->next
, that
, pp
, pi
);
6254 image_transform_png_set_expand_gray_1_2_4_to_8_mod(
6255 PNG_CONST image_transform
*this, image_pixel
*that
, png_const_structp pp
,
6256 PNG_CONST transform_display
*display
)
6258 image_transform_png_set_expand_mod(this, that
, pp
, display
);
6262 image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform
*this,
6263 PNG_CONST image_transform
**that
, png_byte colour_type
, png_byte bit_depth
)
6265 return image_transform_png_set_expand_add(this, that
, colour_type
,
6269 IT(expand_gray_1_2_4_to_8
);
6271 #define PT ITSTRUCT(expand_gray_1_2_4_to_8)
6272 #endif /* PNG_READ_EXPAND_SUPPORTED */
6274 #ifdef PNG_READ_EXPAND_16_SUPPORTED
6275 /* png_set_expand_16 */
6277 image_transform_png_set_expand_16_set(PNG_CONST image_transform
*this,
6278 transform_display
*that
, png_structp pp
, png_infop pi
)
6280 png_set_expand_16(pp
);
6281 this->next
->set(this->next
, that
, pp
, pi
);
6285 image_transform_png_set_expand_16_mod(PNG_CONST image_transform
*this,
6286 image_pixel
*that
, png_const_structp pp
,
6287 PNG_CONST transform_display
*display
)
6289 /* Expect expand_16 to expand everything to 16 bits as a result of also
6290 * causing 'expand' to happen.
6292 if (that
->colour_type
== PNG_COLOR_TYPE_PALETTE
)
6293 image_pixel_convert_PLTE(that
);
6295 if (that
->have_tRNS
)
6296 image_pixel_add_alpha(that
, &display
->this);
6298 if (that
->bit_depth
< 16)
6299 that
->sample_depth
= that
->bit_depth
= 16;
6301 this->next
->mod(this->next
, that
, pp
, display
);
6305 image_transform_png_set_expand_16_add(image_transform
*this,
6306 PNG_CONST image_transform
**that
, png_byte colour_type
, png_byte bit_depth
)
6313 /* expand_16 does something unless the bit depth is already 16. */
6314 return bit_depth
< 16;
6319 #define PT ITSTRUCT(expand_16)
6320 #endif /* PNG_READ_EXPAND_16_SUPPORTED */
6322 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED /* API added in 1.5.4 */
6323 /* png_set_scale_16 */
6325 image_transform_png_set_scale_16_set(PNG_CONST image_transform
*this,
6326 transform_display
*that
, png_structp pp
, png_infop pi
)
6328 png_set_scale_16(pp
);
6329 this->next
->set(this->next
, that
, pp
, pi
);
6333 image_transform_png_set_scale_16_mod(PNG_CONST image_transform
*this,
6334 image_pixel
*that
, png_const_structp pp
,
6335 PNG_CONST transform_display
*display
)
6337 if (that
->bit_depth
== 16)
6339 that
->sample_depth
= that
->bit_depth
= 8;
6340 if (that
->red_sBIT
> 8) that
->red_sBIT
= 8;
6341 if (that
->green_sBIT
> 8) that
->green_sBIT
= 8;
6342 if (that
->blue_sBIT
> 8) that
->blue_sBIT
= 8;
6343 if (that
->alpha_sBIT
> 8) that
->alpha_sBIT
= 8;
6346 this->next
->mod(this->next
, that
, pp
, display
);
6350 image_transform_png_set_scale_16_add(image_transform
*this,
6351 PNG_CONST image_transform
**that
, png_byte colour_type
, png_byte bit_depth
)
6358 return bit_depth
> 8;
6363 #define PT ITSTRUCT(scale_16)
6364 #endif /* PNG_READ_SCALE_16_TO_8_SUPPORTED (1.5.4 on) */
6366 #ifdef PNG_READ_16_TO_8_SUPPORTED /* the default before 1.5.4 */
6367 /* png_set_strip_16 */
6369 image_transform_png_set_strip_16_set(PNG_CONST image_transform
*this,
6370 transform_display
*that
, png_structp pp
, png_infop pi
)
6372 png_set_strip_16(pp
);
6373 this->next
->set(this->next
, that
, pp
, pi
);
6377 image_transform_png_set_strip_16_mod(PNG_CONST image_transform
*this,
6378 image_pixel
*that
, png_const_structp pp
,
6379 PNG_CONST transform_display
*display
)
6381 if (that
->bit_depth
== 16)
6383 that
->sample_depth
= that
->bit_depth
= 8;
6384 if (that
->red_sBIT
> 8) that
->red_sBIT
= 8;
6385 if (that
->green_sBIT
> 8) that
->green_sBIT
= 8;
6386 if (that
->blue_sBIT
> 8) that
->blue_sBIT
= 8;
6387 if (that
->alpha_sBIT
> 8) that
->alpha_sBIT
= 8;
6389 /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
6390 * configuration option is set. From 1.5.4 the flag is never set and the
6391 * 'scale' API (above) must be used.
6393 # ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
6394 # if PNG_LIBPNG_VER >= 10504
6395 # error PNG_READ_ACCURATE_SCALE should not be set
6398 /* The strip 16 algorithm drops the low 8 bits rather than calculating
6399 * 1/257, so we need to adjust the permitted errors appropriately:
6400 * Notice that this is only relevant prior to the addition of the
6401 * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
6404 PNG_CONST
double d
= (255-128.5)/65535;
6413 this->next
->mod(this->next
, that
, pp
, display
);
6417 image_transform_png_set_strip_16_add(image_transform
*this,
6418 PNG_CONST image_transform
**that
, png_byte colour_type
, png_byte bit_depth
)
6425 return bit_depth
> 8;
6430 #define PT ITSTRUCT(strip_16)
6431 #endif /* PNG_READ_16_TO_8_SUPPORTED */
6433 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
6434 /* png_set_strip_alpha */
6436 image_transform_png_set_strip_alpha_set(PNG_CONST image_transform
*this,
6437 transform_display
*that
, png_structp pp
, png_infop pi
)
6439 png_set_strip_alpha(pp
);
6440 this->next
->set(this->next
, that
, pp
, pi
);
6444 image_transform_png_set_strip_alpha_mod(PNG_CONST image_transform
*this,
6445 image_pixel
*that
, png_const_structp pp
,
6446 PNG_CONST transform_display
*display
)
6448 if (that
->colour_type
== PNG_COLOR_TYPE_GRAY_ALPHA
)
6449 that
->colour_type
= PNG_COLOR_TYPE_GRAY
;
6450 else if (that
->colour_type
== PNG_COLOR_TYPE_RGB_ALPHA
)
6451 that
->colour_type
= PNG_COLOR_TYPE_RGB
;
6453 that
->have_tRNS
= 0;
6456 this->next
->mod(this->next
, that
, pp
, display
);
6460 image_transform_png_set_strip_alpha_add(image_transform
*this,
6461 PNG_CONST image_transform
**that
, png_byte colour_type
, png_byte bit_depth
)
6468 return (colour_type
& PNG_COLOR_MASK_ALPHA
) != 0;
6473 #define PT ITSTRUCT(strip_alpha)
6474 #endif /* PNG_READ_STRIP_ALPHA_SUPPORTED */
6476 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
6477 /* png_set_rgb_to_gray(png_structp, int err_action, double red, double green)
6478 * png_set_rgb_to_gray_fixed(png_structp, int err_action, png_fixed_point red,
6479 * png_fixed_point green)
6480 * png_get_rgb_to_gray_status
6482 * The 'default' test here uses values known to be used inside libpng:
6488 * These values are being retained for compatibility, along with the somewhat
6489 * broken truncation calculation in the fast-and-inaccurate code path. Older
6490 * versions of libpng will fail the accuracy tests below because they use the
6491 * truncation algorithm everywhere.
6493 #define data ITDATA(rgb_to_gray)
6496 double gamma
; /* File gamma to use in processing */
6498 /* The following are the parameters for png_set_rgb_to_gray: */
6499 # ifdef PNG_FLOATING_POINT_SUPPORTED
6501 double green_to_set
;
6503 png_fixed_point red_to_set
;
6504 png_fixed_point green_to_set
;
6507 /* The actual coefficients: */
6508 double red_coefficient
;
6509 double green_coefficient
;
6510 double blue_coefficient
;
6512 /* Set if the coeefficients have been overridden. */
6513 int coefficients_overridden
;
6516 #undef image_transform_ini
6517 #define image_transform_ini image_transform_png_set_rgb_to_gray_ini
6519 image_transform_png_set_rgb_to_gray_ini(PNG_CONST image_transform
*this,
6520 transform_display
*that
)
6522 png_modifier
*pm
= that
->pm
;
6523 PNG_CONST color_encoding
*e
= pm
->current_encoding
;
6527 /* Since we check the encoding this flag must be set: */
6528 pm
->test_uses_encoding
= 1;
6530 /* If 'e' is not NULL chromaticity information is present and either a cHRM
6531 * or an sRGB chunk will be inserted.
6535 /* Coefficients come from the encoding, but may need to be normalized to a
6536 * white point Y of 1.0
6538 PNG_CONST
double whiteY
= e
->red
.Y
+ e
->green
.Y
+ e
->blue
.Y
;
6540 data
.red_coefficient
= e
->red
.Y
;
6541 data
.green_coefficient
= e
->green
.Y
;
6542 data
.blue_coefficient
= e
->blue
.Y
;
6546 data
.red_coefficient
/= whiteY
;
6547 data
.green_coefficient
/= whiteY
;
6548 data
.blue_coefficient
/= whiteY
;
6554 /* The default (built in) coeffcients, as above: */
6555 data
.red_coefficient
= 6968 / 32768.;
6556 data
.green_coefficient
= 23434 / 32768.;
6557 data
.blue_coefficient
= 2366 / 32768.;
6560 data
.gamma
= pm
->current_gamma
;
6562 /* If not set then the calculations assume linear encoding (implicitly): */
6563 if (data
.gamma
== 0)
6566 /* The arguments to png_set_rgb_to_gray can override the coefficients implied
6567 * by the color space encoding. If doing exhaustive checks do the override
6568 * in each case, otherwise do it randomly.
6570 if (pm
->test_exhaustive
)
6572 /* First time in coefficients_overridden is 0, the following sets it to 1,
6573 * so repeat if it is set. If a test fails this may mean we subsequently
6574 * skip a non-override test, ignore that.
6576 data
.coefficients_overridden
= !data
.coefficients_overridden
;
6577 pm
->repeat
= data
.coefficients_overridden
!= 0;
6581 data
.coefficients_overridden
= random_choice();
6583 if (data
.coefficients_overridden
)
6585 /* These values override the color encoding defaults, simply use random
6592 data
.green_coefficient
= total
= (ru
& 0xffff) / 65535.;
6594 data
.red_coefficient
= (1 - total
) * (ru
& 0xffff) / 65535.;
6595 total
+= data
.red_coefficient
;
6596 data
.blue_coefficient
= 1 - total
;
6598 # ifdef PNG_FLOATING_POINT_SUPPORTED
6599 data
.red_to_set
= data
.red_coefficient
;
6600 data
.green_to_set
= data
.green_coefficient
;
6602 data
.red_to_set
= fix(data
.red_coefficient
);
6603 data
.green_to_set
= fix(data
.green_coefficient
);
6606 /* The following just changes the error messages: */
6607 pm
->encoding_ignored
= 1;
6612 data
.red_to_set
= -1;
6613 data
.green_to_set
= -1;
6616 /* Adjust the error limit in the png_modifier because of the larger errors
6617 * produced in the digitization during the gamma handling.
6619 if (data
.gamma
!= 1) /* Use gamma tables */
6621 if (that
->this.bit_depth
== 16 || pm
->assume_16_bit_calculations
)
6623 /* The 16 bit case ends up producing a maximum error of about
6624 * +/-5 in 65535, allow for +/-8 with the given gamma.
6626 that
->pm
->limit
+= pow(8./65535, data
.gamma
);
6631 /* Rounding to 8 bits in the linear space causes massive errors which
6632 * will trigger the error check in transform_range_check. Fix that
6633 * here by taking the gamma encoding into account.
6635 that
->pm
->limit
+= pow(1./255, data
.gamma
);
6641 /* With no gamma correction a large error comes from the truncation of the
6642 * calculation in the 8 bit case, allow for that here.
6644 if (that
->this.bit_depth
!= 16)
6645 that
->pm
->limit
+= 4E-3;
6650 image_transform_png_set_rgb_to_gray_set(PNG_CONST image_transform
*this,
6651 transform_display
*that
, png_structp pp
, png_infop pi
)
6653 PNG_CONST
int error_action
= 1; /* no error, no defines in png.h */
6655 # ifdef PNG_FLOATING_POINT_SUPPORTED
6656 png_set_rgb_to_gray(pp
, error_action
, data
.red_to_set
, data
.green_to_set
);
6658 png_set_rgb_to_gray_fixed(pp
, error_action
, data
.red_to_set
,
6662 # ifdef PNG_READ_cHRM_SUPPORTED
6663 if (that
->pm
->current_encoding
!= 0)
6665 /* We have an encoding so a cHRM chunk may have been set; if so then
6666 * check that the libpng APIs give the correct (X,Y,Z) values within
6667 * some margin of error for the round trip through the chromaticity
6670 # ifdef PNG_FLOATING_POINT_SUPPORTED
6671 # define API_function png_get_cHRM_XYZ
6672 # define API_form "FP"
6673 # define API_type double
6674 # define API_cvt(x) (x)
6676 # define API_function png_get_cHRM_XYZ_fixed
6677 # define API_form "fixed"
6678 # define API_type png_fixed_point
6679 # define API_cvt(x) ((double)(x)/PNG_FP_1)
6682 API_type rX
, gX
, bX
;
6683 API_type rY
, gY
, bY
;
6684 API_type rZ
, gZ
, bZ
;
6686 if ((API_function(pp
, pi
, &rX
, &rY
, &rZ
, &gX
, &gY
, &gZ
, &bX
, &bY
, &bZ
)
6687 & PNG_INFO_cHRM
) != 0)
6691 color_encoding e
, o
;
6693 /* Expect libpng to return a normalized result, but the original
6694 * color space encoding may not be normalized.
6696 modifier_current_encoding(that
->pm
, &o
);
6697 normalize_color_encoding(&o
);
6699 /* Sanity check the pngvalid code - the coefficients should match
6700 * the normalized Y values of the encoding unless they were
6703 if (data
.red_to_set
== -1 && data
.green_to_set
== -1 &&
6704 (fabs(o
.red
.Y
- data
.red_coefficient
) > DBL_EPSILON
||
6705 fabs(o
.green
.Y
- data
.green_coefficient
) > DBL_EPSILON
||
6706 fabs(o
.blue
.Y
- data
.blue_coefficient
) > DBL_EPSILON
))
6707 png_error(pp
, "internal pngvalid cHRM coefficient error");
6709 /* Generate a colour space encoding. */
6710 e
.gamma
= o
.gamma
; /* not used */
6711 e
.red
.X
= API_cvt(rX
);
6712 e
.red
.Y
= API_cvt(rY
);
6713 e
.red
.Z
= API_cvt(rZ
);
6714 e
.green
.X
= API_cvt(gX
);
6715 e
.green
.Y
= API_cvt(gY
);
6716 e
.green
.Z
= API_cvt(gZ
);
6717 e
.blue
.X
= API_cvt(bX
);
6718 e
.blue
.Y
= API_cvt(bY
);
6719 e
.blue
.Z
= API_cvt(bZ
);
6721 /* This should match the original one from the png_modifier, within
6722 * the range permitted by the libpng fixed point representation.
6725 el
= "-"; /* Set to element name with error */
6727 # define CHECK(col,x)\
6729 double err = fabs(o.col.x - e.col.x);\
6733 el = #col "(" #x ")";\
6747 /* Here in both fixed and floating cases to check the values read
6748 * from the cHRm chunk. PNG uses fixed point in the cHRM chunk, so
6749 * we can't expect better than +/-.5E-5 on the result, allow 1E-5.
6756 pos
= safecat(buffer
, sizeof buffer
, pos
, API_form
);
6757 pos
= safecat(buffer
, sizeof buffer
, pos
, " cHRM ");
6758 pos
= safecat(buffer
, sizeof buffer
, pos
, el
);
6759 pos
= safecat(buffer
, sizeof buffer
, pos
, " error: ");
6760 pos
= safecatd(buffer
, sizeof buffer
, pos
, maxe
, 7);
6761 pos
= safecat(buffer
, sizeof buffer
, pos
, " ");
6762 /* Print the color space without the gamma value: */
6763 pos
= safecat_color_encoding(buffer
, sizeof buffer
, pos
, &o
, 0);
6764 pos
= safecat(buffer
, sizeof buffer
, pos
, " -> ");
6765 pos
= safecat_color_encoding(buffer
, sizeof buffer
, pos
, &e
, 0);
6767 png_error(pp
, buffer
);
6771 # endif /* READ_cHRM */
6773 this->next
->set(this->next
, that
, pp
, pi
);
6777 image_transform_png_set_rgb_to_gray_mod(PNG_CONST image_transform
*this,
6778 image_pixel
*that
, png_const_structp pp
,
6779 PNG_CONST transform_display
*display
)
6781 if ((that
->colour_type
& PNG_COLOR_MASK_COLOR
) != 0)
6785 if (that
->colour_type
== PNG_COLOR_TYPE_PALETTE
)
6786 image_pixel_convert_PLTE(that
);
6788 /* Image now has RGB channels... */
6790 PNG_CONST png_modifier
*pm
= display
->pm
;
6791 PNG_CONST
unsigned int sample_depth
= that
->sample_depth
;
6794 double rlo
, rhi
, glo
, ghi
, blo
, bhi
, graylo
, grayhi
;
6796 /* Do this using interval arithmetic, otherwise it is too difficult to
6797 * handle the errors correctly.
6799 * To handle the gamma correction work out the upper and lower bounds
6800 * of the digitized value. Assume rounding here - normally the values
6801 * will be identical after this operation if there is only one
6802 * transform, feel free to delete the png_error checks on this below in
6803 * the future (this is just me trying to ensure it works!)
6805 r
= rlo
= rhi
= that
->redf
;
6807 rlo
= digitize(pm
, rlo
, sample_depth
, 1/*round*/);
6809 rhi
= digitize(pm
, rhi
, sample_depth
, 1/*round*/);
6811 g
= glo
= ghi
= that
->greenf
;
6812 glo
-= that
->greene
;
6813 glo
= digitize(pm
, glo
, sample_depth
, 1/*round*/);
6814 ghi
+= that
->greene
;
6815 ghi
= digitize(pm
, ghi
, sample_depth
, 1/*round*/);
6817 b
= blo
= bhi
= that
->bluef
;
6819 blo
= digitize(pm
, blo
, sample_depth
, 1/*round*/);
6820 bhi
+= that
->greene
;
6821 bhi
= digitize(pm
, bhi
, sample_depth
, 1/*round*/);
6823 isgray
= r
==g
&& g
==b
;
6825 if (data
.gamma
!= 1)
6827 PNG_CONST
double power
= 1/data
.gamma
;
6828 PNG_CONST
double abse
= abserr(pm
, sample_depth
, sample_depth
);
6830 /* 'abse' is the absolute error permitted in linear calculations. It
6831 * is used here to capture the error permitted in the handling
6832 * (undoing) of the gamma encoding. Once again digitization occurs
6833 * to handle the upper and lower bounds of the values. This is
6834 * where the real errors are introduced.
6837 rlo
= digitize(pm
, pow(rlo
, power
)-abse
, sample_depth
, 1);
6838 rhi
= digitize(pm
, pow(rhi
, power
)+abse
, sample_depth
, 1);
6841 glo
= digitize(pm
, pow(glo
, power
)-abse
, sample_depth
, 1);
6842 ghi
= digitize(pm
, pow(ghi
, power
)+abse
, sample_depth
, 1);
6845 blo
= digitize(pm
, pow(blo
, power
)-abse
, sample_depth
, 1);
6846 bhi
= digitize(pm
, pow(bhi
, power
)+abse
, sample_depth
, 1);
6849 /* Now calculate the actual gray values. Although the error in the
6850 * coefficients depends on whether they were specified on the command
6851 * line (in which case truncation to 15 bits happened) or not (rounding
6852 * was used) the maxium error in an individual coefficient is always
6853 * 1/32768, because even in the rounding case the requirement that
6854 * coefficients add up to 32768 can cause a larger rounding error.
6856 * The only time when rounding doesn't occur in 1.5.5 and later is when
6857 * the non-gamma code path is used for less than 16 bit data.
6859 gray
= r
* data
.red_coefficient
+ g
* data
.green_coefficient
+
6860 b
* data
.blue_coefficient
;
6863 PNG_CONST
int do_round
= data
.gamma
!= 1 || sample_depth
== 16;
6864 PNG_CONST
double ce
= 1. / 32768;
6866 graylo
= digitize(pm
, rlo
* (data
.red_coefficient
-ce
) +
6867 glo
* (data
.green_coefficient
-ce
) +
6868 blo
* (data
.blue_coefficient
-ce
), sample_depth
, do_round
);
6872 grayhi
= digitize(pm
, rhi
* (data
.red_coefficient
+ce
) +
6873 ghi
* (data
.green_coefficient
+ce
) +
6874 bhi
* (data
.blue_coefficient
+ce
), sample_depth
, do_round
);
6879 /* And invert the gamma. */
6880 if (data
.gamma
!= 1)
6882 PNG_CONST
double power
= data
.gamma
;
6884 gray
= pow(gray
, power
);
6885 graylo
= digitize(pm
, pow(graylo
, power
), sample_depth
, 1);
6886 grayhi
= digitize(pm
, pow(grayhi
, power
), sample_depth
, 1);
6889 /* Now the error can be calculated.
6891 * If r==g==b because there is no overall gamma correction libpng
6892 * currently preserves the original value.
6895 err
= (that
->rede
+ that
->greene
+ that
->bluee
)/3;
6899 err
= fabs(grayhi
-gray
);
6900 if (fabs(gray
- graylo
) > err
)
6901 err
= fabs(graylo
-gray
);
6903 /* Check that this worked: */
6904 if (err
> display
->pm
->limit
)
6909 pos
= safecat(buffer
, sizeof buffer
, pos
, "rgb_to_gray error ");
6910 pos
= safecatd(buffer
, sizeof buffer
, pos
, err
, 6);
6911 pos
= safecat(buffer
, sizeof buffer
, pos
, " exceeds limit ");
6912 pos
= safecatd(buffer
, sizeof buffer
, pos
,
6913 display
->pm
->limit
, 6);
6914 png_error(pp
, buffer
);
6919 that
->bluef
= that
->greenf
= that
->redf
= gray
;
6920 that
->bluee
= that
->greene
= that
->rede
= err
;
6922 /* The sBIT is the minium of the three colour channel sBITs. */
6923 if (that
->red_sBIT
> that
->green_sBIT
)
6924 that
->red_sBIT
= that
->green_sBIT
;
6925 if (that
->red_sBIT
> that
->blue_sBIT
)
6926 that
->red_sBIT
= that
->blue_sBIT
;
6927 that
->blue_sBIT
= that
->green_sBIT
= that
->red_sBIT
;
6929 /* And remove the colour bit in the type: */
6930 if (that
->colour_type
== PNG_COLOR_TYPE_RGB
)
6931 that
->colour_type
= PNG_COLOR_TYPE_GRAY
;
6932 else if (that
->colour_type
== PNG_COLOR_TYPE_RGB_ALPHA
)
6933 that
->colour_type
= PNG_COLOR_TYPE_GRAY_ALPHA
;
6936 this->next
->mod(this->next
, that
, pp
, display
);
6940 image_transform_png_set_rgb_to_gray_add(image_transform
*this,
6941 PNG_CONST image_transform
**that
, png_byte colour_type
, png_byte bit_depth
)
6948 return (colour_type
& PNG_COLOR_MASK_COLOR
) != 0;
6954 #define PT ITSTRUCT(rgb_to_gray)
6955 #undef image_transform_ini
6956 #define image_transform_ini image_transform_default_ini
6957 #endif /* PNG_READ_RGB_TO_GRAY_SUPPORTED */
6959 #ifdef PNG_READ_BACKGROUND_SUPPORTED
6960 /* png_set_background(png_structp, png_const_color_16p background_color,
6961 * int background_gamma_code, int need_expand, double background_gamma)
6962 * png_set_background_fixed(png_structp, png_const_color_16p background_color,
6963 * int background_gamma_code, int need_expand,
6964 * png_fixed_point background_gamma)
6966 * As with rgb_to_gray this ignores the gamma (at present.)
6968 #define data ITDATA(background)
6969 static image_pixel data
;
6972 image_transform_png_set_background_set(PNG_CONST image_transform
*this,
6973 transform_display
*that
, png_structp pp
, png_infop pi
)
6975 png_byte colour_type
, bit_depth
;
6976 png_byte random_bytes
[8]; /* 8 bytes - 64 bits - the biggest pixel */
6979 /* We need a background colour, because we don't know exactly what transforms
6980 * have been set we have to supply the colour in the original file format and
6981 * so we need to know what that is! The background colour is stored in the
6982 * transform_display.
6984 RANDOMIZE(random_bytes
);
6986 /* Read the random value, for colour type 3 the background colour is actually
6987 * expressed as a 24bit rgb, not an index.
6989 colour_type
= that
->this.colour_type
;
6990 if (colour_type
== 3)
6992 colour_type
= PNG_COLOR_TYPE_RGB
;
6997 bit_depth
= that
->this.bit_depth
;
6999 image_pixel_init(&data
, random_bytes
, colour_type
,
7000 bit_depth
, 0/*x*/, 0/*unused: palette*/);
7002 /* Extract the background colour from this image_pixel, but make sure the
7003 * unused fields of 'back' are garbage.
7007 if (colour_type
& PNG_COLOR_MASK_COLOR
)
7009 back
.red
= (png_uint_16
)data
.red
;
7010 back
.green
= (png_uint_16
)data
.green
;
7011 back
.blue
= (png_uint_16
)data
.blue
;
7015 back
.gray
= (png_uint_16
)data
.red
;
7017 # ifdef PNG_FLOATING_POINT_SUPPORTED
7018 png_set_background(pp
, &back
, PNG_BACKGROUND_GAMMA_FILE
, 1/*need expand*/,
7021 png_set_background_fixed(pp
, &back
, PNG_BACKGROUND_GAMMA_FILE
,
7022 1/*need expand*/, 0);
7025 this->next
->set(this->next
, that
, pp
, pi
);
7029 image_transform_png_set_background_mod(PNG_CONST image_transform
*this,
7030 image_pixel
*that
, png_const_structp pp
,
7031 PNG_CONST transform_display
*display
)
7033 /* Check for tRNS first: */
7034 if (that
->have_tRNS
&& that
->colour_type
!= PNG_COLOR_TYPE_PALETTE
)
7035 image_pixel_add_alpha(that
, &display
->this);
7037 /* This is only necessary if the alpha value is less than 1. */
7038 if (that
->alphaf
< 1)
7040 /* Now we do the background calculation without any gamma correction. */
7041 if (that
->alphaf
<= 0)
7043 that
->redf
= data
.redf
;
7044 that
->greenf
= data
.greenf
;
7045 that
->bluef
= data
.bluef
;
7047 that
->rede
= data
.rede
;
7048 that
->greene
= data
.greene
;
7049 that
->bluee
= data
.bluee
;
7051 that
->red_sBIT
= data
.red_sBIT
;
7052 that
->green_sBIT
= data
.green_sBIT
;
7053 that
->blue_sBIT
= data
.blue_sBIT
;
7056 else /* 0 < alpha < 1 */
7058 double alf
= 1 - that
->alphaf
;
7060 that
->redf
= that
->redf
* that
->alphaf
+ data
.redf
* alf
;
7061 that
->rede
= that
->rede
* that
->alphaf
+ data
.rede
* alf
+
7063 that
->greenf
= that
->greenf
* that
->alphaf
+ data
.greenf
* alf
;
7064 that
->greene
= that
->greene
* that
->alphaf
+ data
.greene
* alf
+
7066 that
->bluef
= that
->bluef
* that
->alphaf
+ data
.bluef
* alf
;
7067 that
->bluee
= that
->bluee
* that
->alphaf
+ data
.bluee
* alf
+
7071 /* Remove the alpha type and set the alpha (not in that order.) */
7075 if (that
->colour_type
== PNG_COLOR_TYPE_RGB_ALPHA
)
7076 that
->colour_type
= PNG_COLOR_TYPE_RGB
;
7077 else if (that
->colour_type
== PNG_COLOR_TYPE_GRAY_ALPHA
)
7078 that
->colour_type
= PNG_COLOR_TYPE_GRAY
;
7079 /* PNG_COLOR_TYPE_PALETTE is not changed */
7082 this->next
->mod(this->next
, that
, pp
, display
);
7085 #define image_transform_png_set_background_add image_transform_default_add
7090 #define PT ITSTRUCT(background)
7091 #endif /* PNG_READ_BACKGROUND_SUPPORTED */
7093 /* This may just be 'end' if all the transforms are disabled! */
7094 static image_transform
*PNG_CONST image_transform_first
= &PT
;
7097 transform_enable(PNG_CONST
char *name
)
7099 /* Everything starts out enabled, so if we see an 'enable' disabled
7100 * everything else the first time round.
7102 static int all_disabled
= 0;
7104 image_transform
*list
= image_transform_first
;
7106 while (list
!= &image_transform_end
)
7108 if (strcmp(list
->name
, name
) == 0)
7113 else if (!all_disabled
)
7123 fprintf(stderr
, "pngvalid: --transform-enable=%s: unknown transform\n",
7130 transform_disable(PNG_CONST
char *name
)
7132 image_transform
*list
= image_transform_first
;
7134 while (list
!= &image_transform_end
)
7136 if (strcmp(list
->name
, name
) == 0)
7145 fprintf(stderr
, "pngvalid: --transform-disable=%s: unknown transform\n",
7151 image_transform_reset_count(void)
7153 image_transform
*next
= image_transform_first
;
7156 while (next
!= &image_transform_end
)
7158 next
->local_use
= 0;
7164 /* This can only happen if we every have more than 32 transforms (excluding
7165 * the end) in the list.
7167 if (count
> 32) abort();
7171 image_transform_test_counter(png_uint_32 counter
, unsigned int max
)
7173 /* Test the list to see if there is any point contining, given a current
7174 * counter and a 'max' value.
7176 image_transform
*next
= image_transform_first
;
7178 while (next
!= &image_transform_end
)
7180 /* For max 0 or 1 continue until the counter overflows: */
7183 /* Continue if any entry hasn't reacked the max. */
7184 if (max
> 1 && next
->local_use
< max
)
7189 return max
<= 1 && counter
== 0;
7193 image_transform_add(PNG_CONST image_transform
**this, unsigned int max
,
7194 png_uint_32 counter
, char *name
, size_t sizeof_name
, size_t *pos
,
7195 png_byte colour_type
, png_byte bit_depth
)
7197 for (;;) /* until we manage to add something */
7200 image_transform
*list
;
7202 /* Find the next counter value, if the counter is zero this is the start
7203 * of the list. This routine always returns the current counter (not the
7204 * next) so it returns 0 at the end and expects 0 at the beginning.
7206 if (counter
== 0) /* first time */
7208 image_transform_reset_count();
7212 counter
= random_32();
7214 else /* advance the counter */
7218 case 0: ++counter
; break;
7219 case 1: counter
<<= 1; break;
7220 default: counter
= random_32(); break;
7224 /* Now add all these items, if possible */
7225 *this = &image_transform_end
;
7226 list
= image_transform_first
;
7229 /* Go through the whole list adding anything that the counter selects: */
7230 while (list
!= &image_transform_end
)
7232 if ((counter
& mask
) != 0 && list
->enable
&&
7233 (max
== 0 || list
->local_use
< max
))
7235 /* Candidate to add: */
7236 if (list
->add(list
, this, colour_type
, bit_depth
) || max
== 0)
7238 /* Added, so add to the name too. */
7239 *pos
= safecat(name
, sizeof_name
, *pos
, " +");
7240 *pos
= safecat(name
, sizeof_name
, *pos
, list
->name
);
7245 /* Not useful and max>0, so remove it from *this: */
7249 /* And, since we know it isn't useful, stop it being added again
7252 list
->local_use
= max
;
7260 /* Now if anything was added we have something to do. */
7261 if (*this != &image_transform_end
)
7264 /* Nothing added, but was there anything in there to add? */
7265 if (!image_transform_test_counter(counter
, max
))
7270 #ifdef THIS_IS_THE_PROFORMA
7272 image_transform_png_set_@
_set(PNG_CONST image_transform
*this,
7273 transform_display
*that
, png_structp pp
, png_infop pi
)
7276 this->next
->set(this->next
, that
, pp
, pi
);
7280 image_transform_png_set_@
_mod(PNG_CONST image_transform
*this,
7281 image_pixel
*that
, png_const_structp pp
,
7282 PNG_CONST transform_display
*display
)
7284 this->next
->mod(this->next
, that
, pp
, display
);
7288 image_transform_png_set_@
_add(image_transform
*this,
7289 PNG_CONST image_transform
**that
, char *name
, size_t sizeof_name
,
7290 size_t *pos
, png_byte colour_type
, png_byte bit_depth
)
7295 *pos
= safecat(name
, sizeof_name
, *pos
, " +@");
7303 /* png_set_quantize(png_structp, png_colorp palette, int num_palette,
7304 * int maximum_colors, png_const_uint_16p histogram, int full_quantize)
7306 * Very difficult to validate this!
7310 /* The data layout transforms are handled by swapping our own channel data,
7311 * necessarily these need to happen at the end of the transform list because the
7312 * semantic of the channels changes after these are executed. Some of these,
7313 * like set_shift and set_packing, can't be done at present because they change
7314 * the layout of the data at the sub-sample level so sample() won't get the
7317 /* png_set_invert_alpha */
7323 /* png_set_swap_alpha */
7329 /* png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags)); */
7332 /* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */
7335 /* png_set_packing */
7338 /* png_set_packswap */
7341 /* png_set_invert_mono */
7344 /* png_set_shift(png_structp, png_const_color_8p true_bits) */
7348 perform_transform_test(png_modifier
*pm
)
7350 png_byte colour_type
= 0;
7351 png_byte bit_depth
= 0;
7352 unsigned int palette_number
= 0;
7354 while (next_format(&colour_type
, &bit_depth
, &palette_number
))
7356 png_uint_32 counter
= 0;
7360 base_pos
= safecat(name
, sizeof name
, 0, "transform:");
7364 size_t pos
= base_pos
;
7365 PNG_CONST image_transform
*list
= 0;
7367 /* 'max' is currently hardwired to '1'; this should be settable on the
7370 counter
= image_transform_add(&list
, 1/*max*/, counter
,
7371 name
, sizeof name
, &pos
, colour_type
, bit_depth
);
7376 /* The command line can change this to checking interlaced images. */
7380 transform_test(pm
, FILEID(colour_type
, bit_depth
, palette_number
,
7381 pm
->interlace_type
, 0, 0, 0), list
, name
);
7390 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
7392 /********************************* GAMMA TESTS ********************************/
7393 #ifdef PNG_READ_GAMMA_SUPPORTED
7394 /* Reader callbacks and implementations, where they differ from the standard
7397 typedef struct gamma_display
7399 standard_display
this;
7404 double screen_gamma
;
7405 double background_gamma
;
7408 int use_input_precision
;
7412 png_color_16 background_color
;
7414 /* Local variables */
7420 #define ALPHA_MODE_OFFSET 4
7423 gamma_display_init(gamma_display
*dp
, png_modifier
*pm
, png_uint_32 id
,
7424 double file_gamma
, double screen_gamma
, png_byte sbit
, int threshold_test
,
7425 int use_input_precision
, int scale16
, int expand16
,
7426 int do_background
, PNG_CONST png_color_16
*pointer_to_the_background_color
,
7427 double background_gamma
)
7429 /* Standard fields */
7430 standard_display_init(&dp
->this, &pm
->this, id
, 0/*do_interlace*/,
7431 pm
->use_update_info
);
7433 /* Parameter fields */
7435 dp
->file_gamma
= file_gamma
;
7436 dp
->screen_gamma
= screen_gamma
;
7437 dp
->background_gamma
= background_gamma
;
7439 dp
->threshold_test
= threshold_test
;
7440 dp
->use_input_precision
= use_input_precision
;
7441 dp
->scale16
= scale16
;
7442 dp
->expand16
= expand16
;
7443 dp
->do_background
= do_background
;
7444 if (do_background
&& pointer_to_the_background_color
!= 0)
7445 dp
->background_color
= *pointer_to_the_background_color
;
7447 memset(&dp
->background_color
, 0, sizeof dp
->background_color
);
7449 /* Local variable fields */
7450 dp
->maxerrout
= dp
->maxerrpc
= dp
->maxerrabs
= 0;
7454 gamma_info_imp(gamma_display
*dp
, png_structp pp
, png_infop pi
)
7456 /* Reuse the standard stuff as appropriate. */
7457 standard_info_part1(&dp
->this, pp
, pi
);
7459 /* If requested strip 16 to 8 bits - this is handled automagically below
7460 * because the output bit depth is read from the library. Note that there
7461 * are interactions with sBIT but, internally, libpng makes sbit at most
7462 * PNG_MAX_GAMMA_8 when doing the following.
7465 # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
7466 png_set_scale_16(pp
);
7468 /* The following works both in 1.5.4 and earlier versions: */
7469 # ifdef PNG_READ_16_TO_8_SUPPORTED
7470 png_set_strip_16(pp
);
7472 png_error(pp
, "scale16 (16 to 8 bit conversion) not supported");
7477 # ifdef PNG_READ_EXPAND_16_SUPPORTED
7478 png_set_expand_16(pp
);
7480 png_error(pp
, "expand16 (8 to 16 bit conversion) not supported");
7483 if (dp
->do_background
>= ALPHA_MODE_OFFSET
)
7485 # ifdef PNG_READ_ALPHA_MODE_SUPPORTED
7487 /* This tests the alpha mode handling, if supported. */
7488 int mode
= dp
->do_background
- ALPHA_MODE_OFFSET
;
7490 /* The gamma value is the output gamma, and is in the standard,
7491 * non-inverted, represenation. It provides a default for the PNG file
7492 * gamma, but since the file has a gAMA chunk this does not matter.
7494 PNG_CONST
double sg
= dp
->screen_gamma
;
7495 # ifndef PNG_FLOATING_POINT_SUPPORTED
7496 PNG_CONST png_fixed_point g
= fix(sg
);
7499 # ifdef PNG_FLOATING_POINT_SUPPORTED
7500 png_set_alpha_mode(pp
, mode
, sg
);
7502 png_set_alpha_mode_fixed(pp
, mode
, g
);
7505 /* However, for the standard Porter-Duff algorithm the output defaults
7506 * to be linear, so if the test requires non-linear output it must be
7509 if (mode
== PNG_ALPHA_STANDARD
&& sg
!= 1)
7511 # ifdef PNG_FLOATING_POINT_SUPPORTED
7512 png_set_gamma(pp
, sg
, dp
->file_gamma
);
7514 png_fixed_point f
= fix(dp
->file_gamma
);
7515 png_set_gamma_fixed(pp
, g
, f
);
7520 png_error(pp
, "alpha mode handling not supported");
7526 /* Set up gamma processing. */
7527 # ifdef PNG_FLOATING_POINT_SUPPORTED
7528 png_set_gamma(pp
, dp
->screen_gamma
, dp
->file_gamma
);
7531 png_fixed_point s
= fix(dp
->screen_gamma
);
7532 png_fixed_point f
= fix(dp
->file_gamma
);
7533 png_set_gamma_fixed(pp
, s
, f
);
7537 if (dp
->do_background
)
7539 # ifdef PNG_READ_BACKGROUND_SUPPORTED
7540 /* NOTE: this assumes the caller provided the correct background gamma!
7542 PNG_CONST
double bg
= dp
->background_gamma
;
7543 # ifndef PNG_FLOATING_POINT_SUPPORTED
7544 PNG_CONST png_fixed_point g
= fix(bg
);
7547 # ifdef PNG_FLOATING_POINT_SUPPORTED
7548 png_set_background(pp
, &dp
->background_color
, dp
->do_background
,
7549 0/*need_expand*/, bg
);
7551 png_set_background_fixed(pp
, &dp
->background_color
,
7552 dp
->do_background
, 0/*need_expand*/, g
);
7555 png_error(pp
, "png_set_background not supported");
7561 int i
= dp
->this.use_update_info
;
7562 /* Always do one call, even if use_update_info is 0. */
7564 png_read_update_info(pp
, pi
);
7568 /* Now we may get a different cbRow: */
7569 standard_info_part2(&dp
->this, pp
, pi
, 1 /*images*/);
7573 gamma_info(png_structp pp
, png_infop pi
)
7575 gamma_info_imp(voidcast(gamma_display
*, png_get_progressive_ptr(pp
)), pp
,
7579 /* Validate a single component value - the routine gets the input and output
7580 * sample values as unscaled PNG component values along with a cache of all the
7581 * information required to validate the values.
7583 typedef struct validate_info
7585 png_const_structp pp
;
7588 int use_input_precision
;
7591 unsigned int sbit_max
;
7592 unsigned int isbit_shift
;
7593 unsigned int outmax
;
7595 double gamma_correction
; /* Overall correction required. */
7596 double file_inverse
; /* Inverse of file gamma. */
7597 double screen_gamma
;
7598 double screen_inverse
; /* Inverse of screen gamma. */
7600 double background_red
; /* Linear background value, red or gray. */
7601 double background_green
;
7602 double background_blue
;
7608 double maxout_total
; /* Total including quantization error */
7615 init_validate_info(validate_info
*vi
, gamma_display
*dp
, png_const_structp pp
,
7616 int in_depth
, int out_depth
)
7618 PNG_CONST
unsigned int outmax
= (1U<<out_depth
)-1;
7623 if (dp
->sbit
> 0 && dp
->sbit
< in_depth
)
7625 vi
->sbit
= dp
->sbit
;
7626 vi
->isbit_shift
= in_depth
- dp
->sbit
;
7631 vi
->sbit
= (png_byte
)in_depth
;
7632 vi
->isbit_shift
= 0;
7635 vi
->sbit_max
= (1U << vi
->sbit
)-1;
7637 /* This mimics the libpng threshold test, '0' is used to prevent gamma
7638 * correction in the validation test.
7640 vi
->screen_gamma
= dp
->screen_gamma
;
7641 if (fabs(vi
->screen_gamma
-1) < PNG_GAMMA_THRESHOLD
)
7642 vi
->screen_gamma
= vi
->screen_inverse
= 0;
7644 vi
->screen_inverse
= 1/vi
->screen_gamma
;
7646 vi
->use_input_precision
= dp
->use_input_precision
;
7647 vi
->outmax
= outmax
;
7648 vi
->maxabs
= abserr(dp
->pm
, in_depth
, out_depth
);
7649 vi
->maxpc
= pcerr(dp
->pm
, in_depth
, out_depth
);
7650 vi
->maxcalc
= calcerr(dp
->pm
, in_depth
, out_depth
);
7651 vi
->maxout
= outerr(dp
->pm
, in_depth
, out_depth
);
7652 vi
->outquant
= output_quantization_factor(dp
->pm
, in_depth
, out_depth
);
7653 vi
->maxout_total
= vi
->maxout
+ vi
->outquant
* .5;
7654 vi
->outlog
= outlog(dp
->pm
, in_depth
, out_depth
);
7656 if ((dp
->this.colour_type
& PNG_COLOR_MASK_ALPHA
) != 0 ||
7657 (dp
->this.colour_type
== 3 && dp
->this.is_transparent
))
7659 vi
->do_background
= dp
->do_background
;
7661 if (vi
->do_background
!= 0)
7663 PNG_CONST
double bg_inverse
= 1/dp
->background_gamma
;
7666 /* Caller must at least put the gray value into the red channel */
7667 r
= dp
->background_color
.red
; r
/= outmax
;
7668 g
= dp
->background_color
.green
; g
/= outmax
;
7669 b
= dp
->background_color
.blue
; b
/= outmax
;
7672 /* libpng doesn't do this optimization, if we do pngvalid will fail.
7674 if (fabs(bg_inverse
-1) >= PNG_GAMMA_THRESHOLD
)
7677 r
= pow(r
, bg_inverse
);
7678 g
= pow(g
, bg_inverse
);
7679 b
= pow(b
, bg_inverse
);
7682 vi
->background_red
= r
;
7683 vi
->background_green
= g
;
7684 vi
->background_blue
= b
;
7688 vi
->do_background
= 0;
7690 if (vi
->do_background
== 0)
7691 vi
->background_red
= vi
->background_green
= vi
->background_blue
= 0;
7693 vi
->gamma_correction
= 1/(dp
->file_gamma
*dp
->screen_gamma
);
7694 if (fabs(vi
->gamma_correction
-1) < PNG_GAMMA_THRESHOLD
)
7695 vi
->gamma_correction
= 0;
7697 vi
->file_inverse
= 1/dp
->file_gamma
;
7698 if (fabs(vi
->file_inverse
-1) < PNG_GAMMA_THRESHOLD
)
7699 vi
->file_inverse
= 0;
7701 vi
->scale16
= dp
->scale16
;
7704 /* This function handles composition of a single non-alpha component. The
7705 * argument is the input sample value, in the range 0..1, and the alpha value.
7706 * The result is the composed, linear, input sample. If alpha is less than zero
7707 * this is the alpha component and the function should not be called!
7710 gamma_component_compose(int do_background
, double input_sample
, double alpha
,
7711 double background
, int *compose
)
7713 switch (do_background
)
7715 #ifdef PNG_READ_BACKGROUND_SUPPORTED
7716 case PNG_BACKGROUND_GAMMA_SCREEN
:
7717 case PNG_BACKGROUND_GAMMA_FILE
:
7718 case PNG_BACKGROUND_GAMMA_UNIQUE
:
7719 /* Standard PNG background processing. */
7724 input_sample
= input_sample
* alpha
+ background
* (1-alpha
);
7725 if (compose
!= NULL
)
7730 input_sample
= background
;
7735 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
7736 case ALPHA_MODE_OFFSET
+ PNG_ALPHA_STANDARD
:
7737 case ALPHA_MODE_OFFSET
+ PNG_ALPHA_BROKEN
:
7738 /* The components are premultiplied in either case and the output is
7739 * gamma encoded (to get standard Porter-Duff we expect the output
7740 * gamma to be set to 1.0!)
7742 case ALPHA_MODE_OFFSET
+ PNG_ALPHA_OPTIMIZED
:
7743 /* The optimization is that the partial-alpha entries are linear
7744 * while the opaque pixels are gamma encoded, but this only affects the
7751 input_sample
*= alpha
;
7752 if (compose
!= NULL
)
7763 /* Standard cases where no compositing is done (so the component
7764 * value is already correct.)
7772 return input_sample
;
7775 /* This API returns the encoded *input* component, in the range 0..1 */
7777 gamma_component_validate(PNG_CONST
char *name
, PNG_CONST validate_info
*vi
,
7778 PNG_CONST
unsigned int id
, PNG_CONST
unsigned int od
,
7779 PNG_CONST
double alpha
/* <0 for the alpha channel itself */,
7780 PNG_CONST
double background
/* component background value */)
7782 PNG_CONST
unsigned int isbit
= id
>> vi
->isbit_shift
;
7783 PNG_CONST
unsigned int sbit_max
= vi
->sbit_max
;
7784 PNG_CONST
unsigned int outmax
= vi
->outmax
;
7785 PNG_CONST
int do_background
= vi
->do_background
;
7789 /* First check on the 'perfect' result obtained from the digitized input
7790 * value, id, and compare this against the actual digitized result, 'od'.
7791 * 'i' is the input result in the range 0..1:
7793 i
= isbit
; i
/= sbit_max
;
7795 /* Check for the fast route: if we don't do any background composition or if
7796 * this is the alpha channel ('alpha' < 0) or if the pixel is opaque then
7797 * just use the gamma_correction field to correct to the final output gamma.
7799 if (alpha
== 1 /* opaque pixel component */ || !do_background
7800 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
7801 || do_background
== ALPHA_MODE_OFFSET
+ PNG_ALPHA_PNG
7803 || (alpha
< 0 /* alpha channel */
7804 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
7805 && do_background
!= ALPHA_MODE_OFFSET
+ PNG_ALPHA_BROKEN
7809 /* Then get the gamma corrected version of 'i' and compare to 'od', any
7810 * error less than .5 is insignificant - just quantization of the output
7811 * value to the nearest digital value (nevertheless the error is still
7812 * recorded - it's interesting ;-)
7814 double encoded_sample
= i
;
7815 double encoded_error
;
7817 /* alpha less than 0 indicates the alpha channel, which is always linear
7819 if (alpha
>= 0 && vi
->gamma_correction
> 0)
7820 encoded_sample
= pow(encoded_sample
, vi
->gamma_correction
);
7821 encoded_sample
*= outmax
;
7823 encoded_error
= fabs(od
-encoded_sample
);
7825 if (encoded_error
> vi
->dp
->maxerrout
)
7826 vi
->dp
->maxerrout
= encoded_error
;
7828 if (encoded_error
< vi
->maxout_total
&& encoded_error
< vi
->outlog
)
7832 /* The slow route - attempt to do linear calculations. */
7833 /* There may be an error, or background processing is required, so calculate
7834 * the actual sample values - unencoded light intensity values. Note that in
7835 * practice these are not completely unencoded because they include a
7836 * 'viewing correction' to decrease or (normally) increase the perceptual
7837 * contrast of the image. There's nothing we can do about this - we don't
7838 * know what it is - so assume the unencoded value is perceptually linear.
7841 double input_sample
= i
; /* In range 0..1 */
7842 double output
, error
, encoded_sample
, encoded_error
;
7843 double es_lo
, es_hi
;
7844 int compose
= 0; /* Set to one if composition done */
7845 int output_is_encoded
; /* Set if encoded to screen gamma */
7846 int log_max_error
= 1; /* Check maximum error values */
7847 png_const_charp pass
= 0; /* Reason test passes (or 0 for fail) */
7849 /* Convert to linear light (with the above caveat.) The alpha channel is
7856 if (vi
->file_inverse
> 0)
7857 input_sample
= pow(input_sample
, vi
->file_inverse
);
7859 /* Handle the compose processing: */
7861 input_sample
= gamma_component_compose(do_background
, input_sample
,
7862 alpha
, background
, &tcompose
);
7868 /* And similarly for the output value, but we need to check the background
7869 * handling to linearize it correctly.
7874 output_is_encoded
= vi
->screen_gamma
> 0;
7876 if (alpha
< 0) /* The alpha channel */
7878 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
7879 if (do_background
!= ALPHA_MODE_OFFSET
+ PNG_ALPHA_BROKEN
)
7882 /* In all other cases the output alpha channel is linear already,
7883 * don't log errors here, they are much larger in linear data.
7885 output_is_encoded
= 0;
7890 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
7891 else /* A component */
7893 if (do_background
== ALPHA_MODE_OFFSET
+ PNG_ALPHA_OPTIMIZED
&&
7894 alpha
< 1) /* the optimized case - linear output */
7896 if (alpha
> 0) log_max_error
= 0;
7897 output_is_encoded
= 0;
7902 if (output_is_encoded
)
7903 output
= pow(output
, vi
->screen_gamma
);
7905 /* Calculate (or recalculate) the encoded_sample value and repeat the
7906 * check above (unnecessary if we took the fast route, but harmless.)
7908 encoded_sample
= input_sample
;
7909 if (output_is_encoded
)
7910 encoded_sample
= pow(encoded_sample
, vi
->screen_inverse
);
7911 encoded_sample
*= outmax
;
7913 encoded_error
= fabs(od
-encoded_sample
);
7915 /* Don't log errors in the alpha channel, or the 'optimized' case,
7916 * neither are significant to the overall perception.
7918 if (log_max_error
&& encoded_error
> vi
->dp
->maxerrout
)
7919 vi
->dp
->maxerrout
= encoded_error
;
7921 if (encoded_error
< vi
->maxout_total
)
7923 if (encoded_error
< vi
->outlog
)
7926 /* Test passed but error is bigger than the log limit, record why the
7929 pass
= "less than maxout:\n";
7932 /* i: the original input value in the range 0..1
7934 * pngvalid calculations:
7935 * input_sample: linear result; i linearized and composed, range 0..1
7936 * encoded_sample: encoded result; input_sample scaled to ouput bit depth
7938 * libpng calculations:
7939 * output: linear result; od scaled to 0..1 and linearized
7940 * od: encoded result from libpng
7943 /* Now we have the numbers for real errors, both absolute values as as a
7944 * percentage of the correct value (output):
7946 error
= fabs(input_sample
-output
);
7948 if (log_max_error
&& error
> vi
->dp
->maxerrabs
)
7949 vi
->dp
->maxerrabs
= error
;
7951 /* The following is an attempt to ignore the tendency of quantization to
7952 * dominate the percentage errors for lower result values:
7954 if (log_max_error
&& input_sample
> .5)
7956 double percentage_error
= error
/input_sample
;
7957 if (percentage_error
> vi
->dp
->maxerrpc
)
7958 vi
->dp
->maxerrpc
= percentage_error
;
7961 /* Now calculate the digitization limits for 'encoded_sample' using the
7962 * 'max' values. Note that maxout is in the encoded space but maxpc and
7963 * maxabs are in linear light space.
7965 * First find the maximum error in linear light space, range 0..1:
7968 double tmp
= input_sample
* vi
->maxpc
;
7969 if (tmp
< vi
->maxabs
) tmp
= vi
->maxabs
;
7970 /* If 'compose' is true the composition was done in linear space using
7971 * integer arithmetic. This introduces an extra error of +/- 0.5 (at
7972 * least) in the integer space used. 'maxcalc' records this, taking
7973 * into account the possibility that even for 16 bit output 8 bit space
7974 * may have been used.
7976 if (compose
&& tmp
< vi
->maxcalc
) tmp
= vi
->maxcalc
;
7978 /* The 'maxout' value refers to the encoded result, to compare with
7979 * this encode input_sample adjusted by the maximum error (tmp) above.
7981 es_lo
= encoded_sample
- vi
->maxout
;
7983 if (es_lo
> 0 && input_sample
-tmp
> 0)
7985 double low_value
= input_sample
-tmp
;
7986 if (output_is_encoded
)
7987 low_value
= pow(low_value
, vi
->screen_inverse
);
7988 low_value
*= outmax
;
7989 if (low_value
< es_lo
) es_lo
= low_value
;
7991 /* Quantize this appropriately: */
7992 es_lo
= ceil(es_lo
/ vi
->outquant
- .5) * vi
->outquant
;
7998 es_hi
= encoded_sample
+ vi
->maxout
;
8000 if (es_hi
< outmax
&& input_sample
+tmp
< 1)
8002 double high_value
= input_sample
+tmp
;
8003 if (output_is_encoded
)
8004 high_value
= pow(high_value
, vi
->screen_inverse
);
8005 high_value
*= outmax
;
8006 if (high_value
> es_hi
) es_hi
= high_value
;
8008 es_hi
= floor(es_hi
/ vi
->outquant
+ .5) * vi
->outquant
;
8015 /* The primary test is that the final encoded value returned by the
8016 * library should be between the two limits (inclusive) that were
8019 if (od
>= es_lo
&& od
<= es_hi
)
8021 /* The value passes, but we may need to log the information anyway. */
8022 if (encoded_error
< vi
->outlog
)
8026 pass
= "within digitization limits:\n";
8030 /* There has been an error in processing, or we need to log this
8033 double is_lo
, is_hi
;
8035 /* pass is set at this point if either of the tests above would have
8036 * passed. Don't do these additional tests here - just log the
8037 * original [es_lo..es_hi] values.
8039 if (pass
== 0 && vi
->use_input_precision
)
8041 /* Ok, something is wrong - this actually happens in current libpng
8042 * 16-to-8 processing. Assume that the input value (id, adjusted
8043 * for sbit) can be anywhere between value-.5 and value+.5 - quite a
8044 * large range if sbit is low.
8046 double tmp
= (isbit
- .5)/sbit_max
;
8051 else if (alpha
>= 0 && vi
->file_inverse
> 0 && tmp
< 1)
8052 tmp
= pow(tmp
, vi
->file_inverse
);
8054 tmp
= gamma_component_compose(do_background
, tmp
, alpha
, background
,
8057 if (output_is_encoded
&& tmp
> 0 && tmp
< 1)
8058 tmp
= pow(tmp
, vi
->screen_inverse
);
8060 is_lo
= ceil(outmax
* tmp
- vi
->maxout_total
);
8065 tmp
= (isbit
+ .5)/sbit_max
;
8070 else if (alpha
>= 0 && vi
->file_inverse
> 0 && tmp
< 1)
8071 tmp
= pow(tmp
, vi
->file_inverse
);
8073 tmp
= gamma_component_compose(do_background
, tmp
, alpha
, background
,
8076 if (output_is_encoded
&& tmp
> 0 && tmp
< 1)
8077 tmp
= pow(tmp
, vi
->screen_inverse
);
8079 is_hi
= floor(outmax
* tmp
+ vi
->maxout_total
);
8084 if (!(od
< is_lo
|| od
> is_hi
))
8086 if (encoded_error
< vi
->outlog
)
8089 pass
= "within input precision limits:\n";
8092 /* One last chance. If this is an alpha channel and the 16to8
8093 * option has been used and 'inaccurate' scaling is used then the
8094 * bit reduction is obtained by simply using the top 8 bits of the
8097 * This is only done for older libpng versions when the 'inaccurate'
8098 * (chop) method of scaling was used.
8100 # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
8101 # if PNG_LIBPNG_VER < 10504
8102 /* This may be required for other components in the future,
8103 * but at present the presence of gamma correction effectively
8104 * prevents the errors in the component scaling (I don't quite
8105 * understand why, but since it's better this way I care not
8106 * to ask, JB 20110419.)
8108 if (pass
== 0 && alpha
< 0 && vi
->scale16
&& vi
->sbit
> 8 &&
8109 vi
->sbit
+ vi
->isbit_shift
== 16)
8111 tmp
= ((id
>> 8) - .5)/255;
8115 is_lo
= ceil(outmax
* tmp
- vi
->maxout_total
);
8116 if (is_lo
< 0) is_lo
= 0;
8122 tmp
= ((id
>> 8) + .5)/255;
8126 is_hi
= floor(outmax
* tmp
+ vi
->maxout_total
);
8127 if (is_hi
> outmax
) is_hi
= outmax
;
8133 if (!(od
< is_lo
|| od
> is_hi
))
8135 if (encoded_error
< vi
->outlog
)
8138 pass
= "within 8 bit limits:\n";
8144 else /* !use_input_precision */
8145 is_lo
= es_lo
, is_hi
= es_hi
;
8147 /* Attempt to output a meaningful error/warning message: the message
8148 * output depends on the background/composite operation being performed
8149 * because this changes what parameters were actually used above.
8153 /* Need either 1/255 or 1/65535 precision here; 3 or 6 decimal
8154 * places. Just use outmax to work out which.
8156 int precision
= (outmax
>= 1000 ? 6 : 3);
8157 int use_input
=1, use_background
=0, do_compose
=0;
8161 pos
= safecat(msg
, sizeof msg
, pos
, "\n\t");
8163 /* Set up the various flags, the output_is_encoded flag above
8164 * is also used below. do_compose is just a double check.
8166 switch (do_background
)
8168 # ifdef PNG_READ_BACKGROUND_SUPPORTED
8169 case PNG_BACKGROUND_GAMMA_SCREEN
:
8170 case PNG_BACKGROUND_GAMMA_FILE
:
8171 case PNG_BACKGROUND_GAMMA_UNIQUE
:
8172 use_background
= (alpha
>= 0 && alpha
< 1);
8175 # ifdef PNG_READ_ALPHA_MODE_SUPPORTED
8176 case ALPHA_MODE_OFFSET
+ PNG_ALPHA_STANDARD
:
8177 case ALPHA_MODE_OFFSET
+ PNG_ALPHA_BROKEN
:
8178 case ALPHA_MODE_OFFSET
+ PNG_ALPHA_OPTIMIZED
:
8179 # endif /* ALPHA_MODE_SUPPORTED */
8180 do_compose
= (alpha
> 0 && alpha
< 1);
8181 use_input
= (alpha
!= 0);
8188 /* Check the 'compose' flag */
8189 if (compose
!= do_compose
)
8190 png_error(vi
->pp
, "internal error (compose)");
8192 /* 'name' is the component name */
8193 pos
= safecat(msg
, sizeof msg
, pos
, name
);
8194 pos
= safecat(msg
, sizeof msg
, pos
, "(");
8195 pos
= safecatn(msg
, sizeof msg
, pos
, id
);
8196 if (use_input
|| pass
!= 0/*logging*/)
8200 /* sBIT has reduced the precision of the input: */
8201 pos
= safecat(msg
, sizeof msg
, pos
, ", sbit(");
8202 pos
= safecatn(msg
, sizeof msg
, pos
, vi
->sbit
);
8203 pos
= safecat(msg
, sizeof msg
, pos
, "): ");
8204 pos
= safecatn(msg
, sizeof msg
, pos
, isbit
);
8206 pos
= safecat(msg
, sizeof msg
, pos
, "/");
8207 /* The output is either "id/max" or "id sbit(sbit): isbit/max" */
8208 pos
= safecatn(msg
, sizeof msg
, pos
, vi
->sbit_max
);
8210 pos
= safecat(msg
, sizeof msg
, pos
, ")");
8212 /* A component may have been multiplied (in linear space) by the
8213 * alpha value, 'compose' says whether this is relevant.
8215 if (compose
|| pass
!= 0)
8217 /* If any form of composition is being done report our
8218 * calculated linear value here (the code above doesn't record
8219 * the input value before composition is performed, so what
8220 * gets reported is the value after composition.)
8222 if (use_input
|| pass
!= 0)
8224 if (vi
->file_inverse
> 0)
8226 pos
= safecat(msg
, sizeof msg
, pos
, "^");
8227 pos
= safecatd(msg
, sizeof msg
, pos
, vi
->file_inverse
, 2);
8231 pos
= safecat(msg
, sizeof msg
, pos
, "[linear]");
8233 pos
= safecat(msg
, sizeof msg
, pos
, "*(alpha)");
8234 pos
= safecatd(msg
, sizeof msg
, pos
, alpha
, precision
);
8237 /* Now record the *linear* background value if it was used
8238 * (this function is not passed the original, non-linear,
8239 * value but it is contained in the test name.)
8243 pos
= safecat(msg
, sizeof msg
, pos
, use_input
? "+" : " ");
8244 pos
= safecat(msg
, sizeof msg
, pos
, "(background)");
8245 pos
= safecatd(msg
, sizeof msg
, pos
, background
, precision
);
8246 pos
= safecat(msg
, sizeof msg
, pos
, "*");
8247 pos
= safecatd(msg
, sizeof msg
, pos
, 1-alpha
, precision
);
8251 /* Report the calculated value (input_sample) and the linearized
8252 * libpng value (output) unless this is just a component gamma
8255 if (compose
|| alpha
< 0 || pass
!= 0)
8257 pos
= safecat(msg
, sizeof msg
, pos
,
8258 pass
!= 0 ? " =\n\t" : " = ");
8259 pos
= safecatd(msg
, sizeof msg
, pos
, input_sample
, precision
);
8260 pos
= safecat(msg
, sizeof msg
, pos
, " (libpng: ");
8261 pos
= safecatd(msg
, sizeof msg
, pos
, output
, precision
);
8262 pos
= safecat(msg
, sizeof msg
, pos
, ")");
8264 /* Finally report the output gamma encoding, if any. */
8265 if (output_is_encoded
)
8267 pos
= safecat(msg
, sizeof msg
, pos
, " ^");
8268 pos
= safecatd(msg
, sizeof msg
, pos
, vi
->screen_inverse
, 2);
8269 pos
= safecat(msg
, sizeof msg
, pos
, "(to screen) =");
8273 pos
= safecat(msg
, sizeof msg
, pos
, " [screen is linear] =");
8276 if ((!compose
&& alpha
>= 0) || pass
!= 0)
8278 if (pass
!= 0) /* logging */
8279 pos
= safecat(msg
, sizeof msg
, pos
, "\n\t[overall:");
8281 /* This is the non-composition case, the internal linear
8282 * values are irrelevant (though the log below will reveal
8283 * them.) Output a much shorter warning/error message and report
8284 * the overall gamma correction.
8286 if (vi
->gamma_correction
> 0)
8288 pos
= safecat(msg
, sizeof msg
, pos
, " ^");
8289 pos
= safecatd(msg
, sizeof msg
, pos
, vi
->gamma_correction
, 2);
8290 pos
= safecat(msg
, sizeof msg
, pos
, "(gamma correction) =");
8294 pos
= safecat(msg
, sizeof msg
, pos
,
8295 " [no gamma correction] =");
8298 pos
= safecat(msg
, sizeof msg
, pos
, "]");
8301 /* This is our calculated encoded_sample which should (but does
8304 pos
= safecat(msg
, sizeof msg
, pos
, pass
!= 0 ? "\n\t" : " ");
8305 pos
= safecatd(msg
, sizeof msg
, pos
, is_lo
, 1);
8306 pos
= safecat(msg
, sizeof msg
, pos
, " < ");
8307 pos
= safecatd(msg
, sizeof msg
, pos
, encoded_sample
, 1);
8308 pos
= safecat(msg
, sizeof msg
, pos
, " (libpng: ");
8309 pos
= safecatn(msg
, sizeof msg
, pos
, od
);
8310 pos
= safecat(msg
, sizeof msg
, pos
, ")");
8311 pos
= safecat(msg
, sizeof msg
, pos
, "/");
8312 pos
= safecatn(msg
, sizeof msg
, pos
, outmax
);
8313 pos
= safecat(msg
, sizeof msg
, pos
, " < ");
8314 pos
= safecatd(msg
, sizeof msg
, pos
, is_hi
, 1);
8316 if (pass
== 0) /* The error condition */
8318 # ifdef PNG_WARNINGS_SUPPORTED
8319 png_warning(vi
->pp
, msg
);
8321 store_warning(vi
->pp
, msg
);
8325 else /* logging this value */
8326 store_verbose(&vi
->dp
->pm
->this, vi
->pp
, pass
, msg
);
8335 gamma_image_validate(gamma_display
*dp
, png_const_structp pp
,
8338 /* Get some constants derived from the input and output file formats: */
8339 PNG_CONST png_store
* PNG_CONST ps
= dp
->this.ps
;
8340 PNG_CONST png_byte in_ct
= dp
->this.colour_type
;
8341 PNG_CONST png_byte in_bd
= dp
->this.bit_depth
;
8342 PNG_CONST png_uint_32 w
= dp
->this.w
;
8343 PNG_CONST png_uint_32 h
= dp
->this.h
;
8344 PNG_CONST
size_t cbRow
= dp
->this.cbRow
;
8345 PNG_CONST png_byte out_ct
= png_get_color_type(pp
, pi
);
8346 PNG_CONST png_byte out_bd
= png_get_bit_depth(pp
, pi
);
8348 /* There are three sources of error, firstly the quantization in the
8349 * file encoding, determined by sbit and/or the file depth, secondly
8350 * the output (screen) gamma and thirdly the output file encoding.
8352 * Since this API receives the screen and file gamma in double
8353 * precision it is possible to calculate an exact answer given an input
8354 * pixel value. Therefore we assume that the *input* value is exact -
8355 * sample/maxsample - calculate the corresponding gamma corrected
8356 * output to the limits of double precision arithmetic and compare with
8357 * what libpng returns.
8359 * Since the library must quantize the output to 8 or 16 bits there is
8360 * a fundamental limit on the accuracy of the output of +/-.5 - this
8361 * quantization limit is included in addition to the other limits
8362 * specified by the paramaters to the API. (Effectively, add .5
8365 * The behavior of the 'sbit' paramter is defined by section 12.5
8366 * (sample depth scaling) of the PNG spec. That section forces the
8367 * decoder to assume that the PNG values have been scaled if sBIT is
8370 * png-sample = floor( input-sample * (max-out/max-in) + .5);
8372 * This means that only a subset of the possible PNG values should
8373 * appear in the input. However, the spec allows the encoder to use a
8374 * variety of approximations to the above and doesn't require any
8375 * restriction of the values produced.
8377 * Nevertheless the spec requires that the upper 'sBIT' bits of the
8378 * value stored in a PNG file be the original sample bits.
8379 * Consequently the code below simply scales the top sbit bits by
8380 * (1<<sbit)-1 to obtain an original sample value.
8382 * Because there is limited precision in the input it is arguable that
8383 * an acceptable result is any valid result from input-.5 to input+.5.
8384 * The basic tests below do not do this, however if 'use_input_precision'
8385 * is set a subsequent test is performed below.
8387 PNG_CONST
unsigned int samples_per_pixel
= (out_ct
& 2U) ? 3U : 1U;
8390 PNG_CONST store_palette_entry
*in_palette
= dp
->this.palette
;
8391 PNG_CONST
int in_is_transparent
= dp
->this.is_transparent
;
8392 int out_npalette
= -1;
8393 int out_is_transparent
= 0; /* Just refers to the palette case */
8394 store_palette out_palette
;
8397 /* Check for row overwrite errors */
8398 store_image_check(dp
->this.ps
, pp
, 0);
8400 /* Supply the input and output sample depths here - 8 for an indexed image,
8401 * otherwise the bit depth.
8403 init_validate_info(&vi
, dp
, pp
, in_ct
==3?8:in_bd
, out_ct
==3?8:out_bd
);
8405 processing
= (vi
.gamma_correction
> 0 && !dp
->threshold_test
)
8406 || in_bd
!= out_bd
|| in_ct
!= out_ct
|| vi
.do_background
;
8408 /* TODO: FIX THIS: MAJOR BUG! If the transformations all happen inside
8409 * the palette there is no way of finding out, because libpng fails to
8410 * update the palette on png_read_update_info. Indeed, libpng doesn't
8411 * even do the required work until much later, when it doesn't have any
8412 * info pointer. Oops. For the moment 'processing' is turned off if
8413 * out_ct is palette.
8415 if (in_ct
== 3 && out_ct
== 3)
8418 if (processing
&& out_ct
== 3)
8419 out_is_transparent
= read_palette(out_palette
, &out_npalette
, pp
, pi
);
8423 png_const_bytep pRow
= store_image_row(ps
, pp
, 0, y
);
8424 png_byte std
[STANDARD_ROWMAX
];
8426 transform_row(pp
, std
, in_ct
, in_bd
, y
);
8434 double alpha
= 1; /* serves as a flag value */
8436 /* Record the palette index for index images. */
8437 PNG_CONST
unsigned int in_index
=
8438 in_ct
== 3 ? sample(std
, 3, in_bd
, x
, 0) : 256;
8439 PNG_CONST
unsigned int out_index
=
8440 out_ct
== 3 ? sample(std
, 3, out_bd
, x
, 0) : 256;
8442 /* Handle input alpha - png_set_background will cause the output
8443 * alpha to disappear so there is nothing to check.
8445 if ((in_ct
& PNG_COLOR_MASK_ALPHA
) != 0 || (in_ct
== 3 &&
8448 PNG_CONST
unsigned int input_alpha
= in_ct
== 3 ?
8449 dp
->this.palette
[in_index
].alpha
:
8450 sample(std
, in_ct
, in_bd
, x
, samples_per_pixel
);
8452 unsigned int output_alpha
= 65536 /* as a flag value */;
8456 if (out_is_transparent
)
8457 output_alpha
= out_palette
[out_index
].alpha
;
8460 else if ((out_ct
& PNG_COLOR_MASK_ALPHA
) != 0)
8461 output_alpha
= sample(pRow
, out_ct
, out_bd
, x
,
8464 if (output_alpha
!= 65536)
8465 alpha
= gamma_component_validate("alpha", &vi
, input_alpha
,
8466 output_alpha
, -1/*alpha*/, 0/*background*/);
8468 else /* no alpha in output */
8470 /* This is a copy of the calculation of 'i' above in order to
8471 * have the alpha value to use in the background calculation.
8473 alpha
= input_alpha
>> vi
.isbit_shift
;
8474 alpha
/= vi
.sbit_max
;
8478 /* Handle grayscale or RGB components. */
8479 if ((in_ct
& PNG_COLOR_MASK_COLOR
) == 0) /* grayscale */
8480 (void)gamma_component_validate("gray", &vi
,
8481 sample(std
, in_ct
, in_bd
, x
, 0),
8482 sample(pRow
, out_ct
, out_bd
, x
, 0), alpha
/*component*/,
8484 else /* RGB or palette */
8486 (void)gamma_component_validate("red", &vi
,
8487 in_ct
== 3 ? in_palette
[in_index
].red
:
8488 sample(std
, in_ct
, in_bd
, x
, 0),
8489 out_ct
== 3 ? out_palette
[out_index
].red
:
8490 sample(pRow
, out_ct
, out_bd
, x
, 0),
8491 alpha
/*component*/, vi
.background_red
);
8493 (void)gamma_component_validate("green", &vi
,
8494 in_ct
== 3 ? in_palette
[in_index
].green
:
8495 sample(std
, in_ct
, in_bd
, x
, 1),
8496 out_ct
== 3 ? out_palette
[out_index
].green
:
8497 sample(pRow
, out_ct
, out_bd
, x
, 1),
8498 alpha
/*component*/, vi
.background_green
);
8500 (void)gamma_component_validate("blue", &vi
,
8501 in_ct
== 3 ? in_palette
[in_index
].blue
:
8502 sample(std
, in_ct
, in_bd
, x
, 2),
8503 out_ct
== 3 ? out_palette
[out_index
].blue
:
8504 sample(pRow
, out_ct
, out_bd
, x
, 2),
8505 alpha
/*component*/, vi
.background_blue
);
8510 else if (memcmp(std
, pRow
, cbRow
) != 0)
8514 /* No transform is expected on the threshold tests. */
8515 sprintf(msg
, "gamma: below threshold row %lu changed",
8520 } /* row (y) loop */
8522 dp
->this.ps
->validated
= 1;
8526 gamma_end(png_structp ppIn
, png_infop pi
)
8528 png_const_structp pp
= ppIn
;
8529 gamma_display
*dp
= voidcast(gamma_display
*, png_get_progressive_ptr(pp
));
8531 if (!dp
->this.speed
)
8532 gamma_image_validate(dp
, pp
, pi
);
8534 dp
->this.ps
->validated
= 1;
8537 /* A single test run checking a gamma transformation.
8539 * maxabs: maximum absolute error as a fraction
8540 * maxout: maximum output error in the output units
8541 * maxpc: maximum percentage error (as a percentage)
8544 gamma_test(png_modifier
*pmIn
, PNG_CONST png_byte colour_typeIn
,
8545 PNG_CONST png_byte bit_depthIn
, PNG_CONST
int palette_numberIn
,
8546 PNG_CONST
int interlace_typeIn
,
8547 PNG_CONST
double file_gammaIn
, PNG_CONST
double screen_gammaIn
,
8548 PNG_CONST png_byte sbitIn
, PNG_CONST
int threshold_testIn
,
8549 PNG_CONST
char *name
,
8550 PNG_CONST
int use_input_precisionIn
, PNG_CONST
int scale16In
,
8551 PNG_CONST
int expand16In
, PNG_CONST
int do_backgroundIn
,
8552 PNG_CONST png_color_16
*bkgd_colorIn
, double bkgd_gammaIn
)
8555 context(&pmIn
->this, fault
);
8557 gamma_display_init(&d
, pmIn
, FILEID(colour_typeIn
, bit_depthIn
,
8558 palette_numberIn
, interlace_typeIn
, 0, 0, 0),
8559 file_gammaIn
, screen_gammaIn
, sbitIn
,
8560 threshold_testIn
, use_input_precisionIn
, scale16In
,
8561 expand16In
, do_backgroundIn
, bkgd_colorIn
, bkgd_gammaIn
);
8567 gama_modification gama_mod
;
8568 srgb_modification srgb_mod
;
8569 sbit_modification sbit_mod
;
8571 /* For the moment don't use the png_modifier support here. */
8572 d
.pm
->encoding_counter
= 0;
8573 modifier_set_encoding(d
.pm
); /* Just resets everything */
8574 d
.pm
->current_gamma
= d
.file_gamma
;
8576 /* Make an appropriate modifier to set the PNG file gamma to the
8577 * given gamma value and the sBIT chunk to the given precision.
8579 d
.pm
->modifications
= NULL
;
8580 gama_modification_init(&gama_mod
, d
.pm
, d
.file_gamma
);
8581 srgb_modification_init(&srgb_mod
, d
.pm
, 127 /*delete*/);
8583 sbit_modification_init(&sbit_mod
, d
.pm
, d
.sbit
);
8585 modification_reset(d
.pm
->modifications
);
8587 /* Get a png_struct for writing the image. */
8588 pp
= set_modifier_for_read(d
.pm
, &pi
, d
.this.id
, name
);
8589 standard_palette_init(&d
.this);
8591 /* Introduce the correct read function. */
8592 if (d
.pm
->this.progressive
)
8594 /* Share the row function with the standard implementation. */
8595 png_set_progressive_read_fn(pp
, &d
, gamma_info
, progressive_row
,
8598 /* Now feed data into the reader until we reach the end: */
8599 modifier_progressive_read(d
.pm
, pp
, pi
);
8603 /* modifier_read expects a png_modifier* */
8604 png_set_read_fn(pp
, d
.pm
, modifier_read
);
8606 /* Check the header values: */
8607 png_read_info(pp
, pi
);
8609 /* Process the 'info' requirements. Only one image is generated */
8610 gamma_info_imp(&d
, pp
, pi
);
8612 sequential_row(&d
.this, pp
, pi
, -1, 0);
8615 gamma_image_validate(&d
, pp
, pi
);
8617 d
.this.ps
->validated
= 1;
8620 modifier_reset(d
.pm
);
8622 if (d
.pm
->log
&& !d
.threshold_test
&& !d
.this.speed
)
8623 fprintf(stderr
, "%d bit %s %s: max error %f (%.2g, %2g%%)\n",
8624 d
.this.bit_depth
, colour_types
[d
.this.colour_type
], name
,
8625 d
.maxerrout
, d
.maxerrabs
, 100*d
.maxerrpc
);
8627 /* Log the summary values too. */
8628 if (d
.this.colour_type
== 0 || d
.this.colour_type
== 4)
8630 switch (d
.this.bit_depth
)
8636 if (d
.maxerrout
> d
.pm
->error_gray_2
)
8637 d
.pm
->error_gray_2
= d
.maxerrout
;
8642 if (d
.maxerrout
> d
.pm
->error_gray_4
)
8643 d
.pm
->error_gray_4
= d
.maxerrout
;
8648 if (d
.maxerrout
> d
.pm
->error_gray_8
)
8649 d
.pm
->error_gray_8
= d
.maxerrout
;
8654 if (d
.maxerrout
> d
.pm
->error_gray_16
)
8655 d
.pm
->error_gray_16
= d
.maxerrout
;
8660 png_error(pp
, "bad bit depth (internal: 1)");
8664 else if (d
.this.colour_type
== 2 || d
.this.colour_type
== 6)
8666 switch (d
.this.bit_depth
)
8670 if (d
.maxerrout
> d
.pm
->error_color_8
)
8671 d
.pm
->error_color_8
= d
.maxerrout
;
8677 if (d
.maxerrout
> d
.pm
->error_color_16
)
8678 d
.pm
->error_color_16
= d
.maxerrout
;
8683 png_error(pp
, "bad bit depth (internal: 2)");
8687 else if (d
.this.colour_type
== 3)
8689 if (d
.maxerrout
> d
.pm
->error_indexed
)
8690 d
.pm
->error_indexed
= d
.maxerrout
;
8695 modifier_reset((png_modifier
*)fault
);
8698 static void gamma_threshold_test(png_modifier
*pm
, png_byte colour_type
,
8699 png_byte bit_depth
, int interlace_type
, double file_gamma
,
8700 double screen_gamma
)
8704 pos
= safecat(name
, sizeof name
, pos
, "threshold ");
8705 pos
= safecatd(name
, sizeof name
, pos
, file_gamma
, 3);
8706 pos
= safecat(name
, sizeof name
, pos
, "/");
8707 pos
= safecatd(name
, sizeof name
, pos
, screen_gamma
, 3);
8709 (void)gamma_test(pm
, colour_type
, bit_depth
, 0/*palette*/, interlace_type
,
8710 file_gamma
, screen_gamma
, 0/*sBIT*/, 1/*threshold test*/, name
,
8711 0 /*no input precision*/,
8712 0 /*no scale16*/, 0 /*no expand16*/, 0 /*no background*/, 0 /*hence*/,
8713 0 /*no background gamma*/);
8717 perform_gamma_threshold_tests(png_modifier
*pm
)
8719 png_byte colour_type
= 0;
8720 png_byte bit_depth
= 0;
8721 unsigned int palette_number
= 0;
8723 /* Don't test more than one instance of each palette - it's pointless, in
8724 * fact this test is somewhat excessive since libpng doesn't make this
8725 * decision based on colour type or bit depth!
8727 while (next_format(&colour_type
, &bit_depth
, &palette_number
))
8728 if (palette_number
== 0)
8730 double test_gamma
= 1.0;
8731 while (test_gamma
>= .4)
8733 /* There's little point testing the interlacing vs non-interlacing,
8734 * but this can be set from the command line.
8736 gamma_threshold_test(pm
, colour_type
, bit_depth
, pm
->interlace_type
,
8737 test_gamma
, 1/test_gamma
);
8741 /* And a special test for sRGB */
8742 gamma_threshold_test(pm
, colour_type
, bit_depth
, pm
->interlace_type
,
8750 static void gamma_transform_test(png_modifier
*pm
,
8751 PNG_CONST png_byte colour_type
, PNG_CONST png_byte bit_depth
,
8752 PNG_CONST
int palette_number
,
8753 PNG_CONST
int interlace_type
, PNG_CONST
double file_gamma
,
8754 PNG_CONST
double screen_gamma
, PNG_CONST png_byte sbit
,
8755 PNG_CONST
int use_input_precision
, PNG_CONST
int scale16
)
8760 if (sbit
!= bit_depth
&& sbit
!= 0)
8762 pos
= safecat(name
, sizeof name
, pos
, "sbit(");
8763 pos
= safecatn(name
, sizeof name
, pos
, sbit
);
8764 pos
= safecat(name
, sizeof name
, pos
, ") ");
8768 pos
= safecat(name
, sizeof name
, pos
, "gamma ");
8771 pos
= safecat(name
, sizeof name
, pos
, "16to8 ");
8773 pos
= safecatd(name
, sizeof name
, pos
, file_gamma
, 3);
8774 pos
= safecat(name
, sizeof name
, pos
, "->");
8775 pos
= safecatd(name
, sizeof name
, pos
, screen_gamma
, 3);
8777 gamma_test(pm
, colour_type
, bit_depth
, palette_number
, interlace_type
,
8778 file_gamma
, screen_gamma
, sbit
, 0, name
, use_input_precision
,
8779 scale16
, pm
->test_gamma_expand16
, 0 , 0, 0);
8782 static void perform_gamma_transform_tests(png_modifier
*pm
)
8784 png_byte colour_type
= 0;
8785 png_byte bit_depth
= 0;
8786 unsigned int palette_number
= 0;
8788 while (next_format(&colour_type
, &bit_depth
, &palette_number
))
8792 for (i
=0; i
<pm
->ngamma_tests
; ++i
) for (j
=0; j
<pm
->ngamma_tests
; ++j
)
8795 gamma_transform_test(pm
, colour_type
, bit_depth
, palette_number
,
8796 pm
->interlace_type
, 1/pm
->gammas
[i
], pm
->gammas
[j
], 0/*sBIT*/,
8797 pm
->use_input_precision
, 0 /*do not scale16*/);
8805 static void perform_gamma_sbit_tests(png_modifier
*pm
)
8809 /* The only interesting cases are colour and grayscale, alpha is ignored here
8810 * for overall speed. Only bit depths where sbit is less than the bit depth
8813 for (sbit
=pm
->sbitlow
; sbit
<(1<<READ_BDHI
); ++sbit
)
8815 png_byte colour_type
= 0, bit_depth
= 0;
8816 unsigned int npalette
= 0;
8818 while (next_format(&colour_type
, &bit_depth
, &npalette
))
8819 if ((colour_type
& PNG_COLOR_MASK_ALPHA
) == 0 &&
8820 ((colour_type
== 3 && sbit
< 8) ||
8821 (colour_type
!= 3 && sbit
< bit_depth
)))
8825 for (i
=0; i
<pm
->ngamma_tests
; ++i
)
8829 for (j
=0; j
<pm
->ngamma_tests
; ++j
) if (i
!= j
)
8831 gamma_transform_test(pm
, colour_type
, bit_depth
, npalette
,
8832 pm
->interlace_type
, 1/pm
->gammas
[i
], pm
->gammas
[j
],
8833 sbit
, pm
->use_input_precision_sbit
, 0 /*scale16*/);
8843 /* Note that this requires a 16 bit source image but produces 8 bit output, so
8844 * we only need the 16bit write support, but the 16 bit images are only
8845 * generated if DO_16BIT is defined.
8848 static void perform_gamma_scale16_tests(png_modifier
*pm
)
8850 # ifndef PNG_MAX_GAMMA_8
8851 # define PNG_MAX_GAMMA_8 11
8853 /* Include the alpha cases here. Note that sbit matches the internal value
8854 * used by the library - otherwise we will get spurious errors from the
8855 * internal sbit style approximation.
8857 * The threshold test is here because otherwise the 16 to 8 conversion will
8858 * proceed *without* gamma correction, and the tests above will fail (but not
8859 * by much) - this could be fixed, it only appears with the -g option.
8862 for (i
=0; i
<pm
->ngamma_tests
; ++i
)
8864 for (j
=0; j
<pm
->ngamma_tests
; ++j
)
8867 fabs(pm
->gammas
[j
]/pm
->gammas
[i
]-1) >= PNG_GAMMA_THRESHOLD
)
8869 gamma_transform_test(pm
, 0, 16, 0, pm
->interlace_type
,
8870 1/pm
->gammas
[i
], pm
->gammas
[j
], PNG_MAX_GAMMA_8
,
8871 pm
->use_input_precision_16to8
, 1 /*scale16*/);
8876 gamma_transform_test(pm
, 2, 16, 0, pm
->interlace_type
,
8877 1/pm
->gammas
[i
], pm
->gammas
[j
], PNG_MAX_GAMMA_8
,
8878 pm
->use_input_precision_16to8
, 1 /*scale16*/);
8883 gamma_transform_test(pm
, 4, 16, 0, pm
->interlace_type
,
8884 1/pm
->gammas
[i
], pm
->gammas
[j
], PNG_MAX_GAMMA_8
,
8885 pm
->use_input_precision_16to8
, 1 /*scale16*/);
8890 gamma_transform_test(pm
, 6, 16, 0, pm
->interlace_type
,
8891 1/pm
->gammas
[i
], pm
->gammas
[j
], PNG_MAX_GAMMA_8
,
8892 pm
->use_input_precision_16to8
, 1 /*scale16*/);
8900 #endif /* 16 to 8 bit conversion */
8902 #if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\
8903 defined(PNG_READ_ALPHA_MODE_SUPPORTED)
8904 static void gamma_composition_test(png_modifier
*pm
,
8905 PNG_CONST png_byte colour_type
, PNG_CONST png_byte bit_depth
,
8906 PNG_CONST
int palette_number
,
8907 PNG_CONST
int interlace_type
, PNG_CONST
double file_gamma
,
8908 PNG_CONST
double screen_gamma
,
8909 PNG_CONST
int use_input_precision
, PNG_CONST
int do_background
,
8910 PNG_CONST
int expand_16
)
8913 png_const_charp base
;
8916 png_color_16 background
;
8918 /* Make up a name and get an appropriate background gamma value. */
8919 switch (do_background
)
8923 bg
= 4; /* should not be used */
8925 case PNG_BACKGROUND_GAMMA_SCREEN
:
8926 base
= " bckg(Screen):";
8927 bg
= 1/screen_gamma
;
8929 case PNG_BACKGROUND_GAMMA_FILE
:
8930 base
= " bckg(File):";
8933 case PNG_BACKGROUND_GAMMA_UNIQUE
:
8934 base
= " bckg(Unique):";
8935 /* This tests the handling of a unique value, the math is such that the
8936 * value tends to be <1, but is neither screen nor file (even if they
8939 bg
= (file_gamma
+ screen_gamma
) / 3;
8941 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
8942 case ALPHA_MODE_OFFSET
+ PNG_ALPHA_PNG
:
8943 base
= " alpha(PNG)";
8944 bg
= 4; /* should not be used */
8946 case ALPHA_MODE_OFFSET
+ PNG_ALPHA_STANDARD
:
8947 base
= " alpha(Porter-Duff)";
8948 bg
= 4; /* should not be used */
8950 case ALPHA_MODE_OFFSET
+ PNG_ALPHA_OPTIMIZED
:
8951 base
= " alpha(Optimized)";
8952 bg
= 4; /* should not be used */
8954 case ALPHA_MODE_OFFSET
+ PNG_ALPHA_BROKEN
:
8955 base
= " alpha(Broken)";
8956 bg
= 4; /* should not be used */
8961 /* Use random background values - the background is always presented in the
8962 * output space (8 or 16 bit components).
8964 if (expand_16
|| bit_depth
== 16)
8966 png_uint_32 r
= random_32();
8968 background
.red
= (png_uint_16
)r
;
8969 background
.green
= (png_uint_16
)(r
>> 16);
8971 background
.blue
= (png_uint_16
)r
;
8972 background
.gray
= (png_uint_16
)(r
>> 16);
8975 else /* 8 bit colors */
8977 png_uint_32 r
= random_32();
8979 background
.red
= (png_byte
)r
;
8980 background
.green
= (png_byte
)(r
>> 8);
8981 background
.blue
= (png_byte
)(r
>> 16);
8982 background
.gray
= (png_byte
)(r
>> 24);
8985 background
.index
= 193; /* rgb(193,193,193) to detect errors */
8986 if (!(colour_type
& PNG_COLOR_MASK_COLOR
))
8988 /* Grayscale input, we do not convert to RGB (TBD), so we must set the
8989 * background to gray - else libpng seems to fail.
8991 background
.red
= background
.green
= background
.blue
= background
.gray
;
8994 pos
= safecat(name
, sizeof name
, pos
, "gamma ");
8995 pos
= safecatd(name
, sizeof name
, pos
, file_gamma
, 3);
8996 pos
= safecat(name
, sizeof name
, pos
, "->");
8997 pos
= safecatd(name
, sizeof name
, pos
, screen_gamma
, 3);
8999 pos
= safecat(name
, sizeof name
, pos
, base
);
9000 if (do_background
< ALPHA_MODE_OFFSET
)
9002 /* Include the background color and gamma in the name: */
9003 pos
= safecat(name
, sizeof name
, pos
, "(");
9004 /* This assumes no expand gray->rgb - the current code won't handle that!
9006 if (colour_type
& PNG_COLOR_MASK_COLOR
)
9008 pos
= safecatn(name
, sizeof name
, pos
, background
.red
);
9009 pos
= safecat(name
, sizeof name
, pos
, ",");
9010 pos
= safecatn(name
, sizeof name
, pos
, background
.green
);
9011 pos
= safecat(name
, sizeof name
, pos
, ",");
9012 pos
= safecatn(name
, sizeof name
, pos
, background
.blue
);
9015 pos
= safecatn(name
, sizeof name
, pos
, background
.gray
);
9016 pos
= safecat(name
, sizeof name
, pos
, ")^");
9017 pos
= safecatd(name
, sizeof name
, pos
, bg
, 3);
9020 gamma_test(pm
, colour_type
, bit_depth
, palette_number
, interlace_type
,
9021 file_gamma
, screen_gamma
, 0/*sBIT*/, 0, name
, use_input_precision
,
9022 0/*strip 16*/, expand_16
, do_background
, &background
, bg
);
9027 perform_gamma_composition_tests(png_modifier
*pm
, int do_background
,
9030 png_byte colour_type
= 0;
9031 png_byte bit_depth
= 0;
9032 unsigned int palette_number
= 0;
9034 /* Skip the non-alpha cases - there is no setting of a transparency colour at
9037 while (next_format(&colour_type
, &bit_depth
, &palette_number
))
9038 if ((colour_type
& PNG_COLOR_MASK_ALPHA
) != 0)
9042 /* Don't skip the i==j case here - it's relevant. */
9043 for (i
=0; i
<pm
->ngamma_tests
; ++i
) for (j
=0; j
<pm
->ngamma_tests
; ++j
)
9045 gamma_composition_test(pm
, colour_type
, bit_depth
, palette_number
,
9046 pm
->interlace_type
, 1/pm
->gammas
[i
], pm
->gammas
[j
],
9047 pm
->use_input_precision
, do_background
, expand_16
);
9054 #endif /* READ_BACKGROUND || READ_ALPHA_MODE */
9057 init_gamma_errors(png_modifier
*pm
)
9059 pm
->error_gray_2
= pm
->error_gray_4
= pm
->error_gray_8
= 0;
9060 pm
->error_color_8
= 0;
9061 pm
->error_indexed
= 0;
9062 pm
->error_gray_16
= pm
->error_color_16
= 0;
9066 summarize_gamma_errors(png_modifier
*pm
, png_const_charp who
, int low_bit_depth
)
9069 printf("Gamma correction with %s:\n", who
);
9073 printf(" 2 bit gray: %.5f\n", pm
->error_gray_2
);
9074 printf(" 4 bit gray: %.5f\n", pm
->error_gray_4
);
9075 printf(" 8 bit gray: %.5f\n", pm
->error_gray_8
);
9076 printf(" 8 bit color: %.5f\n", pm
->error_color_8
);
9077 printf(" indexed: %.5f\n", pm
->error_indexed
);
9081 printf(" 16 bit gray: %.5f\n", pm
->error_gray_16
);
9082 printf(" 16 bit color: %.5f\n", pm
->error_color_16
);
9087 perform_gamma_test(png_modifier
*pm
, int summary
)
9089 /*TODO: remove this*/
9090 /* Save certain values for the temporary overrides below. */
9091 unsigned int calculations_use_input_precision
=
9092 pm
->calculations_use_input_precision
;
9093 # ifdef PNG_READ_BACKGROUND_SUPPORTED
9094 double maxout8
= pm
->maxout8
;
9097 /* First some arbitrary no-transform tests: */
9098 if (!pm
->this.speed
&& pm
->test_gamma_threshold
)
9100 perform_gamma_threshold_tests(pm
);
9106 /* Now some real transforms. */
9107 if (pm
->test_gamma_transform
)
9109 init_gamma_errors(pm
);
9110 /*TODO: remove this. Necessary because the current libpng
9111 * implementation works in 8 bits:
9113 if (pm
->test_gamma_expand16
)
9114 pm
->calculations_use_input_precision
= 1;
9115 perform_gamma_transform_tests(pm
);
9116 if (!calculations_use_input_precision
)
9117 pm
->calculations_use_input_precision
= 0;
9121 printf("Gamma correction error summary\n\n");
9122 printf("The printed value is the maximum error in the pixel values\n");
9123 printf("calculated by the libpng gamma correction code. The error\n");
9124 printf("is calculated as the difference between the output pixel\n");
9125 printf("value (always an integer) and the ideal value from the\n");
9126 printf("libpng specification (typically not an integer).\n\n");
9128 printf("Expect this value to be less than .5 for 8 bit formats,\n");
9129 printf("less than 1 for formats with fewer than 8 bits and a small\n");
9130 printf("number (typically less than 5) for the 16 bit formats.\n");
9131 printf("For performance reasons the value for 16 bit formats\n");
9132 printf("increases when the image file includes an sBIT chunk.\n\n");
9134 summarize_gamma_errors(pm
, 0/*who*/, 1);
9138 /* The sbit tests produce much larger errors: */
9139 if (pm
->test_gamma_sbit
)
9141 init_gamma_errors(pm
);
9142 perform_gamma_sbit_tests(pm
);
9145 summarize_gamma_errors(pm
, "sBIT", pm
->sbitlow
< 8U);
9148 #ifdef DO_16BIT /* Should be READ_16BIT_SUPPORTED */
9149 if (pm
->test_gamma_scale16
)
9151 /* The 16 to 8 bit strip operations: */
9152 init_gamma_errors(pm
);
9153 perform_gamma_scale16_tests(pm
);
9157 printf("Gamma correction with 16 to 8 bit reduction:\n");
9158 printf(" 16 bit gray: %.5f\n", pm
->error_gray_16
);
9159 printf(" 16 bit color: %.5f\n", pm
->error_color_16
);
9164 #ifdef PNG_READ_BACKGROUND_SUPPORTED
9165 if (pm
->test_gamma_background
)
9167 init_gamma_errors(pm
);
9169 /*TODO: remove this. Necessary because the current libpng
9170 * implementation works in 8 bits:
9172 if (pm
->test_gamma_expand16
)
9174 pm
->calculations_use_input_precision
= 1;
9175 pm
->maxout8
= .499; /* because the 16 bit background is smashed */
9177 perform_gamma_composition_tests(pm
, PNG_BACKGROUND_GAMMA_UNIQUE
,
9178 pm
->test_gamma_expand16
);
9179 if (!calculations_use_input_precision
)
9180 pm
->calculations_use_input_precision
= 0;
9181 pm
->maxout8
= maxout8
;
9184 summarize_gamma_errors(pm
, "background", 1);
9188 #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9189 if (pm
->test_gamma_alpha_mode
)
9193 init_gamma_errors(pm
);
9195 /*TODO: remove this. Necessary because the current libpng
9196 * implementation works in 8 bits:
9198 if (pm
->test_gamma_expand16
)
9199 pm
->calculations_use_input_precision
= 1;
9200 for (do_background
= ALPHA_MODE_OFFSET
+ PNG_ALPHA_STANDARD
;
9201 do_background
<= ALPHA_MODE_OFFSET
+ PNG_ALPHA_BROKEN
&& !fail(pm
);
9203 perform_gamma_composition_tests(pm
, do_background
,
9204 pm
->test_gamma_expand16
);
9205 if (!calculations_use_input_precision
)
9206 pm
->calculations_use_input_precision
= 0;
9209 summarize_gamma_errors(pm
, "alpha mode", 1);
9213 #endif /* PNG_READ_GAMMA_SUPPORTED */
9214 #endif /* PNG_READ_SUPPORTED */
9216 /* INTERLACE MACRO VALIDATION */
9217 /* This is copied verbatim from the specification, it is simply the pass
9218 * number in which each pixel in each 8x8 tile appears. The array must
9219 * be indexed adam7[y][x] and notice that the pass numbers are based at
9220 * 1, not 0 - the base libpng uses.
9223 png_byte adam7
[8][8] =
9225 { 1,6,4,6,2,6,4,6 },
9226 { 7,7,7,7,7,7,7,7 },
9227 { 5,6,5,6,5,6,5,6 },
9228 { 7,7,7,7,7,7,7,7 },
9229 { 3,6,4,6,3,6,4,6 },
9230 { 7,7,7,7,7,7,7,7 },
9231 { 5,6,5,6,5,6,5,6 },
9235 /* This routine validates all the interlace support macros in png.h for
9236 * a variety of valid PNG widths and heights. It uses a number of similarly
9237 * named internal routines that feed off the above array.
9240 png_pass_start_row(int pass
)
9244 for (y
=0; y
<8; ++y
) for (x
=0; x
<8; ++x
) if (adam7
[y
][x
] == pass
)
9250 png_pass_start_col(int pass
)
9254 for (x
=0; x
<8; ++x
) for (y
=0; y
<8; ++y
) if (adam7
[y
][x
] == pass
)
9260 png_pass_row_shift(int pass
)
9262 int x
, y
, base
=(-1), inc
=8;
9264 for (y
=0; y
<8; ++y
) for (x
=0; x
<8; ++x
) if (adam7
[y
][x
] == pass
)
9270 else if (inc
== y
-base
)
9273 inc
= y
-base
, base
=y
;
9274 else if (inc
!= y
-base
)
9275 return 0xff; /* error - more than one 'inc' value! */
9278 if (base
== (-1)) return 0xfe; /* error - no row in pass! */
9280 /* The shift is always 1, 2 or 3 - no pass has all the rows! */
9289 /* error - unrecognized 'inc' */
9290 return (inc
<< 8) + 0xfd;
9294 png_pass_col_shift(int pass
)
9296 int x
, y
, base
=(-1), inc
=8;
9298 for (x
=0; x
<8; ++x
) for (y
=0; y
<8; ++y
) if (adam7
[y
][x
] == pass
)
9304 else if (inc
== x
-base
)
9307 inc
= x
-base
, base
=x
;
9308 else if (inc
!= x
-base
)
9309 return 0xff; /* error - more than one 'inc' value! */
9312 if (base
== (-1)) return 0xfe; /* error - no row in pass! */
9314 /* The shift is always 1, 2 or 3 - no pass has all the rows! */
9317 case 1: return 0; /* pass 7 has all the columns */
9324 /* error - unrecognized 'inc' */
9325 return (inc
<< 8) + 0xfd;
9329 png_row_from_pass_row(png_uint_32 yIn
, int pass
)
9331 /* By examination of the array: */
9334 case 0: return yIn
* 8;
9335 case 1: return yIn
* 8;
9336 case 2: return yIn
* 8 + 4;
9337 case 3: return yIn
* 4;
9338 case 4: return yIn
* 4 + 2;
9339 case 5: return yIn
* 2;
9340 case 6: return yIn
* 2 + 1;
9344 return 0xff; /* bad pass number */
9348 png_col_from_pass_col(png_uint_32 xIn
, int pass
)
9350 /* By examination of the array: */
9353 case 0: return xIn
* 8;
9354 case 1: return xIn
* 8 + 4;
9355 case 2: return xIn
* 4;
9356 case 3: return xIn
* 4 + 2;
9357 case 4: return xIn
* 2;
9358 case 5: return xIn
* 2 + 1;
9363 return 0xff; /* bad pass number */
9367 png_row_in_interlace_pass(png_uint_32 y
, int pass
)
9369 /* Is row 'y' in pass 'pass'? */
9373 for (x
=0; x
<8; ++x
) if (adam7
[y
][x
] == pass
)
9380 png_col_in_interlace_pass(png_uint_32 x
, int pass
)
9382 /* Is column 'x' in pass 'pass'? */
9386 for (y
=0; y
<8; ++y
) if (adam7
[y
][x
] == pass
)
9393 png_pass_rows(png_uint_32 height
, int pass
)
9395 png_uint_32 tiles
= height
>>3;
9396 png_uint_32 rows
= 0;
9401 for (y
=0; y
<8; ++y
) for (x
=0; x
<8; ++x
) if (adam7
[y
][x
] == pass
)
9404 if (y
< height
) ++rows
;
9405 break; /* i.e. break the 'x', column, loop. */
9412 png_pass_cols(png_uint_32 width
, int pass
)
9414 png_uint_32 tiles
= width
>>3;
9415 png_uint_32 cols
= 0;
9420 for (x
=0; x
<8; ++x
) for (y
=0; y
<8; ++y
) if (adam7
[y
][x
] == pass
)
9423 if (x
< width
) ++cols
;
9424 break; /* i.e. break the 'y', row, loop. */
9431 perform_interlace_macro_validation(void)
9433 /* The macros to validate, first those that depend only on pass:
9435 * PNG_PASS_START_ROW(pass)
9436 * PNG_PASS_START_COL(pass)
9437 * PNG_PASS_ROW_SHIFT(pass)
9438 * PNG_PASS_COL_SHIFT(pass)
9442 for (pass
=0; pass
<7; ++pass
)
9444 png_uint_32 m
, f
, v
;
9446 m
= PNG_PASS_START_ROW(pass
);
9447 f
= png_pass_start_row(pass
);
9450 fprintf(stderr
, "PNG_PASS_START_ROW(%d) = %u != %x\n", pass
, m
, f
);
9454 m
= PNG_PASS_START_COL(pass
);
9455 f
= png_pass_start_col(pass
);
9458 fprintf(stderr
, "PNG_PASS_START_COL(%d) = %u != %x\n", pass
, m
, f
);
9462 m
= PNG_PASS_ROW_SHIFT(pass
);
9463 f
= png_pass_row_shift(pass
);
9466 fprintf(stderr
, "PNG_PASS_ROW_SHIFT(%d) = %u != %x\n", pass
, m
, f
);
9470 m
= PNG_PASS_COL_SHIFT(pass
);
9471 f
= png_pass_col_shift(pass
);
9474 fprintf(stderr
, "PNG_PASS_COL_SHIFT(%d) = %u != %x\n", pass
, m
, f
);
9478 /* Macros that depend on the image or sub-image height too:
9480 * PNG_PASS_ROWS(height, pass)
9481 * PNG_PASS_COLS(width, pass)
9482 * PNG_ROW_FROM_PASS_ROW(yIn, pass)
9483 * PNG_COL_FROM_PASS_COL(xIn, pass)
9484 * PNG_ROW_IN_INTERLACE_PASS(y, pass)
9485 * PNG_COL_IN_INTERLACE_PASS(x, pass)
9489 /* First the base 0 stuff: */
9490 m
= PNG_ROW_FROM_PASS_ROW(v
, pass
);
9491 f
= png_row_from_pass_row(v
, pass
);
9494 fprintf(stderr
, "PNG_ROW_FROM_PASS_ROW(%u, %d) = %u != %x\n",
9499 m
= PNG_COL_FROM_PASS_COL(v
, pass
);
9500 f
= png_col_from_pass_col(v
, pass
);
9503 fprintf(stderr
, "PNG_COL_FROM_PASS_COL(%u, %d) = %u != %x\n",
9508 m
= PNG_ROW_IN_INTERLACE_PASS(v
, pass
);
9509 f
= png_row_in_interlace_pass(v
, pass
);
9512 fprintf(stderr
, "PNG_ROW_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
9517 m
= PNG_COL_IN_INTERLACE_PASS(v
, pass
);
9518 f
= png_col_in_interlace_pass(v
, pass
);
9521 fprintf(stderr
, "PNG_COL_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
9526 /* Then the base 1 stuff: */
9528 m
= PNG_PASS_ROWS(v
, pass
);
9529 f
= png_pass_rows(v
, pass
);
9532 fprintf(stderr
, "PNG_PASS_ROWS(%u, %d) = %u != %x\n",
9537 m
= PNG_PASS_COLS(v
, pass
);
9538 f
= png_pass_cols(v
, pass
);
9541 fprintf(stderr
, "PNG_PASS_COLS(%u, %d) = %u != %x\n",
9546 /* Move to the next v - the stepping algorithm starts skipping
9547 * values above 1024.
9551 if (v
== PNG_UINT_31_MAX
)
9555 if (v
>= PNG_UINT_31_MAX
)
9556 v
= PNG_UINT_31_MAX
-1;
9562 /* Test color encodings. These values are back-calculated from the published
9563 * chromaticities. The values are accurate to about 14 decimal places; 15 are
9564 * given. These values are much more accurate than the ones given in the spec,
9565 * which typically don't exceed 4 decimal places. This allows testing of the
9566 * libpng code to its theoretical accuracy of 4 decimal places. (If pngvalid
9567 * used the published errors the 'slack' permitted would have to be +/-.5E-4 or
9570 * The png_modifier code assumes that encodings[0] is sRGB and treats it
9571 * specially: do not change the first entry in this list!
9573 static PNG_CONST color_encoding test_encodings
[] =
9575 /* sRGB: must be first in this list! */
9577 /*red: */ { 0.412390799265959, 0.212639005871510, 0.019330818715592 },
9578 /*green:*/ { 0.357584339383878, 0.715168678767756, 0.119194779794626 },
9579 /*blue: */ { 0.180480788401834, 0.072192315360734, 0.950532152249660} },
9580 /* Kodak ProPhoto (wide gamut) */
9581 /*gamma:*/ { 1/1.6 /*approximate: uses 1.8 power law compared to sRGB 2.4*/,
9582 /*red: */ { 0.797760489672303, 0.288071128229293, 0.000000000000000 },
9583 /*green:*/ { 0.135185837175740, 0.711843217810102, 0.000000000000000 },
9584 /*blue: */ { 0.031349349581525, 0.000085653960605, 0.825104602510460} },
9585 /* Adobe RGB (1998) */
9586 /*gamma:*/ { 1/(2+51./256),
9587 /*red: */ { 0.576669042910131, 0.297344975250536, 0.027031361386412 },
9588 /*green:*/ { 0.185558237906546, 0.627363566255466, 0.070688852535827 },
9589 /*blue: */ { 0.188228646234995, 0.075291458493998, 0.991337536837639} },
9590 /* Adobe Wide Gamut RGB */
9591 /*gamma:*/ { 1/(2+51./256),
9592 /*red: */ { 0.716500716779386, 0.258728243040113, 0.000000000000000 },
9593 /*green:*/ { 0.101020574397477, 0.724682314948566, 0.051211818965388 },
9594 /*blue: */ { 0.146774385252705, 0.016589442011321, 0.773892783545073} },
9599 * This attempts to trap signals and escape without crashing. It needs a
9600 * context pointer so that it can throw an exception (call longjmp) to recover
9601 * from the condition; this is handled by making the png_modifier used by 'main'
9602 * into a global variable.
9604 static png_modifier pm
;
9606 static void signal_handler(int signum
)
9612 pos
= safecat(msg
, sizeof msg
, pos
, "caught signal: ");
9617 pos
= safecat(msg
, sizeof msg
, pos
, "abort");
9621 pos
= safecat(msg
, sizeof msg
, pos
, "floating point exception");
9625 pos
= safecat(msg
, sizeof msg
, pos
, "illegal instruction");
9629 pos
= safecat(msg
, sizeof msg
, pos
, "interrupt");
9633 pos
= safecat(msg
, sizeof msg
, pos
, "invalid memory access");
9637 pos
= safecat(msg
, sizeof msg
, pos
, "termination request");
9641 pos
= safecat(msg
, sizeof msg
, pos
, "unknown ");
9642 pos
= safecatn(msg
, sizeof msg
, pos
, signum
);
9646 store_log(&pm
.this, NULL
/*png_structp*/, msg
, 1/*error*/);
9648 /* And finally throw an exception so we can keep going, unless this is
9649 * SIGTERM in which case stop now.
9651 if (signum
!= SIGTERM
)
9653 struct exception_context
*the_exception_context
=
9654 &pm
.this.exception_context
;
9664 int main(int argc
, char **argv
)
9666 volatile int summary
= 1; /* Print the error summary at the end */
9667 volatile int memstats
= 0; /* Print memory statistics at the end */
9669 /* Create the given output file on success: */
9670 PNG_CONST
char *volatile touch
= NULL
;
9672 /* This is an array of standard gamma values (believe it or not I've seen
9673 * every one of these mentioned somewhere.)
9675 * In the following list the most useful values are first!
9678 gammas
[]={2.2, 1.0, 2.2/1.45, 1.8, 1.5, 2.4, 2.5, 2.62, 2.9};
9680 /* This records the command and arguments: */
9684 anon_context(&pm
.this);
9686 /* Add appropriate signal handlers, just the ANSI specified ones: */
9687 signal(SIGABRT
, signal_handler
);
9688 signal(SIGFPE
, signal_handler
);
9689 signal(SIGILL
, signal_handler
);
9690 signal(SIGINT
, signal_handler
);
9691 signal(SIGSEGV
, signal_handler
);
9692 signal(SIGTERM
, signal_handler
);
9694 #ifdef HAVE_FEENABLEEXCEPT
9695 /* Only required to enable FP exceptions on platforms where they start off
9696 * disabled; this is not necessary but if it is not done pngvalid will likely
9697 * end up ignoring FP conditions that other platforms fault.
9699 feenableexcept(FE_DIVBYZERO
| FE_INVALID
| FE_OVERFLOW
);
9704 /* Preallocate the image buffer, because we know how big it needs to be,
9705 * note that, for testing purposes, it is deliberately mis-aligned by tag
9706 * bytes either side. All rows have an additional five bytes of padding for
9707 * overwrite checking.
9709 store_ensure_image(&pm
.this, NULL
, 2, TRANSFORM_ROWMAX
, TRANSFORM_HEIGHTMAX
);
9711 /* Don't give argv[0], it's normally some horrible libtool string: */
9712 cp
= safecat(command
, sizeof command
, cp
, "pngvalid");
9714 /* Default to error on warning: */
9715 pm
.this.treat_warnings_as_errors
= 1;
9717 /* Store the test gammas */
9719 pm
.ngammas
= (sizeof gammas
) / (sizeof gammas
[0]);
9720 pm
.ngamma_tests
= 0; /* default to off */
9722 /* And the test encodings */
9723 pm
.encodings
= test_encodings
;
9724 pm
.nencodings
= (sizeof test_encodings
) / (sizeof test_encodings
[0]);
9726 pm
.sbitlow
= 8U; /* because libpng doesn't do sBIT below 8! */
9727 /* The following allows results to pass if they correspond to anything in the
9728 * transformed range [input-.5,input+.5]; this is is required because of the
9729 * way libpng treates the 16_TO_8 flag when building the gamma tables.
9733 pm
.use_input_precision_16to8
= 1U;
9735 /* Some default values (set the behavior for 'make check' here).
9736 * These values simply control the maximum error permitted in the gamma
9737 * transformations. The practial limits for human perception are described
9738 * below (the setting for maxpc16), however for 8 bit encodings it isn't
9739 * possible to meet the accepted capabilities of human vision - i.e. 8 bit
9740 * images can never be good enough, regardless of encoding.
9742 pm
.maxout8
= .1; /* Arithmetic error in *encoded* value */
9743 pm
.maxabs8
= .00005; /* 1/20000 */
9744 pm
.maxcalc8
= .004; /* +/-1 in 8 bits for compose errors */
9745 pm
.maxpc8
= .499; /* I.e., .499% fractional error */
9746 pm
.maxout16
= .499; /* Error in *encoded* value */
9747 pm
.maxabs16
= .00005;/* 1/20000 */
9748 pm
.maxcalc16
=.000015;/* +/-1 in 16 bits for compose errors */
9750 /* NOTE: this is a reasonable perceptual limit. We assume that humans can
9751 * perceive light level differences of 1% over a 100:1 range, so we need to
9752 * maintain 1 in 10000 accuracy (in linear light space), which is what the
9753 * following guarantees. It also allows significantly higher errors at
9754 * higher 16 bit values, which is important for performance. The actual
9755 * maximum 16 bit error is about +/-1.9 in the fixed point implementation but
9756 * this is only allowed for values >38149 by the following:
9758 pm
.maxpc16
= .005; /* I.e., 1/200% - 1/20000 */
9760 /* Now parse the command line options. */
9763 int catmore
= 0; /* Set if the argument has an argument. */
9765 /* Record each argument for posterity: */
9766 cp
= safecat(command
, sizeof command
, cp
, " ");
9767 cp
= safecat(command
, sizeof command
, cp
, *++argv
);
9769 if (strcmp(*argv
, "-v") == 0)
9770 pm
.this.verbose
= 1;
9772 else if (strcmp(*argv
, "-l") == 0)
9775 else if (strcmp(*argv
, "-q") == 0)
9776 summary
= pm
.this.verbose
= pm
.log
= 0;
9778 else if (strcmp(*argv
, "-w") == 0)
9779 pm
.this.treat_warnings_as_errors
= 0;
9781 else if (strcmp(*argv
, "--speed") == 0)
9782 pm
.this.speed
= 1, pm
.ngamma_tests
= pm
.ngammas
, pm
.test_standard
= 0,
9785 else if (strcmp(*argv
, "--memory") == 0)
9788 else if (strcmp(*argv
, "--size") == 0)
9791 else if (strcmp(*argv
, "--nosize") == 0)
9794 else if (strcmp(*argv
, "--standard") == 0)
9795 pm
.test_standard
= 1;
9797 else if (strcmp(*argv
, "--nostandard") == 0)
9798 pm
.test_standard
= 0;
9800 else if (strcmp(*argv
, "--transform") == 0)
9801 pm
.test_transform
= 1;
9803 else if (strcmp(*argv
, "--notransform") == 0)
9804 pm
.test_transform
= 0;
9806 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
9807 else if (strncmp(*argv
, "--transform-disable=",
9808 sizeof "--transform-disable") == 0)
9810 pm
.test_transform
= 1;
9811 transform_disable(*argv
+ sizeof "--transform-disable");
9814 else if (strncmp(*argv
, "--transform-enable=",
9815 sizeof "--transform-enable") == 0)
9817 pm
.test_transform
= 1;
9818 transform_enable(*argv
+ sizeof "--transform-enable");
9820 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
9822 else if (strcmp(*argv
, "--gamma") == 0)
9824 /* Just do two gamma tests here (2.2 and linear) for speed: */
9825 pm
.ngamma_tests
= 2U;
9826 pm
.test_gamma_threshold
= 1;
9827 pm
.test_gamma_transform
= 1;
9828 pm
.test_gamma_sbit
= 1;
9829 pm
.test_gamma_scale16
= 1;
9830 pm
.test_gamma_background
= 1;
9831 pm
.test_gamma_alpha_mode
= 1;
9834 else if (strcmp(*argv
, "--nogamma") == 0)
9835 pm
.ngamma_tests
= 0;
9837 else if (strcmp(*argv
, "--gamma-threshold") == 0)
9838 pm
.ngamma_tests
= 2U, pm
.test_gamma_threshold
= 1;
9840 else if (strcmp(*argv
, "--nogamma-threshold") == 0)
9841 pm
.test_gamma_threshold
= 0;
9843 else if (strcmp(*argv
, "--gamma-transform") == 0)
9844 pm
.ngamma_tests
= 2U, pm
.test_gamma_transform
= 1;
9846 else if (strcmp(*argv
, "--nogamma-transform") == 0)
9847 pm
.test_gamma_transform
= 0;
9849 else if (strcmp(*argv
, "--gamma-sbit") == 0)
9850 pm
.ngamma_tests
= 2U, pm
.test_gamma_sbit
= 1;
9852 else if (strcmp(*argv
, "--nogamma-sbit") == 0)
9853 pm
.test_gamma_sbit
= 0;
9855 else if (strcmp(*argv
, "--gamma-16-to-8") == 0)
9856 pm
.ngamma_tests
= 2U, pm
.test_gamma_scale16
= 1;
9858 else if (strcmp(*argv
, "--nogamma-16-to-8") == 0)
9859 pm
.test_gamma_scale16
= 0;
9861 else if (strcmp(*argv
, "--gamma-background") == 0)
9862 pm
.ngamma_tests
= 2U, pm
.test_gamma_background
= 1;
9864 else if (strcmp(*argv
, "--nogamma-background") == 0)
9865 pm
.test_gamma_background
= 0;
9867 else if (strcmp(*argv
, "--gamma-alpha-mode") == 0)
9868 pm
.ngamma_tests
= 2U, pm
.test_gamma_alpha_mode
= 1;
9870 else if (strcmp(*argv
, "--nogamma-alpha-mode") == 0)
9871 pm
.test_gamma_alpha_mode
= 0;
9873 else if (strcmp(*argv
, "--expand16") == 0)
9874 pm
.test_gamma_expand16
= 1;
9876 else if (strcmp(*argv
, "--noexpand16") == 0)
9877 pm
.test_gamma_expand16
= 0;
9879 else if (strcmp(*argv
, "--more-gammas") == 0)
9880 pm
.ngamma_tests
= 3U;
9882 else if (strcmp(*argv
, "--all-gammas") == 0)
9883 pm
.ngamma_tests
= pm
.ngammas
;
9885 else if (strcmp(*argv
, "--progressive-read") == 0)
9886 pm
.this.progressive
= 1;
9888 else if (strcmp(*argv
, "--use-update-info") == 0)
9889 ++pm
.use_update_info
; /* Can call multiple times */
9891 else if (strcmp(*argv
, "--interlace") == 0)
9892 pm
.interlace_type
= PNG_INTERLACE_ADAM7
;
9894 else if (strcmp(*argv
, "--use-input-precision") == 0)
9895 pm
.use_input_precision
= 1;
9897 else if (strcmp(*argv
, "--calculations-use-input-precision") == 0)
9898 pm
.calculations_use_input_precision
= 1;
9900 else if (strcmp(*argv
, "--assume-16-bit-calculations") == 0)
9901 pm
.assume_16_bit_calculations
= 1;
9903 else if (strcmp(*argv
, "--calculations-follow-bit-depth") == 0)
9904 pm
.calculations_use_input_precision
=
9905 pm
.assume_16_bit_calculations
= 0;
9907 else if (strcmp(*argv
, "--exhaustive") == 0)
9908 pm
.test_exhaustive
= 1;
9910 else if (argc
> 1 && strcmp(*argv
, "--sbitlow") == 0)
9911 --argc
, pm
.sbitlow
= (png_byte
)atoi(*++argv
), catmore
= 1;
9913 else if (argc
> 1 && strcmp(*argv
, "--touch") == 0)
9914 --argc
, touch
= *++argv
, catmore
= 1;
9916 else if (argc
> 1 && strncmp(*argv
, "--max", 5) == 0)
9920 if (strcmp(5+*argv
, "abs8") == 0)
9921 pm
.maxabs8
= atof(*++argv
);
9923 else if (strcmp(5+*argv
, "abs16") == 0)
9924 pm
.maxabs16
= atof(*++argv
);
9926 else if (strcmp(5+*argv
, "calc8") == 0)
9927 pm
.maxcalc8
= atof(*++argv
);
9929 else if (strcmp(5+*argv
, "calc16") == 0)
9930 pm
.maxcalc16
= atof(*++argv
);
9932 else if (strcmp(5+*argv
, "out8") == 0)
9933 pm
.maxout8
= atof(*++argv
);
9935 else if (strcmp(5+*argv
, "out16") == 0)
9936 pm
.maxout16
= atof(*++argv
);
9938 else if (strcmp(5+*argv
, "pc8") == 0)
9939 pm
.maxpc8
= atof(*++argv
);
9941 else if (strcmp(5+*argv
, "pc16") == 0)
9942 pm
.maxpc16
= atof(*++argv
);
9946 fprintf(stderr
, "pngvalid: %s: unknown 'max' option\n", *argv
);
9953 else if (strcmp(*argv
, "--log8") == 0)
9954 --argc
, pm
.log8
= atof(*++argv
), catmore
= 1;
9956 else if (strcmp(*argv
, "--log16") == 0)
9957 --argc
, pm
.log16
= atof(*++argv
), catmore
= 1;
9961 fprintf(stderr
, "pngvalid: %s: unknown argument\n", *argv
);
9965 if (catmore
) /* consumed an extra *argv */
9967 cp
= safecat(command
, sizeof command
, cp
, " ");
9968 cp
= safecat(command
, sizeof command
, cp
, *argv
);
9972 /* If pngvalid is run with no arguments default to a reasonable set of the
9975 if (pm
.test_standard
== 0 && pm
.test_size
== 0 && pm
.test_transform
== 0 &&
9976 pm
.ngamma_tests
== 0)
9978 /* Make this do all the tests done in the test shell scripts with the same
9979 * parameters, where possible. The limitation is that all the progressive
9980 * read and interlace stuff has to be done in separate runs, so only the
9981 * basic 'standard' and 'size' tests are done.
9983 pm
.test_standard
= 1;
9985 pm
.test_transform
= 1;
9986 pm
.ngamma_tests
= 2U;
9989 if (pm
.ngamma_tests
> 0 &&
9990 pm
.test_gamma_threshold
== 0 && pm
.test_gamma_transform
== 0 &&
9991 pm
.test_gamma_sbit
== 0 && pm
.test_gamma_scale16
== 0 &&
9992 pm
.test_gamma_background
== 0 && pm
.test_gamma_alpha_mode
== 0)
9994 pm
.test_gamma_threshold
= 1;
9995 pm
.test_gamma_transform
= 1;
9996 pm
.test_gamma_sbit
= 1;
9997 pm
.test_gamma_scale16
= 1;
9998 pm
.test_gamma_background
= 1;
9999 pm
.test_gamma_alpha_mode
= 1;
10002 else if (pm
.ngamma_tests
== 0)
10004 /* Nothing to test so turn everything off: */
10005 pm
.test_gamma_threshold
= 0;
10006 pm
.test_gamma_transform
= 0;
10007 pm
.test_gamma_sbit
= 0;
10008 pm
.test_gamma_scale16
= 0;
10009 pm
.test_gamma_background
= 0;
10010 pm
.test_gamma_alpha_mode
= 0;
10015 /* Make useful base images */
10016 make_transform_images(&pm
.this);
10018 /* Perform the standard and gamma tests. */
10019 if (pm
.test_standard
)
10021 perform_interlace_macro_validation();
10022 perform_formatting_test(&pm
.this);
10023 # ifdef PNG_READ_SUPPORTED
10024 perform_standard_test(&pm
);
10026 perform_error_test(&pm
);
10029 /* Various oddly sized images: */
10032 make_size_images(&pm
.this);
10033 # ifdef PNG_READ_SUPPORTED
10034 perform_size_test(&pm
);
10038 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
10039 /* Combinatorial transforms: */
10040 if (pm
.test_transform
)
10041 perform_transform_test(&pm
);
10042 #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
10044 #ifdef PNG_READ_GAMMA_SUPPORTED
10045 if (pm
.ngamma_tests
> 0)
10046 perform_gamma_test(&pm
, summary
);
10052 fprintf(stderr
, "pngvalid: test aborted (probably failed in cleanup)\n");
10053 if (!pm
.this.verbose
)
10055 if (pm
.this.error
[0] != 0)
10056 fprintf(stderr
, "pngvalid: first error: %s\n", pm
.this.error
);
10058 fprintf(stderr
, "pngvalid: run with -v to see what happened\n");
10065 printf("%s: %s (%s point arithmetic)\n",
10066 (pm
.this.nerrors
|| (pm
.this.treat_warnings_as_errors
&&
10067 pm
.this.nwarnings
)) ? "FAIL" : "PASS",
10069 #if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || PNG_LIBPNG_VER < 10500
10079 printf("Allocated memory statistics (in bytes):\n"
10080 "\tread %lu maximum single, %lu peak, %lu total\n"
10081 "\twrite %lu maximum single, %lu peak, %lu total\n",
10082 (unsigned long)pm
.this.read_memory_pool
.max_max
,
10083 (unsigned long)pm
.this.read_memory_pool
.max_limit
,
10084 (unsigned long)pm
.this.read_memory_pool
.max_total
,
10085 (unsigned long)pm
.this.write_memory_pool
.max_max
,
10086 (unsigned long)pm
.this.write_memory_pool
.max_limit
,
10087 (unsigned long)pm
.this.write_memory_pool
.max_total
);
10090 /* Do this here to provoke memory corruption errors in memory not directly
10091 * allocated by libpng - not a complete test, but better than nothing.
10093 store_delete(&pm
.this);
10095 /* Error exit if there are any errors, and maybe if there are any
10098 if (pm
.this.nerrors
|| (pm
.this.treat_warnings_as_errors
&&
10099 pm
.this.nwarnings
))
10101 if (!pm
.this.verbose
)
10102 fprintf(stderr
, "pngvalid: %s\n", pm
.this.error
);
10104 fprintf(stderr
, "pngvalid: %d errors, %d warnings\n", pm
.this.nerrors
,
10105 pm
.this.nwarnings
);
10110 /* Success case. */
10113 FILE *fsuccess
= fopen(touch
, "wt");
10115 if (fsuccess
!= NULL
)
10118 fprintf(fsuccess
, "PNG validation succeeded\n");
10120 error
= ferror(fsuccess
);
10122 if (fclose(fsuccess
) || error
)
10124 fprintf(stderr
, "%s: write failed\n", touch
);
10131 fprintf(stderr
, "%s: open failed\n", touch
);
10138 #else /* write not supported */
10141 fprintf(stderr
, "pngvalid: no write support in libpng, all tests skipped\n");
10142 /* So the test is skipped: */