blob: bdd3c9188d6accbf33a4c34995a2b5ac731d2852 [file] [log] [blame]
Chris Craikb50c2172013-07-29 15:28:30 -07001
2/* pngvalid.c - validate libpng by constructing then reading png files.
3 *
Matt Sarett9ea75692016-01-08 13:00:42 -05004 * Last changed in libpng 1.5.25 [December 3, 2015]
5 * Copyright (c) 2014-2015 Glenn Randers-Pehrson
Chris Craikb50c2172013-07-29 15:28:30 -07006 * Written by John Cunningham Bowler
7 *
8 * This code is released under the libpng license.
9 * For conditions of distribution and use, see the disclaimer
10 * and license in png.h
11 *
12 * NOTES:
13 * This is a C program that is intended to be linked against libpng. It
14 * generates bitmaps internally, stores them as PNG files (using the
15 * sequential write code) then reads them back (using the sequential
16 * read code) and validates that the result has the correct data.
17 *
18 * The program can be modified and extended to test the correctness of
19 * transformations performed by libpng.
20 */
21
22#define _POSIX_SOURCE 1
23#define _ISOC99_SOURCE 1 /* For floating point */
24#define _GNU_SOURCE 1 /* For the floating point exception extension */
25
26#include <signal.h>
27#include <stdio.h>
28
29#if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
30# include <config.h>
31#endif
32
33#ifdef HAVE_FEENABLEEXCEPT /* from config.h, if included */
34# include <fenv.h>
35#endif
36
Matt Sarett9ea75692016-01-08 13:00:42 -050037#ifndef FE_DIVBYZERO
38# define FE_DIVBYZERO 0
39#endif
40#ifndef FE_INVALID
41# define FE_INVALID 0
42#endif
43#ifndef FE_OVERFLOW
44# define FE_OVERFLOW 0
45#endif
46
Chris Craikb50c2172013-07-29 15:28:30 -070047/* Define the following to use this test against your installed libpng, rather
48 * than the one being built here:
49 */
50#ifdef PNG_FREESTANDING_TESTS
51# include <png.h>
52#else
53# include "../../png.h"
54#endif
55
Sireesh Tripurarib478e662014-05-09 15:15:10 +053056#ifdef PNG_ZLIB_HEADER
57# include PNG_ZLIB_HEADER
58#else
59# include <zlib.h> /* For crc32 */
60#endif
61
62/* 1.6.1 added support for the configure test harness, which uses 77 to indicate
63 * a skipped test, in earlier versions we need to succeed on a skipped test, so:
64 */
65#if PNG_LIBPNG_VER < 10601
66# define SKIP 0
67#else
68# define SKIP 77
69#endif
70
71/* pngvalid requires write support and one of the fixed or floating point APIs.
72 */
73#if defined(PNG_WRITE_SUPPORTED) &&\
74 (defined(PNG_FIXED_POINT_SUPPORTED) || defined(PNG_FLOATING_POINT_SUPPORTED))
Chris Craikb50c2172013-07-29 15:28:30 -070075
76#if PNG_LIBPNG_VER < 10500
Matt Sarett9ea75692016-01-08 13:00:42 -050077/* This deliberately lacks the const. */
Chris Craikb50c2172013-07-29 15:28:30 -070078typedef png_byte *png_const_bytep;
79
80/* This is copied from 1.5.1 png.h: */
81#define PNG_INTERLACE_ADAM7_PASSES 7
82#define PNG_PASS_START_ROW(pass) (((1U&~(pass))<<(3-((pass)>>1)))&7)
83#define PNG_PASS_START_COL(pass) (((1U& (pass))<<(3-(((pass)+1)>>1)))&7)
84#define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3)
85#define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3)
86#define PNG_PASS_ROWS(height, pass) (((height)+(((1<<PNG_PASS_ROW_SHIFT(pass))\
87 -1)-PNG_PASS_START_ROW(pass)))>>PNG_PASS_ROW_SHIFT(pass))
88#define PNG_PASS_COLS(width, pass) (((width)+(((1<<PNG_PASS_COL_SHIFT(pass))\
89 -1)-PNG_PASS_START_COL(pass)))>>PNG_PASS_COL_SHIFT(pass))
90#define PNG_ROW_FROM_PASS_ROW(yIn, pass) \
91 (((yIn)<<PNG_PASS_ROW_SHIFT(pass))+PNG_PASS_START_ROW(pass))
92#define PNG_COL_FROM_PASS_COL(xIn, pass) \
93 (((xIn)<<PNG_PASS_COL_SHIFT(pass))+PNG_PASS_START_COL(pass))
94#define PNG_PASS_MASK(pass,off) ( \
95 ((0x110145AFU>>(((7-(off))-(pass))<<2)) & 0xFU) | \
96 ((0x01145AF0U>>(((7-(off))-(pass))<<2)) & 0xF0U))
97#define PNG_ROW_IN_INTERLACE_PASS(y, pass) \
98 ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1)
99#define PNG_COL_IN_INTERLACE_PASS(x, pass) \
100 ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1)
101
102/* These are needed too for the default build: */
103#define PNG_WRITE_16BIT_SUPPORTED
104#define PNG_READ_16BIT_SUPPORTED
105
106/* This comes from pnglibconf.h afer 1.5: */
107#define PNG_FP_1 100000
108#define PNG_GAMMA_THRESHOLD_FIXED\
109 ((png_fixed_point)(PNG_GAMMA_THRESHOLD * PNG_FP_1))
110#endif
111
112#if PNG_LIBPNG_VER < 10600
113 /* 1.6.0 constifies many APIs, the following exists to allow pngvalid to be
114 * compiled against earlier versions.
115 */
116# define png_const_structp png_structp
117#endif
118
Chris Craikb50c2172013-07-29 15:28:30 -0700119#include <float.h> /* For floating point constants */
120#include <stdlib.h> /* For malloc */
121#include <string.h> /* For memcpy, memset */
122#include <math.h> /* For floor */
123
124/* Unused formal parameter errors are removed using the following macro which is
125 * expected to have no bad effects on performance.
126 */
127#ifndef UNUSED
128# if defined(__GNUC__) || defined(_MSC_VER)
129# define UNUSED(param) (void)param;
130# else
131# define UNUSED(param)
132# endif
133#endif
134
135/***************************** EXCEPTION HANDLING *****************************/
136#ifdef PNG_FREESTANDING_TESTS
137# include <cexcept.h>
138#else
139# include "../visupng/cexcept.h"
140#endif
141
142#ifdef __cplusplus
143# define this not_the_cpp_this
144# define new not_the_cpp_new
145# define voidcast(type, value) static_cast<type>(value)
146#else
147# define voidcast(type, value) (value)
148#endif /* __cplusplus */
149
150struct png_store;
151define_exception_type(struct png_store*);
152
153/* The following are macros to reduce typing everywhere where the well known
154 * name 'the_exception_context' must be defined.
155 */
156#define anon_context(ps) struct exception_context *the_exception_context = \
157 &(ps)->exception_context
158#define context(ps,fault) anon_context(ps); png_store *fault
159
Matt Sarett9ea75692016-01-08 13:00:42 -0500160/* This macro returns the number of elements in an array as an (unsigned int),
161 * it is necessary to avoid the inability of certain versions of GCC to use
162 * the value of a compile-time constant when performing range checks. It must
163 * be passed an array name.
164 */
165#define ARRAY_SIZE(a) ((unsigned int)((sizeof (a))/(sizeof (a)[0])))
166
167/* GCC BUG 66447 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66447) requires
168 * some broken GCC versions to be fixed up to avoid invalid whining about auto
169 * variables that are *not* changed within the scope of a setjmp being changed.
170 *
171 * Feel free to extend the list of broken versions.
172 */
173#define is_gnu(major,minor)\
174 (defined __GNUC__) && __GNUC__ == (major) && __GNUC_MINOR__ == (minor)
175#define is_gnu_patch(major,minor,patch)\
176 is_gnu(major,minor) && __GNUC_PATCHLEVEL__ == 0
177/* For the moment just do it always; all versions of GCC seem to be broken: */
178#ifdef __GNUC__
179 const void * volatile make_volatile_for_gnu;
180# define gnu_volatile(x) make_volatile_for_gnu = &x;
181#else /* !GNUC broken versions */
182# define gnu_volatile(x)
183#endif /* !GNUC broken versions */
184
Chris Craikb50c2172013-07-29 15:28:30 -0700185/******************************* UTILITIES ************************************/
186/* Error handling is particularly problematic in production code - error
187 * handlers often themselves have bugs which lead to programs that detect
188 * minor errors crashing. The following functions deal with one very
189 * common class of errors in error handlers - attempting to format error or
190 * warning messages into buffers that are too small.
191 */
192static size_t safecat(char *buffer, size_t bufsize, size_t pos,
Matt Sarett9ea75692016-01-08 13:00:42 -0500193 const char *cat)
Chris Craikb50c2172013-07-29 15:28:30 -0700194{
195 while (pos < bufsize && cat != NULL && *cat != 0)
196 buffer[pos++] = *cat++;
197
198 if (pos >= bufsize)
199 pos = bufsize-1;
200
201 buffer[pos] = 0;
202 return pos;
203}
204
205static size_t safecatn(char *buffer, size_t bufsize, size_t pos, int n)
206{
207 char number[64];
208 sprintf(number, "%d", n);
209 return safecat(buffer, bufsize, pos, number);
210}
211
212#ifdef PNG_READ_TRANSFORMS_SUPPORTED
213static size_t safecatd(char *buffer, size_t bufsize, size_t pos, double d,
214 int precision)
215{
216 char number[64];
217 sprintf(number, "%.*f", precision, d);
218 return safecat(buffer, bufsize, pos, number);
219}
220#endif
221
Matt Sarett9ea75692016-01-08 13:00:42 -0500222static const char invalid[] = "invalid";
223static const char sep[] = ": ";
Chris Craikb50c2172013-07-29 15:28:30 -0700224
Matt Sarett9ea75692016-01-08 13:00:42 -0500225static const char *colour_types[8] =
Chris Craikb50c2172013-07-29 15:28:30 -0700226{
227 "grayscale", invalid, "truecolour", "indexed-colour",
228 "grayscale with alpha", invalid, "truecolour with alpha", invalid
229};
230
Matt Sarett9ea75692016-01-08 13:00:42 -0500231#ifdef PNG_READ_TRANSFORMS_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -0700232/* Convert a double precision value to fixed point. */
233static png_fixed_point
234fix(double d)
235{
236 d = floor(d * PNG_FP_1 + .5);
237 return (png_fixed_point)d;
238}
239#endif /* PNG_READ_SUPPORTED */
240
241/* Generate random bytes. This uses a boring repeatable algorithm and it
242 * is implemented here so that it gives the same set of numbers on every
243 * architecture. It's a linear congruential generator (Knuth or Sedgewick
244 * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
245 * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise
246 * Generation.)
247 */
248static void
249make_random_bytes(png_uint_32* seed, void* pv, size_t size)
250{
251 png_uint_32 u0 = seed[0], u1 = seed[1];
252 png_bytep bytes = voidcast(png_bytep, pv);
253
254 /* There are thirty three bits, the next bit in the sequence is bit-33 XOR
255 * bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
256 */
257 size_t i;
258 for (i=0; i<size; ++i)
259 {
260 /* First generate 8 new bits then shift them in at the end. */
261 png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
262 u1 <<= 8;
263 u1 |= u0 >> 24;
264 u0 <<= 8;
265 u0 |= u;
266 *bytes++ = (png_byte)u;
267 }
268
269 seed[0] = u0;
270 seed[1] = u1;
271}
272
273static void
274make_four_random_bytes(png_uint_32* seed, png_bytep bytes)
275{
276 make_random_bytes(seed, bytes, 4);
277}
278
Matt Sarett9ea75692016-01-08 13:00:42 -0500279#if defined PNG_READ_SUPPORTED || defined PNG_WRITE_tRNS_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -0700280static void
281randomize(void *pv, size_t size)
282{
283 static png_uint_32 random_seed[2] = {0x56789abc, 0xd};
284 make_random_bytes(random_seed, pv, size);
285}
286
287#define RANDOMIZE(this) randomize(&(this), sizeof (this))
Matt Sarett9ea75692016-01-08 13:00:42 -0500288#endif /* READ || WRITE_tRNS */
Chris Craikb50c2172013-07-29 15:28:30 -0700289
Matt Sarett9ea75692016-01-08 13:00:42 -0500290#ifdef PNG_READ_TRANSFORMS_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -0700291static unsigned int
292random_mod(unsigned int max)
293{
294 unsigned int x;
295
296 RANDOMIZE(x);
297
298 return x % max; /* 0 .. max-1 */
299}
300
Matt Sarett9ea75692016-01-08 13:00:42 -0500301#if (defined PNG_READ_RGB_TO_GRAY_SUPPORTED) ||\
302 (defined PNG_READ_FILLER_SUPPORTED)
Chris Craikb50c2172013-07-29 15:28:30 -0700303static int
304random_choice(void)
305{
306 unsigned char x;
307
308 RANDOMIZE(x);
309
310 return x & 1;
311}
312#endif
313#endif /* PNG_READ_SUPPORTED */
314
315/* A numeric ID based on PNG file characteristics. The 'do_interlace' field
316 * simply records whether pngvalid did the interlace itself or whether it
317 * was done by libpng. Width and height must be less than 256. 'palette' is an
Matt Sarett9ea75692016-01-08 13:00:42 -0500318 * index of the palette to use for formats with a palette otherwise a boolean
319 * indicating if a tRNS chunk was generated.
Chris Craikb50c2172013-07-29 15:28:30 -0700320 */
321#define FILEID(col, depth, palette, interlace, width, height, do_interlace) \
322 ((png_uint_32)((col) + ((depth)<<3) + ((palette)<<8) + ((interlace)<<13) + \
323 (((do_interlace)!=0)<<15) + ((width)<<16) + ((height)<<24)))
324
325#define COL_FROM_ID(id) ((png_byte)((id)& 0x7U))
326#define DEPTH_FROM_ID(id) ((png_byte)(((id) >> 3) & 0x1fU))
327#define PALETTE_FROM_ID(id) (((id) >> 8) & 0x1f)
Matt Sarett9ea75692016-01-08 13:00:42 -0500328#define INTERLACE_FROM_ID(id) ((png_byte)(((id) >> 13) & 0x3))
Chris Craikb50c2172013-07-29 15:28:30 -0700329#define DO_INTERLACE_FROM_ID(id) ((int)(((id)>>15) & 1))
330#define WIDTH_FROM_ID(id) (((id)>>16) & 0xff)
331#define HEIGHT_FROM_ID(id) (((id)>>24) & 0xff)
332
333/* Utility to construct a standard name for a standard image. */
334static size_t
335standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type,
336 int bit_depth, unsigned int npalette, int interlace_type,
337 png_uint_32 w, png_uint_32 h, int do_interlace)
338{
339 pos = safecat(buffer, bufsize, pos, colour_types[colour_type]);
Matt Sarett9ea75692016-01-08 13:00:42 -0500340 if (colour_type == 3) /* must have a palette */
Chris Craikb50c2172013-07-29 15:28:30 -0700341 {
342 pos = safecat(buffer, bufsize, pos, "[");
343 pos = safecatn(buffer, bufsize, pos, npalette);
344 pos = safecat(buffer, bufsize, pos, "]");
345 }
Matt Sarett9ea75692016-01-08 13:00:42 -0500346
347 else if (npalette != 0)
348 pos = safecat(buffer, bufsize, pos, "+tRNS");
349
Chris Craikb50c2172013-07-29 15:28:30 -0700350 pos = safecat(buffer, bufsize, pos, " ");
351 pos = safecatn(buffer, bufsize, pos, bit_depth);
352 pos = safecat(buffer, bufsize, pos, " bit");
353
354 if (interlace_type != PNG_INTERLACE_NONE)
355 {
356 pos = safecat(buffer, bufsize, pos, " interlaced");
357 if (do_interlace)
358 pos = safecat(buffer, bufsize, pos, "(pngvalid)");
359 else
360 pos = safecat(buffer, bufsize, pos, "(libpng)");
361 }
362
363 if (w > 0 || h > 0)
364 {
365 pos = safecat(buffer, bufsize, pos, " ");
366 pos = safecatn(buffer, bufsize, pos, w);
367 pos = safecat(buffer, bufsize, pos, "x");
368 pos = safecatn(buffer, bufsize, pos, h);
369 }
370
371 return pos;
372}
373
374static size_t
375standard_name_from_id(char *buffer, size_t bufsize, size_t pos, png_uint_32 id)
376{
377 return standard_name(buffer, bufsize, pos, COL_FROM_ID(id),
378 DEPTH_FROM_ID(id), PALETTE_FROM_ID(id), INTERLACE_FROM_ID(id),
379 WIDTH_FROM_ID(id), HEIGHT_FROM_ID(id), DO_INTERLACE_FROM_ID(id));
380}
381
382/* Convenience API and defines to list valid formats. Note that 16 bit read and
383 * write support is required to do 16 bit read tests (we must be able to make a
384 * 16 bit image to test!)
385 */
386#ifdef PNG_WRITE_16BIT_SUPPORTED
387# define WRITE_BDHI 4
388# ifdef PNG_READ_16BIT_SUPPORTED
389# define READ_BDHI 4
390# define DO_16BIT
391# endif
392#else
393# define WRITE_BDHI 3
394#endif
395#ifndef DO_16BIT
396# define READ_BDHI 3
397#endif
398
399/* The following defines the number of different palettes to generate for
400 * each log bit depth of a colour type 3 standard image.
401 */
402#define PALETTE_COUNT(bit_depth) ((bit_depth) > 4 ? 1U : 16U)
403
404static int
405next_format(png_bytep colour_type, png_bytep bit_depth,
Matt Sarett9ea75692016-01-08 13:00:42 -0500406 unsigned int* palette_number, int low_depth_gray, int tRNS)
Chris Craikb50c2172013-07-29 15:28:30 -0700407{
408 if (*bit_depth == 0)
409 {
Sireesh Tripurarib478e662014-05-09 15:15:10 +0530410 *colour_type = 0;
Matt Sarett9ea75692016-01-08 13:00:42 -0500411 if (low_depth_gray)
Sireesh Tripurarib478e662014-05-09 15:15:10 +0530412 *bit_depth = 1;
Matt Sarett9ea75692016-01-08 13:00:42 -0500413 else
414 *bit_depth = 8;
Sireesh Tripurarib478e662014-05-09 15:15:10 +0530415 *palette_number = 0;
Chris Craikb50c2172013-07-29 15:28:30 -0700416 return 1;
417 }
418
Matt Sarett9ea75692016-01-08 13:00:42 -0500419 if (*colour_type < 4/*no alpha channel*/)
Chris Craikb50c2172013-07-29 15:28:30 -0700420 {
Matt Sarett9ea75692016-01-08 13:00:42 -0500421 /* Add multiple palettes for colour type 3, one image with tRNS
422 * and one without for other non-alpha formats:
423 */
424 unsigned int pn = ++*palette_number;
425 png_byte ct = *colour_type;
426
427 if (((ct == 0/*GRAY*/ || ct/*RGB*/ == 2) && tRNS && pn < 2) ||
428 (ct == 3/*PALETTE*/ && pn < PALETTE_COUNT(*bit_depth)))
Chris Craikb50c2172013-07-29 15:28:30 -0700429 return 1;
430
Matt Sarett9ea75692016-01-08 13:00:42 -0500431 /* No: next bit depth */
Chris Craikb50c2172013-07-29 15:28:30 -0700432 *palette_number = 0;
433 }
434
435 *bit_depth = (png_byte)(*bit_depth << 1);
436
437 /* Palette images are restricted to 8 bit depth */
438 if (*bit_depth <= 8
Matt Sarett9ea75692016-01-08 13:00:42 -0500439#ifdef DO_16BIT
Chris Craikb50c2172013-07-29 15:28:30 -0700440 || (*colour_type != 3 && *bit_depth <= 16)
Matt Sarett9ea75692016-01-08 13:00:42 -0500441#endif
Chris Craikb50c2172013-07-29 15:28:30 -0700442 )
443 return 1;
444
445 /* Move to the next color type, or return 0 at the end. */
446 switch (*colour_type)
447 {
448 case 0:
449 *colour_type = 2;
450 *bit_depth = 8;
451 return 1;
452
453 case 2:
454 *colour_type = 3;
455 *bit_depth = 1;
456 return 1;
457
458 case 3:
459 *colour_type = 4;
460 *bit_depth = 8;
461 return 1;
462
463 case 4:
464 *colour_type = 6;
465 *bit_depth = 8;
466 return 1;
467
468 default:
469 return 0;
470 }
471}
472
473#ifdef PNG_READ_TRANSFORMS_SUPPORTED
474static unsigned int
475sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth,
Matt Sarett9ea75692016-01-08 13:00:42 -0500476 png_uint_32 x, unsigned int sample_index, int swap16, int littleendian)
Chris Craikb50c2172013-07-29 15:28:30 -0700477{
478 png_uint_32 bit_index, result;
479
480 /* Find a sample index for the desired sample: */
481 x *= bit_depth;
482 bit_index = x;
483
484 if ((colour_type & 1) == 0) /* !palette */
485 {
486 if (colour_type & 2)
487 bit_index *= 3;
488
489 if (colour_type & 4)
490 bit_index += x; /* Alpha channel */
491
492 /* Multiple channels; select one: */
493 if (colour_type & (2+4))
494 bit_index += sample_index * bit_depth;
495 }
496
497 /* Return the sample from the row as an integer. */
498 row += bit_index >> 3;
499 result = *row;
500
501 if (bit_depth == 8)
502 return result;
503
504 else if (bit_depth > 8)
Matt Sarett9ea75692016-01-08 13:00:42 -0500505 {
506 if (swap16)
507 return (*++row << 8) + result;
508 else
509 return (result << 8) + *++row;
510 }
Chris Craikb50c2172013-07-29 15:28:30 -0700511
Matt Sarett9ea75692016-01-08 13:00:42 -0500512 /* Less than 8 bits per sample. By default PNG has the big end of
513 * the egg on the left of the screen, but if littleendian is set
514 * then the big end is on the right.
515 */
Chris Craikb50c2172013-07-29 15:28:30 -0700516 bit_index &= 7;
Matt Sarett9ea75692016-01-08 13:00:42 -0500517
518 if (!littleendian)
519 bit_index = 8-bit_index-bit_depth;
520
521 return (result >> bit_index) & ((1U<<bit_depth)-1);
Chris Craikb50c2172013-07-29 15:28:30 -0700522}
523#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
524
525/* Copy a single pixel, of a given size, from one buffer to another -
526 * while this is basically bit addressed there is an implicit assumption
527 * that pixels 8 or more bits in size are byte aligned and that pixels
528 * do not otherwise cross byte boundaries. (This is, so far as I know,
529 * universally true in bitmap computer graphics. [JCB 20101212])
530 *
531 * NOTE: The to and from buffers may be the same.
532 */
533static void
534pixel_copy(png_bytep toBuffer, png_uint_32 toIndex,
Matt Sarett9ea75692016-01-08 13:00:42 -0500535 png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize,
536 int littleendian)
Chris Craikb50c2172013-07-29 15:28:30 -0700537{
538 /* Assume we can multiply by 'size' without overflow because we are
539 * just working in a single buffer.
540 */
541 toIndex *= pixelSize;
542 fromIndex *= pixelSize;
543 if (pixelSize < 8) /* Sub-byte */
544 {
545 /* Mask to select the location of the copied pixel: */
Matt Sarett9ea75692016-01-08 13:00:42 -0500546 unsigned int destMask = ((1U<<pixelSize)-1) <<
547 (littleendian ? toIndex&7 : 8-pixelSize-(toIndex&7));
Chris Craikb50c2172013-07-29 15:28:30 -0700548 /* The following read the entire pixels and clears the extra: */
549 unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask;
550 unsigned int sourceByte = fromBuffer[fromIndex >> 3];
551
552 /* Don't rely on << or >> supporting '0' here, just in case: */
553 fromIndex &= 7;
Matt Sarett9ea75692016-01-08 13:00:42 -0500554 if (littleendian)
555 {
556 if (fromIndex > 0) sourceByte >>= fromIndex;
557 if ((toIndex & 7) > 0) sourceByte <<= toIndex & 7;
558 }
559
560 else
561 {
562 if (fromIndex > 0) sourceByte <<= fromIndex;
563 if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7;
564 }
Chris Craikb50c2172013-07-29 15:28:30 -0700565
566 toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask));
567 }
568 else /* One or more bytes */
569 memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3);
570}
571
572#ifdef PNG_READ_SUPPORTED
573/* Copy a complete row of pixels, taking into account potential partial
574 * bytes at the end.
575 */
576static void
Matt Sarett9ea75692016-01-08 13:00:42 -0500577row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth,
578 int littleendian)
Chris Craikb50c2172013-07-29 15:28:30 -0700579{
580 memcpy(toBuffer, fromBuffer, bitWidth >> 3);
581
582 if ((bitWidth & 7) != 0)
583 {
584 unsigned int mask;
585
586 toBuffer += bitWidth >> 3;
587 fromBuffer += bitWidth >> 3;
Matt Sarett9ea75692016-01-08 13:00:42 -0500588 if (littleendian)
589 mask = 0xff << (bitWidth & 7);
590 else
591 mask = 0xff >> (bitWidth & 7);
Chris Craikb50c2172013-07-29 15:28:30 -0700592 *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask));
593 }
594}
595
596/* Compare pixels - they are assumed to start at the first byte in the
597 * given buffers.
598 */
599static int
600pixel_cmp(png_const_bytep pa, png_const_bytep pb, png_uint_32 bit_width)
601{
602#if PNG_LIBPNG_VER < 10506
603 if (memcmp(pa, pb, bit_width>>3) == 0)
604 {
605 png_uint_32 p;
606
607 if ((bit_width & 7) == 0) return 0;
608
609 /* Ok, any differences? */
610 p = pa[bit_width >> 3];
611 p ^= pb[bit_width >> 3];
612
613 if (p == 0) return 0;
614
615 /* There are, but they may not be significant, remove the bits
616 * after the end (the low order bits in PNG.)
617 */
618 bit_width &= 7;
619 p >>= 8-bit_width;
620
621 if (p == 0) return 0;
622 }
623#else
624 /* From libpng-1.5.6 the overwrite should be fixed, so compare the trailing
625 * bits too:
626 */
627 if (memcmp(pa, pb, (bit_width+7)>>3) == 0)
628 return 0;
629#endif
630
631 /* Return the index of the changed byte. */
632 {
633 png_uint_32 where = 0;
634
635 while (pa[where] == pb[where]) ++where;
636 return 1+where;
637 }
638}
639#endif /* PNG_READ_SUPPORTED */
640
641/*************************** BASIC PNG FILE WRITING ***************************/
642/* A png_store takes data from the sequential writer or provides data
643 * to the sequential reader. It can also store the result of a PNG
644 * write for later retrieval.
645 */
646#define STORE_BUFFER_SIZE 500 /* arbitrary */
647typedef struct png_store_buffer
648{
649 struct png_store_buffer* prev; /* NOTE: stored in reverse order */
650 png_byte buffer[STORE_BUFFER_SIZE];
651} png_store_buffer;
652
653#define FILE_NAME_SIZE 64
654
655typedef struct store_palette_entry /* record of a single palette entry */
656{
657 png_byte red;
658 png_byte green;
659 png_byte blue;
660 png_byte alpha;
661} store_palette_entry, store_palette[256];
662
663typedef struct png_store_file
664{
665 struct png_store_file* next; /* as many as you like... */
666 char name[FILE_NAME_SIZE];
667 png_uint_32 id; /* must be correct (see FILEID) */
668 png_size_t datacount; /* In this (the last) buffer */
669 png_store_buffer data; /* Last buffer in file */
670 int npalette; /* Number of entries in palette */
671 store_palette_entry* palette; /* May be NULL */
672} png_store_file;
673
674/* The following is a pool of memory allocated by a single libpng read or write
675 * operation.
676 */
677typedef struct store_pool
678{
679 struct png_store *store; /* Back pointer */
680 struct store_memory *list; /* List of allocated memory */
681 png_byte mark[4]; /* Before and after data */
682
683 /* Statistics for this run. */
684 png_alloc_size_t max; /* Maximum single allocation */
685 png_alloc_size_t current; /* Current allocation */
686 png_alloc_size_t limit; /* Highest current allocation */
687 png_alloc_size_t total; /* Total allocation */
688
689 /* Overall statistics (retained across successive runs). */
690 png_alloc_size_t max_max;
691 png_alloc_size_t max_limit;
692 png_alloc_size_t max_total;
693} store_pool;
694
695typedef struct png_store
696{
697 /* For cexcept.h exception handling - simply store one of these;
698 * the context is a self pointer but it may point to a different
699 * png_store (in fact it never does in this program.)
700 */
701 struct exception_context
702 exception_context;
703
704 unsigned int verbose :1;
705 unsigned int treat_warnings_as_errors :1;
706 unsigned int expect_error :1;
707 unsigned int expect_warning :1;
708 unsigned int saw_warning :1;
709 unsigned int speed :1;
710 unsigned int progressive :1; /* use progressive read */
711 unsigned int validated :1; /* used as a temporary flag */
712 int nerrors;
713 int nwarnings;
Sireesh Tripurarib478e662014-05-09 15:15:10 +0530714 int noptions; /* number of options below: */
715 struct {
716 unsigned char option; /* option number, 0..30 */
717 unsigned char setting; /* setting (unset,invalid,on,off) */
718 } options[16];
719 char test[128]; /* Name of test */
Chris Craikb50c2172013-07-29 15:28:30 -0700720 char error[256];
721
722 /* Read fields */
723 png_structp pread; /* Used to read a saved file */
724 png_infop piread;
725 png_store_file* current; /* Set when reading */
726 png_store_buffer* next; /* Set when reading */
727 png_size_t readpos; /* Position in *next */
728 png_byte* image; /* Buffer for reading interlaced images */
729 png_size_t cb_image; /* Size of this buffer */
730 png_size_t cb_row; /* Row size of the image(s) */
731 png_uint_32 image_h; /* Number of rows in a single image */
732 store_pool read_memory_pool;
733
734 /* Write fields */
735 png_store_file* saved;
736 png_structp pwrite; /* Used when writing a new file */
737 png_infop piwrite;
738 png_size_t writepos; /* Position in .new */
739 char wname[FILE_NAME_SIZE];
740 png_store_buffer new; /* The end of the new PNG file being written. */
741 store_pool write_memory_pool;
742 store_palette_entry* palette;
743 int npalette;
744} png_store;
745
746/* Initialization and cleanup */
747static void
748store_pool_mark(png_bytep mark)
749{
750 static png_uint_32 store_seed[2] = { 0x12345678, 1};
751
752 make_four_random_bytes(store_seed, mark);
753}
754
Matt Sarett9ea75692016-01-08 13:00:42 -0500755#ifdef PNG_READ_TRANSFORMS_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -0700756/* Use this for random 32 bit values; this function makes sure the result is
757 * non-zero.
758 */
759static png_uint_32
760random_32(void)
761{
762
Matt Sarett9ea75692016-01-08 13:00:42 -0500763 for (;;)
Chris Craikb50c2172013-07-29 15:28:30 -0700764 {
765 png_byte mark[4];
766 png_uint_32 result;
767
768 store_pool_mark(mark);
769 result = png_get_uint_32(mark);
770
771 if (result != 0)
772 return result;
773 }
774}
775#endif /* PNG_READ_SUPPORTED */
776
777static void
778store_pool_init(png_store *ps, store_pool *pool)
779{
780 memset(pool, 0, sizeof *pool);
781
782 pool->store = ps;
783 pool->list = NULL;
784 pool->max = pool->current = pool->limit = pool->total = 0;
785 pool->max_max = pool->max_limit = pool->max_total = 0;
786 store_pool_mark(pool->mark);
787}
788
789static void
790store_init(png_store* ps)
791{
792 memset(ps, 0, sizeof *ps);
793 init_exception_context(&ps->exception_context);
794 store_pool_init(ps, &ps->read_memory_pool);
795 store_pool_init(ps, &ps->write_memory_pool);
796 ps->verbose = 0;
797 ps->treat_warnings_as_errors = 0;
798 ps->expect_error = 0;
799 ps->expect_warning = 0;
800 ps->saw_warning = 0;
801 ps->speed = 0;
802 ps->progressive = 0;
803 ps->validated = 0;
804 ps->nerrors = ps->nwarnings = 0;
805 ps->pread = NULL;
806 ps->piread = NULL;
807 ps->saved = ps->current = NULL;
808 ps->next = NULL;
809 ps->readpos = 0;
810 ps->image = NULL;
811 ps->cb_image = 0;
812 ps->cb_row = 0;
813 ps->image_h = 0;
814 ps->pwrite = NULL;
815 ps->piwrite = NULL;
816 ps->writepos = 0;
817 ps->new.prev = NULL;
818 ps->palette = NULL;
819 ps->npalette = 0;
Sireesh Tripurarib478e662014-05-09 15:15:10 +0530820 ps->noptions = 0;
Chris Craikb50c2172013-07-29 15:28:30 -0700821}
822
823static void
824store_freebuffer(png_store_buffer* psb)
825{
826 if (psb->prev)
827 {
828 store_freebuffer(psb->prev);
829 free(psb->prev);
830 psb->prev = NULL;
831 }
832}
833
834static void
835store_freenew(png_store *ps)
836{
837 store_freebuffer(&ps->new);
838 ps->writepos = 0;
839 if (ps->palette != NULL)
840 {
841 free(ps->palette);
842 ps->palette = NULL;
843 ps->npalette = 0;
844 }
845}
846
847static void
848store_storenew(png_store *ps)
849{
850 png_store_buffer *pb;
851
852 if (ps->writepos != STORE_BUFFER_SIZE)
853 png_error(ps->pwrite, "invalid store call");
854
855 pb = voidcast(png_store_buffer*, malloc(sizeof *pb));
856
857 if (pb == NULL)
858 png_error(ps->pwrite, "store new: OOM");
859
860 *pb = ps->new;
861 ps->new.prev = pb;
862 ps->writepos = 0;
863}
864
865static void
866store_freefile(png_store_file **ppf)
867{
868 if (*ppf != NULL)
869 {
870 store_freefile(&(*ppf)->next);
871
872 store_freebuffer(&(*ppf)->data);
873 (*ppf)->datacount = 0;
874 if ((*ppf)->palette != NULL)
875 {
876 free((*ppf)->palette);
877 (*ppf)->palette = NULL;
878 (*ppf)->npalette = 0;
879 }
880 free(*ppf);
881 *ppf = NULL;
882 }
883}
884
885/* Main interface to file storeage, after writing a new PNG file (see the API
886 * below) call store_storefile to store the result with the given name and id.
887 */
888static void
889store_storefile(png_store *ps, png_uint_32 id)
890{
891 png_store_file *pf = voidcast(png_store_file*, malloc(sizeof *pf));
892 if (pf == NULL)
893 png_error(ps->pwrite, "storefile: OOM");
894 safecat(pf->name, sizeof pf->name, 0, ps->wname);
895 pf->id = id;
896 pf->data = ps->new;
897 pf->datacount = ps->writepos;
898 ps->new.prev = NULL;
899 ps->writepos = 0;
900 pf->palette = ps->palette;
901 pf->npalette = ps->npalette;
902 ps->palette = 0;
903 ps->npalette = 0;
904
905 /* And save it. */
906 pf->next = ps->saved;
907 ps->saved = pf;
908}
909
910/* Generate an error message (in the given buffer) */
911static size_t
912store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize,
Matt Sarett9ea75692016-01-08 13:00:42 -0500913 size_t pos, const char *msg)
Chris Craikb50c2172013-07-29 15:28:30 -0700914{
915 if (pp != NULL && pp == ps->pread)
916 {
917 /* Reading a file */
918 pos = safecat(buffer, bufsize, pos, "read: ");
919
920 if (ps->current != NULL)
921 {
922 pos = safecat(buffer, bufsize, pos, ps->current->name);
923 pos = safecat(buffer, bufsize, pos, sep);
924 }
925 }
926
927 else if (pp != NULL && pp == ps->pwrite)
928 {
929 /* Writing a file */
930 pos = safecat(buffer, bufsize, pos, "write: ");
931 pos = safecat(buffer, bufsize, pos, ps->wname);
932 pos = safecat(buffer, bufsize, pos, sep);
933 }
934
935 else
936 {
937 /* Neither reading nor writing (or a memory error in struct delete) */
938 pos = safecat(buffer, bufsize, pos, "pngvalid: ");
939 }
940
941 if (ps->test[0] != 0)
942 {
943 pos = safecat(buffer, bufsize, pos, ps->test);
944 pos = safecat(buffer, bufsize, pos, sep);
945 }
946 pos = safecat(buffer, bufsize, pos, msg);
947 return pos;
948}
949
950/* Verbose output to the error stream: */
951static void
952store_verbose(png_store *ps, png_const_structp pp, png_const_charp prefix,
953 png_const_charp message)
954{
955 char buffer[512];
956
957 if (prefix)
958 fputs(prefix, stderr);
959
960 (void)store_message(ps, pp, buffer, sizeof buffer, 0, message);
961 fputs(buffer, stderr);
962 fputc('\n', stderr);
963}
964
965/* Log an error or warning - the relevant count is always incremented. */
966static void
967store_log(png_store* ps, png_const_structp pp, png_const_charp message,
968 int is_error)
969{
970 /* The warning is copied to the error buffer if there are no errors and it is
971 * the first warning. The error is copied to the error buffer if it is the
972 * first error (overwriting any prior warnings).
973 */
974 if (is_error ? (ps->nerrors)++ == 0 :
975 (ps->nwarnings)++ == 0 && ps->nerrors == 0)
976 store_message(ps, pp, ps->error, sizeof ps->error, 0, message);
977
978 if (ps->verbose)
979 store_verbose(ps, pp, is_error ? "error: " : "warning: ", message);
980}
981
982#ifdef PNG_READ_SUPPORTED
983/* Internal error function, called with a png_store but no libpng stuff. */
984static void
985internal_error(png_store *ps, png_const_charp message)
986{
987 store_log(ps, NULL, message, 1 /* error */);
988
989 /* And finally throw an exception. */
990 {
991 struct exception_context *the_exception_context = &ps->exception_context;
992 Throw ps;
993 }
994}
995#endif /* PNG_READ_SUPPORTED */
996
997/* Functions to use as PNG callbacks. */
Sireesh Tripurarib478e662014-05-09 15:15:10 +0530998static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -0700999store_error(png_structp ppIn, png_const_charp message) /* PNG_NORETURN */
1000{
1001 png_const_structp pp = ppIn;
1002 png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
1003
1004 if (!ps->expect_error)
1005 store_log(ps, pp, message, 1 /* error */);
1006
1007 /* And finally throw an exception. */
1008 {
1009 struct exception_context *the_exception_context = &ps->exception_context;
1010 Throw ps;
1011 }
1012}
1013
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301014static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07001015store_warning(png_structp ppIn, png_const_charp message)
1016{
1017 png_const_structp pp = ppIn;
1018 png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
1019
1020 if (!ps->expect_warning)
1021 store_log(ps, pp, message, 0 /* warning */);
1022 else
1023 ps->saw_warning = 1;
1024}
1025
1026/* These somewhat odd functions are used when reading an image to ensure that
1027 * the buffer is big enough, the png_structp is for errors.
1028 */
1029/* Return a single row from the correct image. */
1030static png_bytep
Matt Sarett9ea75692016-01-08 13:00:42 -05001031store_image_row(const png_store* ps, png_const_structp pp, int nImage,
Chris Craikb50c2172013-07-29 15:28:30 -07001032 png_uint_32 y)
1033{
1034 png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2;
1035
1036 if (ps->image == NULL)
1037 png_error(pp, "no allocated image");
1038
1039 if (coffset + ps->cb_row + 3 > ps->cb_image)
1040 png_error(pp, "image too small");
1041
1042 return ps->image + coffset;
1043}
1044
1045static void
1046store_image_free(png_store *ps, png_const_structp pp)
1047{
1048 if (ps->image != NULL)
1049 {
1050 png_bytep image = ps->image;
1051
1052 if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
1053 {
1054 if (pp != NULL)
1055 png_error(pp, "png_store image overwrite (1)");
1056 else
1057 store_log(ps, NULL, "png_store image overwrite (2)", 1);
1058 }
1059
1060 ps->image = NULL;
1061 ps->cb_image = 0;
1062 --image;
1063 free(image);
1064 }
1065}
1066
1067static void
1068store_ensure_image(png_store *ps, png_const_structp pp, int nImages,
1069 png_size_t cbRow, png_uint_32 cRows)
1070{
1071 png_size_t cb = nImages * cRows * (cbRow + 5);
1072
1073 if (ps->cb_image < cb)
1074 {
1075 png_bytep image;
1076
1077 store_image_free(ps, pp);
1078
1079 /* The buffer is deliberately mis-aligned. */
1080 image = voidcast(png_bytep, malloc(cb+2));
1081 if (image == NULL)
1082 {
1083 /* Called from the startup - ignore the error for the moment. */
1084 if (pp == NULL)
1085 return;
1086
1087 png_error(pp, "OOM allocating image buffer");
1088 }
1089
1090 /* These magic tags are used to detect overwrites above. */
1091 ++image;
1092 image[-1] = 0xed;
1093 image[cb] = 0xfe;
1094
1095 ps->image = image;
1096 ps->cb_image = cb;
1097 }
1098
1099 /* We have an adequate sized image; lay out the rows. There are 2 bytes at
1100 * the start and three at the end of each (this ensures that the row
1101 * alignment starts out odd - 2+1 and changes for larger images on each row.)
1102 */
1103 ps->cb_row = cbRow;
1104 ps->image_h = cRows;
1105
1106 /* For error checking, the whole buffer is set to 10110010 (0xb2 - 178).
1107 * This deliberately doesn't match the bits in the size test image which are
1108 * outside the image; these are set to 0xff (all 1). To make the row
1109 * comparison work in the 'size' test case the size rows are pre-initialized
1110 * to the same value prior to calling 'standard_row'.
1111 */
1112 memset(ps->image, 178, cb);
1113
1114 /* Then put in the marks. */
1115 while (--nImages >= 0)
1116 {
1117 png_uint_32 y;
1118
1119 for (y=0; y<cRows; ++y)
1120 {
1121 png_bytep row = store_image_row(ps, pp, nImages, y);
1122
1123 /* The markers: */
1124 row[-2] = 190;
1125 row[-1] = 239;
1126 row[cbRow] = 222;
1127 row[cbRow+1] = 173;
1128 row[cbRow+2] = 17;
1129 }
1130 }
1131}
1132
1133#ifdef PNG_READ_SUPPORTED
1134static void
Matt Sarett9ea75692016-01-08 13:00:42 -05001135store_image_check(const png_store* ps, png_const_structp pp, int iImage)
Chris Craikb50c2172013-07-29 15:28:30 -07001136{
1137 png_const_bytep image = ps->image;
1138
1139 if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
1140 png_error(pp, "image overwrite");
1141 else
1142 {
1143 png_size_t cbRow = ps->cb_row;
1144 png_uint_32 rows = ps->image_h;
1145
1146 image += iImage * (cbRow+5) * ps->image_h;
1147
1148 image += 2; /* skip image first row markers */
1149
1150 while (rows-- > 0)
1151 {
1152 if (image[-2] != 190 || image[-1] != 239)
1153 png_error(pp, "row start overwritten");
1154
1155 if (image[cbRow] != 222 || image[cbRow+1] != 173 ||
1156 image[cbRow+2] != 17)
1157 png_error(pp, "row end overwritten");
1158
1159 image += cbRow+5;
1160 }
1161 }
1162}
1163#endif /* PNG_READ_SUPPORTED */
1164
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301165static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07001166store_write(png_structp ppIn, png_bytep pb, png_size_t st)
1167{
1168 png_const_structp pp = ppIn;
1169 png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
1170
1171 if (ps->pwrite != pp)
1172 png_error(pp, "store state damaged");
1173
1174 while (st > 0)
1175 {
1176 size_t cb;
1177
1178 if (ps->writepos >= STORE_BUFFER_SIZE)
1179 store_storenew(ps);
1180
1181 cb = st;
1182
1183 if (cb > STORE_BUFFER_SIZE - ps->writepos)
1184 cb = STORE_BUFFER_SIZE - ps->writepos;
1185
1186 memcpy(ps->new.buffer + ps->writepos, pb, cb);
1187 pb += cb;
1188 st -= cb;
1189 ps->writepos += cb;
1190 }
1191}
1192
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301193static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07001194store_flush(png_structp ppIn)
1195{
1196 UNUSED(ppIn) /*DOES NOTHING*/
1197}
1198
1199#ifdef PNG_READ_SUPPORTED
1200static size_t
1201store_read_buffer_size(png_store *ps)
1202{
1203 /* Return the bytes available for read in the current buffer. */
1204 if (ps->next != &ps->current->data)
1205 return STORE_BUFFER_SIZE;
1206
1207 return ps->current->datacount;
1208}
1209
1210#ifdef PNG_READ_TRANSFORMS_SUPPORTED
1211/* Return total bytes available for read. */
1212static size_t
1213store_read_buffer_avail(png_store *ps)
1214{
1215 if (ps->current != NULL && ps->next != NULL)
1216 {
1217 png_store_buffer *next = &ps->current->data;
1218 size_t cbAvail = ps->current->datacount;
1219
1220 while (next != ps->next && next != NULL)
1221 {
1222 next = next->prev;
1223 cbAvail += STORE_BUFFER_SIZE;
1224 }
1225
1226 if (next != ps->next)
1227 png_error(ps->pread, "buffer read error");
1228
1229 if (cbAvail > ps->readpos)
1230 return cbAvail - ps->readpos;
1231 }
1232
1233 return 0;
1234}
1235#endif
1236
1237static int
1238store_read_buffer_next(png_store *ps)
1239{
1240 png_store_buffer *pbOld = ps->next;
1241 png_store_buffer *pbNew = &ps->current->data;
1242 if (pbOld != pbNew)
1243 {
1244 while (pbNew != NULL && pbNew->prev != pbOld)
1245 pbNew = pbNew->prev;
1246
1247 if (pbNew != NULL)
1248 {
1249 ps->next = pbNew;
1250 ps->readpos = 0;
1251 return 1;
1252 }
1253
1254 png_error(ps->pread, "buffer lost");
1255 }
1256
1257 return 0; /* EOF or error */
1258}
1259
1260/* Need separate implementation and callback to allow use of the same code
1261 * during progressive read, where the io_ptr is set internally by libpng.
1262 */
1263static void
1264store_read_imp(png_store *ps, png_bytep pb, png_size_t st)
1265{
1266 if (ps->current == NULL || ps->next == NULL)
1267 png_error(ps->pread, "store state damaged");
1268
1269 while (st > 0)
1270 {
1271 size_t cbAvail = store_read_buffer_size(ps) - ps->readpos;
1272
1273 if (cbAvail > 0)
1274 {
1275 if (cbAvail > st) cbAvail = st;
1276 memcpy(pb, ps->next->buffer + ps->readpos, cbAvail);
1277 st -= cbAvail;
1278 pb += cbAvail;
1279 ps->readpos += cbAvail;
1280 }
1281
1282 else if (!store_read_buffer_next(ps))
1283 png_error(ps->pread, "read beyond end of file");
1284 }
1285}
1286
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301287static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07001288store_read(png_structp ppIn, png_bytep pb, png_size_t st)
1289{
1290 png_const_structp pp = ppIn;
1291 png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
1292
1293 if (ps == NULL || ps->pread != pp)
1294 png_error(pp, "bad store read call");
1295
1296 store_read_imp(ps, pb, st);
1297}
1298
1299static void
1300store_progressive_read(png_store *ps, png_structp pp, png_infop pi)
1301{
1302 /* Notice that a call to store_read will cause this function to fail because
1303 * readpos will be set.
1304 */
1305 if (ps->pread != pp || ps->current == NULL || ps->next == NULL)
1306 png_error(pp, "store state damaged (progressive)");
1307
1308 do
1309 {
1310 if (ps->readpos != 0)
1311 png_error(pp, "store_read called during progressive read");
1312
1313 png_process_data(pp, pi, ps->next->buffer, store_read_buffer_size(ps));
1314 }
1315 while (store_read_buffer_next(ps));
1316}
1317#endif /* PNG_READ_SUPPORTED */
1318
1319/* The caller must fill this in: */
1320static store_palette_entry *
1321store_write_palette(png_store *ps, int npalette)
1322{
1323 if (ps->pwrite == NULL)
1324 store_log(ps, NULL, "attempt to write palette without write stream", 1);
1325
1326 if (ps->palette != NULL)
1327 png_error(ps->pwrite, "multiple store_write_palette calls");
1328
1329 /* This function can only return NULL if called with '0'! */
1330 if (npalette > 0)
1331 {
1332 ps->palette = voidcast(store_palette_entry*, malloc(npalette *
1333 sizeof *ps->palette));
1334
1335 if (ps->palette == NULL)
1336 png_error(ps->pwrite, "store new palette: OOM");
1337
1338 ps->npalette = npalette;
1339 }
1340
1341 return ps->palette;
1342}
1343
1344#ifdef PNG_READ_SUPPORTED
1345static store_palette_entry *
1346store_current_palette(png_store *ps, int *npalette)
1347{
1348 /* This is an internal error (the call has been made outside a read
1349 * operation.)
1350 */
1351 if (ps->current == NULL)
Matt Sarett9ea75692016-01-08 13:00:42 -05001352 {
Chris Craikb50c2172013-07-29 15:28:30 -07001353 store_log(ps, ps->pread, "no current stream for palette", 1);
Matt Sarett9ea75692016-01-08 13:00:42 -05001354 return NULL;
1355 }
Chris Craikb50c2172013-07-29 15:28:30 -07001356
1357 /* The result may be null if there is no palette. */
1358 *npalette = ps->current->npalette;
1359 return ps->current->palette;
1360}
1361#endif /* PNG_READ_SUPPORTED */
1362
1363/***************************** MEMORY MANAGEMENT*** ***************************/
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301364#ifdef PNG_USER_MEM_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07001365/* A store_memory is simply the header for an allocated block of memory. The
1366 * pointer returned to libpng is just after the end of the header block, the
1367 * allocated memory is followed by a second copy of the 'mark'.
1368 */
1369typedef struct store_memory
1370{
1371 store_pool *pool; /* Originating pool */
1372 struct store_memory *next; /* Singly linked list */
1373 png_alloc_size_t size; /* Size of memory allocated */
1374 png_byte mark[4]; /* ID marker */
1375} store_memory;
1376
1377/* Handle a fatal error in memory allocation. This calls png_error if the
1378 * libpng struct is non-NULL, else it outputs a message and returns. This means
1379 * that a memory problem while libpng is running will abort (png_error) the
1380 * handling of particular file while one in cleanup (after the destroy of the
1381 * struct has returned) will simply keep going and free (or attempt to free)
1382 * all the memory.
1383 */
1384static void
Matt Sarett9ea75692016-01-08 13:00:42 -05001385store_pool_error(png_store *ps, png_const_structp pp, const char *msg)
Chris Craikb50c2172013-07-29 15:28:30 -07001386{
1387 if (pp != NULL)
1388 png_error(pp, msg);
1389
1390 /* Else we have to do it ourselves. png_error eventually calls store_log,
1391 * above. store_log accepts a NULL png_structp - it just changes what gets
1392 * output by store_message.
1393 */
1394 store_log(ps, pp, msg, 1 /* error */);
1395}
1396
1397static void
1398store_memory_free(png_const_structp pp, store_pool *pool, store_memory *memory)
1399{
1400 /* Note that pp may be NULL (see store_pool_delete below), the caller has
1401 * found 'memory' in pool->list *and* unlinked this entry, so this is a valid
1402 * pointer (for sure), but the contents may have been trashed.
1403 */
1404 if (memory->pool != pool)
1405 store_pool_error(pool->store, pp, "memory corrupted (pool)");
1406
1407 else if (memcmp(memory->mark, pool->mark, sizeof memory->mark) != 0)
1408 store_pool_error(pool->store, pp, "memory corrupted (start)");
1409
1410 /* It should be safe to read the size field now. */
1411 else
1412 {
1413 png_alloc_size_t cb = memory->size;
1414
1415 if (cb > pool->max)
1416 store_pool_error(pool->store, pp, "memory corrupted (size)");
1417
1418 else if (memcmp((png_bytep)(memory+1)+cb, pool->mark, sizeof pool->mark)
1419 != 0)
1420 store_pool_error(pool->store, pp, "memory corrupted (end)");
1421
1422 /* Finally give the library a chance to find problems too: */
1423 else
1424 {
1425 pool->current -= cb;
1426 free(memory);
1427 }
1428 }
1429}
1430
1431static void
1432store_pool_delete(png_store *ps, store_pool *pool)
1433{
1434 if (pool->list != NULL)
1435 {
1436 fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
1437 pool == &ps->read_memory_pool ? "read" : "write",
1438 pool == &ps->read_memory_pool ? (ps->current != NULL ?
1439 ps->current->name : "unknown file") : ps->wname);
1440 ++ps->nerrors;
1441
1442 do
1443 {
1444 store_memory *next = pool->list;
1445 pool->list = next->next;
1446 next->next = NULL;
1447
1448 fprintf(stderr, "\t%lu bytes @ %p\n",
Matt Sarett9ea75692016-01-08 13:00:42 -05001449 (unsigned long)next->size, (const void*)(next+1));
Chris Craikb50c2172013-07-29 15:28:30 -07001450 /* The NULL means this will always return, even if the memory is
1451 * corrupted.
1452 */
1453 store_memory_free(NULL, pool, next);
1454 }
1455 while (pool->list != NULL);
1456 }
1457
1458 /* And reset the other fields too for the next time. */
1459 if (pool->max > pool->max_max) pool->max_max = pool->max;
1460 pool->max = 0;
1461 if (pool->current != 0) /* unexpected internal error */
1462 fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
1463 ps->test, pool == &ps->read_memory_pool ? "read" : "write",
1464 pool == &ps->read_memory_pool ? (ps->current != NULL ?
1465 ps->current->name : "unknown file") : ps->wname);
1466 pool->current = 0;
1467
1468 if (pool->limit > pool->max_limit)
1469 pool->max_limit = pool->limit;
1470
1471 pool->limit = 0;
1472
1473 if (pool->total > pool->max_total)
1474 pool->max_total = pool->total;
1475
1476 pool->total = 0;
1477
1478 /* Get a new mark too. */
1479 store_pool_mark(pool->mark);
1480}
1481
1482/* The memory callbacks: */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301483static png_voidp PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07001484store_malloc(png_structp ppIn, png_alloc_size_t cb)
1485{
1486 png_const_structp pp = ppIn;
1487 store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
1488 store_memory *new = voidcast(store_memory*, malloc(cb + (sizeof *new) +
1489 (sizeof pool->mark)));
1490
1491 if (new != NULL)
1492 {
1493 if (cb > pool->max)
1494 pool->max = cb;
1495
1496 pool->current += cb;
1497
1498 if (pool->current > pool->limit)
1499 pool->limit = pool->current;
1500
1501 pool->total += cb;
1502
1503 new->size = cb;
1504 memcpy(new->mark, pool->mark, sizeof new->mark);
1505 memcpy((png_byte*)(new+1) + cb, pool->mark, sizeof pool->mark);
1506 new->pool = pool;
1507 new->next = pool->list;
1508 pool->list = new;
1509 ++new;
1510 }
1511
1512 else
1513 {
1514 /* NOTE: the PNG user malloc function cannot use the png_ptr it is passed
1515 * other than to retrieve the allocation pointer! libpng calls the
1516 * store_malloc callback in two basic cases:
1517 *
1518 * 1) From png_malloc; png_malloc will do a png_error itself if NULL is
1519 * returned.
1520 * 2) From png_struct or png_info structure creation; png_malloc is
1521 * to return so cleanup can be performed.
1522 *
1523 * To handle this store_malloc can log a message, but can't do anything
1524 * else.
1525 */
1526 store_log(pool->store, pp, "out of memory", 1 /* is_error */);
1527 }
1528
1529 return new;
1530}
1531
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301532static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07001533store_free(png_structp ppIn, png_voidp memory)
1534{
1535 png_const_structp pp = ppIn;
1536 store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
1537 store_memory *this = voidcast(store_memory*, memory), **test;
1538
1539 /* Because libpng calls store_free with a dummy png_struct when deleting
1540 * png_struct or png_info via png_destroy_struct_2 it is necessary to check
1541 * the passed in png_structp to ensure it is valid, and not pass it to
1542 * png_error if it is not.
1543 */
1544 if (pp != pool->store->pread && pp != pool->store->pwrite)
1545 pp = NULL;
1546
1547 /* First check that this 'memory' really is valid memory - it must be in the
1548 * pool list. If it is, use the shared memory_free function to free it.
1549 */
1550 --this;
1551 for (test = &pool->list; *test != this; test = &(*test)->next)
1552 {
1553 if (*test == NULL)
1554 {
1555 store_pool_error(pool->store, pp, "bad pointer to free");
1556 return;
1557 }
1558 }
1559
1560 /* Unlink this entry, *test == this. */
1561 *test = this->next;
1562 this->next = NULL;
1563 store_memory_free(pp, pool, this);
1564}
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301565#endif /* PNG_USER_MEM_SUPPORTED */
Chris Craikb50c2172013-07-29 15:28:30 -07001566
1567/* Setup functions. */
1568/* Cleanup when aborting a write or after storing the new file. */
1569static void
1570store_write_reset(png_store *ps)
1571{
1572 if (ps->pwrite != NULL)
1573 {
1574 anon_context(ps);
1575
1576 Try
1577 png_destroy_write_struct(&ps->pwrite, &ps->piwrite);
1578
1579 Catch_anonymous
1580 {
1581 /* memory corruption: continue. */
1582 }
1583
1584 ps->pwrite = NULL;
1585 ps->piwrite = NULL;
1586 }
1587
1588 /* And make sure that all the memory has been freed - this will output
1589 * spurious errors in the case of memory corruption above, but this is safe.
1590 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301591# ifdef PNG_USER_MEM_SUPPORTED
1592 store_pool_delete(ps, &ps->write_memory_pool);
1593# endif
Chris Craikb50c2172013-07-29 15:28:30 -07001594
1595 store_freenew(ps);
1596}
1597
1598/* The following is the main write function, it returns a png_struct and,
1599 * optionally, a png_info suitable for writiing a new PNG file. Use
1600 * store_storefile above to record this file after it has been written. The
1601 * returned libpng structures as destroyed by store_write_reset above.
1602 */
1603static png_structp
Matt Sarett9ea75692016-01-08 13:00:42 -05001604set_store_for_write(png_store *ps, png_infopp ppi, const char *name)
Chris Craikb50c2172013-07-29 15:28:30 -07001605{
1606 anon_context(ps);
1607
1608 Try
1609 {
1610 if (ps->pwrite != NULL)
1611 png_error(ps->pwrite, "write store already in use");
1612
1613 store_write_reset(ps);
1614 safecat(ps->wname, sizeof ps->wname, 0, name);
1615
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301616 /* Don't do the slow memory checks if doing a speed test, also if user
1617 * memory is not supported we can't do it anyway.
1618 */
1619# ifdef PNG_USER_MEM_SUPPORTED
1620 if (!ps->speed)
1621 ps->pwrite = png_create_write_struct_2(PNG_LIBPNG_VER_STRING,
1622 ps, store_error, store_warning, &ps->write_memory_pool,
1623 store_malloc, store_free);
1624
1625 else
1626# endif
Chris Craikb50c2172013-07-29 15:28:30 -07001627 ps->pwrite = png_create_write_struct(PNG_LIBPNG_VER_STRING,
1628 ps, store_error, store_warning);
1629
Chris Craikb50c2172013-07-29 15:28:30 -07001630 png_set_write_fn(ps->pwrite, ps, store_write, store_flush);
1631
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301632# ifdef PNG_SET_OPTION_SUPPORTED
1633 {
1634 int opt;
1635 for (opt=0; opt<ps->noptions; ++opt)
1636 if (png_set_option(ps->pwrite, ps->options[opt].option,
1637 ps->options[opt].setting) == PNG_OPTION_INVALID)
1638 png_error(ps->pwrite, "png option invalid");
1639 }
1640# endif
1641
Chris Craikb50c2172013-07-29 15:28:30 -07001642 if (ppi != NULL)
1643 *ppi = ps->piwrite = png_create_info_struct(ps->pwrite);
1644 }
1645
1646 Catch_anonymous
1647 return NULL;
1648
1649 return ps->pwrite;
1650}
1651
1652/* Cleanup when finished reading (either due to error or in the success case).
1653 * This routine exists even when there is no read support to make the code
1654 * tidier (avoid a mass of ifdefs) and so easier to maintain.
1655 */
1656static void
1657store_read_reset(png_store *ps)
1658{
1659# ifdef PNG_READ_SUPPORTED
1660 if (ps->pread != NULL)
1661 {
1662 anon_context(ps);
1663
1664 Try
1665 png_destroy_read_struct(&ps->pread, &ps->piread, NULL);
1666
1667 Catch_anonymous
1668 {
1669 /* error already output: continue */
1670 }
1671
1672 ps->pread = NULL;
1673 ps->piread = NULL;
1674 }
1675# endif
1676
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301677# ifdef PNG_USER_MEM_SUPPORTED
1678 /* Always do this to be safe. */
1679 store_pool_delete(ps, &ps->read_memory_pool);
1680# endif
Chris Craikb50c2172013-07-29 15:28:30 -07001681
1682 ps->current = NULL;
1683 ps->next = NULL;
1684 ps->readpos = 0;
1685 ps->validated = 0;
1686}
1687
1688#ifdef PNG_READ_SUPPORTED
1689static void
1690store_read_set(png_store *ps, png_uint_32 id)
1691{
1692 png_store_file *pf = ps->saved;
1693
1694 while (pf != NULL)
1695 {
1696 if (pf->id == id)
1697 {
1698 ps->current = pf;
1699 ps->next = NULL;
1700 store_read_buffer_next(ps);
1701 return;
1702 }
1703
1704 pf = pf->next;
1705 }
1706
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301707 {
Chris Craikb50c2172013-07-29 15:28:30 -07001708 size_t pos;
1709 char msg[FILE_NAME_SIZE+64];
1710
1711 pos = standard_name_from_id(msg, sizeof msg, 0, id);
1712 pos = safecat(msg, sizeof msg, pos, ": file not found");
1713 png_error(ps->pread, msg);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301714 }
Chris Craikb50c2172013-07-29 15:28:30 -07001715}
1716
1717/* The main interface for reading a saved file - pass the id number of the file
1718 * to retrieve. Ids must be unique or the earlier file will be hidden. The API
1719 * returns a png_struct and, optionally, a png_info. Both of these will be
1720 * destroyed by store_read_reset above.
1721 */
1722static png_structp
1723set_store_for_read(png_store *ps, png_infopp ppi, png_uint_32 id,
Matt Sarett9ea75692016-01-08 13:00:42 -05001724 const char *name)
Chris Craikb50c2172013-07-29 15:28:30 -07001725{
1726 /* Set the name for png_error */
1727 safecat(ps->test, sizeof ps->test, 0, name);
1728
1729 if (ps->pread != NULL)
1730 png_error(ps->pread, "read store already in use");
1731
1732 store_read_reset(ps);
1733
1734 /* Both the create APIs can return NULL if used in their default mode
1735 * (because there is no other way of handling an error because the jmp_buf
1736 * by default is stored in png_struct and that has not been allocated!)
1737 * However, given that store_error works correctly in these circumstances
1738 * we don't ever expect NULL in this program.
1739 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301740# ifdef PNG_USER_MEM_SUPPORTED
1741 if (!ps->speed)
1742 ps->pread = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, ps,
1743 store_error, store_warning, &ps->read_memory_pool, store_malloc,
1744 store_free);
Chris Craikb50c2172013-07-29 15:28:30 -07001745
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301746 else
1747# endif
1748 ps->pread = png_create_read_struct(PNG_LIBPNG_VER_STRING, ps, store_error,
1749 store_warning);
Chris Craikb50c2172013-07-29 15:28:30 -07001750
1751 if (ps->pread == NULL)
1752 {
1753 struct exception_context *the_exception_context = &ps->exception_context;
1754
1755 store_log(ps, NULL, "png_create_read_struct returned NULL (unexpected)",
1756 1 /*error*/);
1757
1758 Throw ps;
1759 }
1760
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301761# ifdef PNG_SET_OPTION_SUPPORTED
1762 {
1763 int opt;
1764 for (opt=0; opt<ps->noptions; ++opt)
1765 if (png_set_option(ps->pread, ps->options[opt].option,
1766 ps->options[opt].setting) == PNG_OPTION_INVALID)
1767 png_error(ps->pread, "png option invalid");
1768 }
1769# endif
1770
Chris Craikb50c2172013-07-29 15:28:30 -07001771 store_read_set(ps, id);
1772
1773 if (ppi != NULL)
1774 *ppi = ps->piread = png_create_info_struct(ps->pread);
1775
1776 return ps->pread;
1777}
1778#endif /* PNG_READ_SUPPORTED */
1779
1780/* The overall cleanup of a store simply calls the above then removes all the
1781 * saved files. This does not delete the store itself.
1782 */
1783static void
1784store_delete(png_store *ps)
1785{
1786 store_write_reset(ps);
1787 store_read_reset(ps);
1788 store_freefile(&ps->saved);
1789 store_image_free(ps, NULL);
1790}
1791
1792/*********************** PNG FILE MODIFICATION ON READ ************************/
1793/* Files may be modified on read. The following structure contains a complete
1794 * png_store together with extra members to handle modification and a special
1795 * read callback for libpng. To use this the 'modifications' field must be set
1796 * to a list of png_modification structures that actually perform the
1797 * modification, otherwise a png_modifier is functionally equivalent to a
1798 * png_store. There is a special read function, set_modifier_for_read, which
1799 * replaces set_store_for_read.
1800 */
1801typedef enum modifier_state
1802{
1803 modifier_start, /* Initial value */
1804 modifier_signature, /* Have a signature */
1805 modifier_IHDR /* Have an IHDR */
1806} modifier_state;
1807
1808typedef struct CIE_color
1809{
1810 /* A single CIE tristimulus value, representing the unique response of a
1811 * standard observer to a variety of light spectra. The observer recognizes
1812 * all spectra that produce this response as the same color, therefore this
1813 * is effectively a description of a color.
1814 */
1815 double X, Y, Z;
1816} CIE_color;
1817
1818typedef struct color_encoding
1819{
1820 /* A description of an (R,G,B) encoding of color (as defined above); this
1821 * includes the actual colors of the (R,G,B) triples (1,0,0), (0,1,0) and
1822 * (0,0,1) plus an encoding value that is used to encode the linear
1823 * components R, G and B to give the actual values R^gamma, G^gamma and
1824 * B^gamma that are stored.
1825 */
1826 double gamma; /* Encoding (file) gamma of space */
1827 CIE_color red, green, blue; /* End points */
1828} color_encoding;
1829
1830#ifdef PNG_READ_SUPPORTED
Matt Sarett9ea75692016-01-08 13:00:42 -05001831#if defined PNG_READ_TRANSFORMS_SUPPORTED && defined PNG_READ_cHRM_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07001832static double
1833chromaticity_x(CIE_color c)
1834{
1835 return c.X / (c.X + c.Y + c.Z);
1836}
1837
1838static double
1839chromaticity_y(CIE_color c)
1840{
1841 return c.Y / (c.X + c.Y + c.Z);
1842}
1843
1844static CIE_color
Matt Sarett9ea75692016-01-08 13:00:42 -05001845white_point(const color_encoding *encoding)
Chris Craikb50c2172013-07-29 15:28:30 -07001846{
1847 CIE_color white;
1848
1849 white.X = encoding->red.X + encoding->green.X + encoding->blue.X;
1850 white.Y = encoding->red.Y + encoding->green.Y + encoding->blue.Y;
1851 white.Z = encoding->red.Z + encoding->green.Z + encoding->blue.Z;
1852
1853 return white;
1854}
Matt Sarett9ea75692016-01-08 13:00:42 -05001855#endif /* READ_TRANSFORMS && READ_cHRM */
Chris Craikb50c2172013-07-29 15:28:30 -07001856
1857#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
1858static void
1859normalize_color_encoding(color_encoding *encoding)
1860{
Matt Sarett9ea75692016-01-08 13:00:42 -05001861 const double whiteY = encoding->red.Y + encoding->green.Y +
Chris Craikb50c2172013-07-29 15:28:30 -07001862 encoding->blue.Y;
1863
1864 if (whiteY != 1)
1865 {
1866 encoding->red.X /= whiteY;
1867 encoding->red.Y /= whiteY;
1868 encoding->red.Z /= whiteY;
1869 encoding->green.X /= whiteY;
1870 encoding->green.Y /= whiteY;
1871 encoding->green.Z /= whiteY;
1872 encoding->blue.X /= whiteY;
1873 encoding->blue.Y /= whiteY;
1874 encoding->blue.Z /= whiteY;
1875 }
1876}
1877#endif
1878
Matt Sarett9ea75692016-01-08 13:00:42 -05001879#ifdef PNG_READ_TRANSFORMS_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07001880static size_t
1881safecat_color_encoding(char *buffer, size_t bufsize, size_t pos,
Matt Sarett9ea75692016-01-08 13:00:42 -05001882 const color_encoding *e, double encoding_gamma)
Chris Craikb50c2172013-07-29 15:28:30 -07001883{
1884 if (e != 0)
1885 {
1886 if (encoding_gamma != 0)
1887 pos = safecat(buffer, bufsize, pos, "(");
1888 pos = safecat(buffer, bufsize, pos, "R(");
1889 pos = safecatd(buffer, bufsize, pos, e->red.X, 4);
1890 pos = safecat(buffer, bufsize, pos, ",");
1891 pos = safecatd(buffer, bufsize, pos, e->red.Y, 4);
1892 pos = safecat(buffer, bufsize, pos, ",");
1893 pos = safecatd(buffer, bufsize, pos, e->red.Z, 4);
1894 pos = safecat(buffer, bufsize, pos, "),G(");
1895 pos = safecatd(buffer, bufsize, pos, e->green.X, 4);
1896 pos = safecat(buffer, bufsize, pos, ",");
1897 pos = safecatd(buffer, bufsize, pos, e->green.Y, 4);
1898 pos = safecat(buffer, bufsize, pos, ",");
1899 pos = safecatd(buffer, bufsize, pos, e->green.Z, 4);
1900 pos = safecat(buffer, bufsize, pos, "),B(");
1901 pos = safecatd(buffer, bufsize, pos, e->blue.X, 4);
1902 pos = safecat(buffer, bufsize, pos, ",");
1903 pos = safecatd(buffer, bufsize, pos, e->blue.Y, 4);
1904 pos = safecat(buffer, bufsize, pos, ",");
1905 pos = safecatd(buffer, bufsize, pos, e->blue.Z, 4);
1906 pos = safecat(buffer, bufsize, pos, ")");
1907 if (encoding_gamma != 0)
1908 pos = safecat(buffer, bufsize, pos, ")");
1909 }
1910
1911 if (encoding_gamma != 0)
1912 {
1913 pos = safecat(buffer, bufsize, pos, "^");
1914 pos = safecatd(buffer, bufsize, pos, encoding_gamma, 5);
1915 }
1916
1917 return pos;
1918}
Matt Sarett9ea75692016-01-08 13:00:42 -05001919#endif /* READ_TRANSFORMS */
Chris Craikb50c2172013-07-29 15:28:30 -07001920#endif /* PNG_READ_SUPPORTED */
1921
1922typedef struct png_modifier
1923{
1924 png_store this; /* I am a png_store */
1925 struct png_modification *modifications; /* Changes to make */
1926
1927 modifier_state state; /* My state */
1928
1929 /* Information from IHDR: */
1930 png_byte bit_depth; /* From IHDR */
1931 png_byte colour_type; /* From IHDR */
1932
1933 /* While handling PLTE, IDAT and IEND these chunks may be pended to allow
1934 * other chunks to be inserted.
1935 */
1936 png_uint_32 pending_len;
1937 png_uint_32 pending_chunk;
1938
1939 /* Test values */
1940 double *gammas;
1941 unsigned int ngammas;
1942 unsigned int ngamma_tests; /* Number of gamma tests to run*/
1943 double current_gamma; /* 0 if not set */
Matt Sarett9ea75692016-01-08 13:00:42 -05001944 const color_encoding *encodings;
Chris Craikb50c2172013-07-29 15:28:30 -07001945 unsigned int nencodings;
Matt Sarett9ea75692016-01-08 13:00:42 -05001946 const color_encoding *current_encoding; /* If an encoding has been set */
Chris Craikb50c2172013-07-29 15:28:30 -07001947 unsigned int encoding_counter; /* For iteration */
1948 int encoding_ignored; /* Something overwrote it */
1949
1950 /* Control variables used to iterate through possible encodings, the
1951 * following must be set to 0 and tested by the function that uses the
1952 * png_modifier because the modifier only sets it to 1 (true.)
1953 */
1954 unsigned int repeat :1; /* Repeat this transform test. */
1955 unsigned int test_uses_encoding :1;
1956
Matt Sarett9ea75692016-01-08 13:00:42 -05001957 /* Lowest sbit to test (pre-1.7 libpng fails for sbit < 8) */
Chris Craikb50c2172013-07-29 15:28:30 -07001958 png_byte sbitlow;
1959
1960 /* Error control - these are the limits on errors accepted by the gamma tests
1961 * below.
1962 */
1963 double maxout8; /* Maximum output value error */
1964 double maxabs8; /* Absolute sample error 0..1 */
1965 double maxcalc8; /* Absolute sample error 0..1 */
1966 double maxpc8; /* Percentage sample error 0..100% */
1967 double maxout16; /* Maximum output value error */
1968 double maxabs16; /* Absolute sample error 0..1 */
1969 double maxcalc16;/* Absolute sample error 0..1 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301970 double maxcalcG; /* Absolute sample error 0..1 */
Chris Craikb50c2172013-07-29 15:28:30 -07001971 double maxpc16; /* Percentage sample error 0..100% */
1972
1973 /* This is set by transforms that need to allow a higher limit, it is an
1974 * internal check on pngvalid to ensure that the calculated error limits are
1975 * not ridiculous; without this it is too easy to make a mistake in pngvalid
1976 * that allows any value through.
1977 */
1978 double limit; /* limit on error values, normally 4E-3 */
1979
1980 /* Log limits - values above this are logged, but not necessarily
1981 * warned.
1982 */
1983 double log8; /* Absolute error in 8 bits to log */
1984 double log16; /* Absolute error in 16 bits to log */
1985
1986 /* Logged 8 and 16 bit errors ('output' values): */
1987 double error_gray_2;
1988 double error_gray_4;
1989 double error_gray_8;
1990 double error_gray_16;
1991 double error_color_8;
1992 double error_color_16;
1993 double error_indexed;
1994
1995 /* Flags: */
1996 /* Whether to call png_read_update_info, not png_read_start_image, and how
1997 * many times to call it.
1998 */
1999 int use_update_info;
2000
2001 /* Whether or not to interlace. */
2002 int interlace_type :9; /* int, but must store '1' */
2003
2004 /* Run the standard tests? */
2005 unsigned int test_standard :1;
2006
2007 /* Run the odd-sized image and interlace read/write tests? */
2008 unsigned int test_size :1;
2009
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302010 /* Run tests on reading with a combination of transforms, */
Chris Craikb50c2172013-07-29 15:28:30 -07002011 unsigned int test_transform :1;
Matt Sarett9ea75692016-01-08 13:00:42 -05002012 unsigned int test_tRNS :1; /* Includes tRNS images */
Chris Craikb50c2172013-07-29 15:28:30 -07002013
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302014 /* When to use the use_input_precision option, this controls the gamma
2015 * validation code checks. If set any value that is within the transformed
2016 * range input-.5 to input+.5 will be accepted, otherwise the value must be
2017 * within the normal limits. It should not be necessary to set this; the
2018 * result should always be exact within the permitted error limits.
2019 */
Chris Craikb50c2172013-07-29 15:28:30 -07002020 unsigned int use_input_precision :1;
2021 unsigned int use_input_precision_sbit :1;
2022 unsigned int use_input_precision_16to8 :1;
2023
2024 /* If set assume that the calculation bit depth is set by the input
2025 * precision, not the output precision.
2026 */
2027 unsigned int calculations_use_input_precision :1;
2028
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302029 /* If set assume that the calculations are done in 16 bits even if the sample
2030 * depth is 8 bits.
Chris Craikb50c2172013-07-29 15:28:30 -07002031 */
2032 unsigned int assume_16_bit_calculations :1;
2033
2034 /* Which gamma tests to run: */
2035 unsigned int test_gamma_threshold :1;
2036 unsigned int test_gamma_transform :1; /* main tests */
2037 unsigned int test_gamma_sbit :1;
2038 unsigned int test_gamma_scale16 :1;
2039 unsigned int test_gamma_background :1;
2040 unsigned int test_gamma_alpha_mode :1;
2041 unsigned int test_gamma_expand16 :1;
2042 unsigned int test_exhaustive :1;
2043
Matt Sarett9ea75692016-01-08 13:00:42 -05002044 /* Whether or not to run the low-bit-depth grayscale tests. This fails on
2045 * gamma images in some cases because of gross inaccuracies in the grayscale
2046 * gamma handling for low bit depth.
2047 */
2048 unsigned int test_lbg :1;
2049 unsigned int test_lbg_gamma_threshold :1;
2050 unsigned int test_lbg_gamma_transform :1;
2051 unsigned int test_lbg_gamma_sbit :1;
2052 unsigned int test_lbg_gamma_composition :1;
2053
Chris Craikb50c2172013-07-29 15:28:30 -07002054 unsigned int log :1; /* Log max error */
2055
2056 /* Buffer information, the buffer size limits the size of the chunks that can
2057 * be modified - they must fit (including header and CRC) into the buffer!
2058 */
2059 size_t flush; /* Count of bytes to flush */
2060 size_t buffer_count; /* Bytes in buffer */
2061 size_t buffer_position; /* Position in buffer */
2062 png_byte buffer[1024];
2063} png_modifier;
2064
2065/* This returns true if the test should be stopped now because it has already
2066 * failed and it is running silently.
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302067 */
Chris Craikb50c2172013-07-29 15:28:30 -07002068static int fail(png_modifier *pm)
2069{
2070 return !pm->log && !pm->this.verbose && (pm->this.nerrors > 0 ||
2071 (pm->this.treat_warnings_as_errors && pm->this.nwarnings > 0));
2072}
2073
2074static void
2075modifier_init(png_modifier *pm)
2076{
2077 memset(pm, 0, sizeof *pm);
2078 store_init(&pm->this);
2079 pm->modifications = NULL;
2080 pm->state = modifier_start;
2081 pm->sbitlow = 1U;
2082 pm->ngammas = 0;
2083 pm->ngamma_tests = 0;
2084 pm->gammas = 0;
2085 pm->current_gamma = 0;
2086 pm->encodings = 0;
2087 pm->nencodings = 0;
2088 pm->current_encoding = 0;
2089 pm->encoding_counter = 0;
2090 pm->encoding_ignored = 0;
2091 pm->repeat = 0;
2092 pm->test_uses_encoding = 0;
2093 pm->maxout8 = pm->maxpc8 = pm->maxabs8 = pm->maxcalc8 = 0;
2094 pm->maxout16 = pm->maxpc16 = pm->maxabs16 = pm->maxcalc16 = 0;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302095 pm->maxcalcG = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07002096 pm->limit = 4E-3;
2097 pm->log8 = pm->log16 = 0; /* Means 'off' */
2098 pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = 0;
2099 pm->error_gray_16 = pm->error_color_8 = pm->error_color_16 = 0;
2100 pm->error_indexed = 0;
2101 pm->use_update_info = 0;
2102 pm->interlace_type = PNG_INTERLACE_NONE;
2103 pm->test_standard = 0;
2104 pm->test_size = 0;
2105 pm->test_transform = 0;
Matt Sarett9ea75692016-01-08 13:00:42 -05002106# ifdef PNG_WRITE_tRNS_SUPPORTED
2107 pm->test_tRNS = 1;
2108# else
2109 pm->test_tRNS = 0;
2110# endif
Chris Craikb50c2172013-07-29 15:28:30 -07002111 pm->use_input_precision = 0;
2112 pm->use_input_precision_sbit = 0;
2113 pm->use_input_precision_16to8 = 0;
2114 pm->calculations_use_input_precision = 0;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302115 pm->assume_16_bit_calculations = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07002116 pm->test_gamma_threshold = 0;
2117 pm->test_gamma_transform = 0;
2118 pm->test_gamma_sbit = 0;
2119 pm->test_gamma_scale16 = 0;
2120 pm->test_gamma_background = 0;
2121 pm->test_gamma_alpha_mode = 0;
2122 pm->test_gamma_expand16 = 0;
Matt Sarett9ea75692016-01-08 13:00:42 -05002123 pm->test_lbg = 1;
2124 pm->test_lbg_gamma_threshold = 1;
2125 pm->test_lbg_gamma_transform = 1;
2126 pm->test_lbg_gamma_sbit = 1;
2127 pm->test_lbg_gamma_composition = 1;
Chris Craikb50c2172013-07-29 15:28:30 -07002128 pm->test_exhaustive = 0;
2129 pm->log = 0;
2130
2131 /* Rely on the memset for all the other fields - there are no pointers */
2132}
2133
2134#ifdef PNG_READ_TRANSFORMS_SUPPORTED
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302135
2136/* This controls use of checks that explicitly know how libpng digitizes the
2137 * samples in calculations; setting this circumvents simple error limit checking
2138 * in the rgb_to_gray check, replacing it with an exact copy of the libpng 1.5
2139 * algorithm.
2140 */
2141#define DIGITIZE PNG_LIBPNG_VER < 10700
2142
Chris Craikb50c2172013-07-29 15:28:30 -07002143/* If pm->calculations_use_input_precision is set then operations will happen
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302144 * with the precision of the input, not the precision of the output depth.
Chris Craikb50c2172013-07-29 15:28:30 -07002145 *
2146 * If pm->assume_16_bit_calculations is set then even 8 bit calculations use 16
2147 * bit precision. This only affects those of the following limits that pertain
2148 * to a calculation - not a digitization operation - unless the following API is
2149 * called directly.
2150 */
2151#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302152#if DIGITIZE
2153static double digitize(double value, int depth, int do_round)
Chris Craikb50c2172013-07-29 15:28:30 -07002154{
2155 /* 'value' is in the range 0 to 1, the result is the same value rounded to a
2156 * multiple of the digitization factor - 8 or 16 bits depending on both the
2157 * sample depth and the 'assume' setting. Digitization is normally by
2158 * rounding and 'do_round' should be 1, if it is 0 the digitized value will
2159 * be truncated.
2160 */
Matt Sarett9ea75692016-01-08 13:00:42 -05002161 const unsigned int digitization_factor = (1U << depth) -1;
Chris Craikb50c2172013-07-29 15:28:30 -07002162
2163 /* Limiting the range is done as a convenience to the caller - it's easier to
2164 * do it once here than every time at the call site.
2165 */
2166 if (value <= 0)
2167 value = 0;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302168
Chris Craikb50c2172013-07-29 15:28:30 -07002169 else if (value >= 1)
2170 value = 1;
2171
2172 value *= digitization_factor;
2173 if (do_round) value += .5;
2174 return floor(value)/digitization_factor;
2175}
2176#endif
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302177#endif /* RGB_TO_GRAY */
Chris Craikb50c2172013-07-29 15:28:30 -07002178
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302179#ifdef PNG_READ_GAMMA_SUPPORTED
Matt Sarett9ea75692016-01-08 13:00:42 -05002180static double abserr(const png_modifier *pm, int in_depth, int out_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07002181{
2182 /* Absolute error permitted in linear values - affected by the bit depth of
2183 * the calculations.
2184 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302185 if (pm->assume_16_bit_calculations ||
2186 (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
Chris Craikb50c2172013-07-29 15:28:30 -07002187 return pm->maxabs16;
2188 else
2189 return pm->maxabs8;
2190}
Chris Craikb50c2172013-07-29 15:28:30 -07002191
Matt Sarett9ea75692016-01-08 13:00:42 -05002192static double calcerr(const png_modifier *pm, int in_depth, int out_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07002193{
2194 /* Error in the linear composition arithmetic - only relevant when
2195 * composition actually happens (0 < alpha < 1).
2196 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302197 if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
Chris Craikb50c2172013-07-29 15:28:30 -07002198 return pm->maxcalc16;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302199 else if (pm->assume_16_bit_calculations)
2200 return pm->maxcalcG;
Chris Craikb50c2172013-07-29 15:28:30 -07002201 else
2202 return pm->maxcalc8;
2203}
2204
Matt Sarett9ea75692016-01-08 13:00:42 -05002205static double pcerr(const png_modifier *pm, int in_depth, int out_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07002206{
2207 /* Percentage error permitted in the linear values. Note that the specified
2208 * value is a percentage but this routine returns a simple number.
2209 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302210 if (pm->assume_16_bit_calculations ||
2211 (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
Chris Craikb50c2172013-07-29 15:28:30 -07002212 return pm->maxpc16 * .01;
2213 else
2214 return pm->maxpc8 * .01;
2215}
2216
2217/* Output error - the error in the encoded value. This is determined by the
2218 * digitization of the output so can be +/-0.5 in the actual output value. In
2219 * the expand_16 case with the current code in libpng the expand happens after
2220 * all the calculations are done in 8 bit arithmetic, so even though the output
2221 * depth is 16 the output error is determined by the 8 bit calculation.
2222 *
2223 * This limit is not determined by the bit depth of internal calculations.
2224 *
2225 * The specified parameter does *not* include the base .5 digitization error but
2226 * it is added here.
2227 */
Matt Sarett9ea75692016-01-08 13:00:42 -05002228static double outerr(const png_modifier *pm, int in_depth, int out_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07002229{
2230 /* There is a serious error in the 2 and 4 bit grayscale transform because
2231 * the gamma table value (8 bits) is simply shifted, not rounded, so the
2232 * error in 4 bit grayscale gamma is up to the value below. This is a hack
2233 * to allow pngvalid to succeed:
2234 *
2235 * TODO: fix this in libpng
2236 */
2237 if (out_depth == 2)
2238 return .73182-.5;
2239
2240 if (out_depth == 4)
2241 return .90644-.5;
2242
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302243 if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
Chris Craikb50c2172013-07-29 15:28:30 -07002244 return pm->maxout16;
2245
2246 /* This is the case where the value was calculated at 8-bit precision then
2247 * scaled to 16 bits.
2248 */
2249 else if (out_depth == 16)
2250 return pm->maxout8 * 257;
2251
2252 else
2253 return pm->maxout8;
2254}
2255
2256/* This does the same thing as the above however it returns the value to log,
2257 * rather than raising a warning. This is useful for debugging to track down
2258 * exactly what set of parameters cause high error values.
2259 */
Matt Sarett9ea75692016-01-08 13:00:42 -05002260static double outlog(const png_modifier *pm, int in_depth, int out_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07002261{
2262 /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535)
2263 * and so must be adjusted for low bit depth grayscale:
2264 */
2265 if (out_depth <= 8)
2266 {
2267 if (pm->log8 == 0) /* switched off */
2268 return 256;
2269
2270 if (out_depth < 8)
2271 return pm->log8 / 255 * ((1<<out_depth)-1);
2272
2273 return pm->log8;
2274 }
2275
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302276 if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
Chris Craikb50c2172013-07-29 15:28:30 -07002277 {
2278 if (pm->log16 == 0)
2279 return 65536;
2280
2281 return pm->log16;
2282 }
2283
2284 /* This is the case where the value was calculated at 8-bit precision then
2285 * scaled to 16 bits.
2286 */
2287 if (pm->log8 == 0)
2288 return 65536;
2289
2290 return pm->log8 * 257;
2291}
2292
2293/* This complements the above by providing the appropriate quantization for the
2294 * final value. Normally this would just be quantization to an integral value,
2295 * but in the 8 bit calculation case it's actually quantization to a multiple of
2296 * 257!
2297 */
Matt Sarett9ea75692016-01-08 13:00:42 -05002298static int output_quantization_factor(const png_modifier *pm, int in_depth,
Chris Craikb50c2172013-07-29 15:28:30 -07002299 int out_depth)
2300{
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302301 if (out_depth == 16 && in_depth != 16 &&
2302 pm->calculations_use_input_precision)
Chris Craikb50c2172013-07-29 15:28:30 -07002303 return 257;
2304 else
2305 return 1;
2306}
2307#endif /* PNG_READ_GAMMA_SUPPORTED */
2308
2309/* One modification structure must be provided for each chunk to be modified (in
2310 * fact more than one can be provided if multiple separate changes are desired
2311 * for a single chunk.) Modifications include adding a new chunk when a
2312 * suitable chunk does not exist.
2313 *
2314 * The caller of modify_fn will reset the CRC of the chunk and record 'modified'
2315 * or 'added' as appropriate if the modify_fn returns 1 (true). If the
2316 * modify_fn is NULL the chunk is simply removed.
2317 */
2318typedef struct png_modification
2319{
2320 struct png_modification *next;
2321 png_uint_32 chunk;
2322
2323 /* If the following is NULL all matching chunks will be removed: */
2324 int (*modify_fn)(struct png_modifier *pm,
2325 struct png_modification *me, int add);
2326
2327 /* If the following is set to PLTE, IDAT or IEND and the chunk has not been
2328 * found and modified (and there is a modify_fn) the modify_fn will be called
2329 * to add the chunk before the relevant chunk.
2330 */
2331 png_uint_32 add;
2332 unsigned int modified :1; /* Chunk was modified */
2333 unsigned int added :1; /* Chunk was added */
2334 unsigned int removed :1; /* Chunk was removed */
2335} png_modification;
2336
2337static void
2338modification_reset(png_modification *pmm)
2339{
2340 if (pmm != NULL)
2341 {
2342 pmm->modified = 0;
2343 pmm->added = 0;
2344 pmm->removed = 0;
2345 modification_reset(pmm->next);
2346 }
2347}
2348
2349static void
2350modification_init(png_modification *pmm)
2351{
2352 memset(pmm, 0, sizeof *pmm);
2353 pmm->next = NULL;
2354 pmm->chunk = 0;
2355 pmm->modify_fn = NULL;
2356 pmm->add = 0;
2357 modification_reset(pmm);
2358}
2359
2360#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
2361static void
Matt Sarett9ea75692016-01-08 13:00:42 -05002362modifier_current_encoding(const png_modifier *pm, color_encoding *ce)
Chris Craikb50c2172013-07-29 15:28:30 -07002363{
2364 if (pm->current_encoding != 0)
2365 *ce = *pm->current_encoding;
2366
2367 else
2368 memset(ce, 0, sizeof *ce);
2369
2370 ce->gamma = pm->current_gamma;
2371}
2372#endif
2373
Matt Sarett9ea75692016-01-08 13:00:42 -05002374#ifdef PNG_READ_TRANSFORMS_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07002375static size_t
2376safecat_current_encoding(char *buffer, size_t bufsize, size_t pos,
Matt Sarett9ea75692016-01-08 13:00:42 -05002377 const png_modifier *pm)
Chris Craikb50c2172013-07-29 15:28:30 -07002378{
2379 pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding,
2380 pm->current_gamma);
2381
2382 if (pm->encoding_ignored)
2383 pos = safecat(buffer, bufsize, pos, "[overridden]");
2384
2385 return pos;
2386}
Matt Sarett9ea75692016-01-08 13:00:42 -05002387#endif
Chris Craikb50c2172013-07-29 15:28:30 -07002388
2389/* Iterate through the usefully testable color encodings. An encoding is one
2390 * of:
2391 *
2392 * 1) Nothing (no color space, no gamma).
2393 * 2) Just a gamma value from the gamma array (including 1.0)
2394 * 3) A color space from the encodings array with the corresponding gamma.
2395 * 4) The same, but with gamma 1.0 (only really useful with 16 bit calculations)
2396 *
2397 * The iterator selects these in turn, the randomizer selects one at random,
2398 * which is used depends on the setting of the 'test_exhaustive' flag. Notice
2399 * that this function changes the colour space encoding so it must only be
2400 * called on completion of the previous test. This is what 'modifier_reset'
2401 * does, below.
2402 *
2403 * After the function has been called the 'repeat' flag will still be set; the
2404 * caller of modifier_reset must reset it at the start of each run of the test!
2405 */
2406static unsigned int
Matt Sarett9ea75692016-01-08 13:00:42 -05002407modifier_total_encodings(const png_modifier *pm)
Chris Craikb50c2172013-07-29 15:28:30 -07002408{
2409 return 1 + /* (1) nothing */
2410 pm->ngammas + /* (2) gamma values to test */
2411 pm->nencodings + /* (3) total number of encodings */
2412 /* The following test only works after the first time through the
2413 * png_modifier code because 'bit_depth' is set when the IHDR is read.
2414 * modifier_reset, below, preserves the setting until after it has called
2415 * the iterate function (also below.)
2416 *
2417 * For this reason do not rely on this function outside a call to
2418 * modifier_reset.
2419 */
2420 ((pm->bit_depth == 16 || pm->assume_16_bit_calculations) ?
2421 pm->nencodings : 0); /* (4) encodings with gamma == 1.0 */
2422}
2423
2424static void
2425modifier_encoding_iterate(png_modifier *pm)
2426{
2427 if (!pm->repeat && /* Else something needs the current encoding again. */
2428 pm->test_uses_encoding) /* Some transform is encoding dependent */
2429 {
2430 if (pm->test_exhaustive)
2431 {
2432 if (++pm->encoding_counter >= modifier_total_encodings(pm))
2433 pm->encoding_counter = 0; /* This will stop the repeat */
2434 }
2435
2436 else
2437 {
2438 /* Not exhaustive - choose an encoding at random; generate a number in
2439 * the range 1..(max-1), so the result is always non-zero:
2440 */
2441 if (pm->encoding_counter == 0)
2442 pm->encoding_counter = random_mod(modifier_total_encodings(pm)-1)+1;
2443 else
2444 pm->encoding_counter = 0;
2445 }
2446
2447 if (pm->encoding_counter > 0)
2448 pm->repeat = 1;
2449 }
2450
2451 else if (!pm->repeat)
2452 pm->encoding_counter = 0;
2453}
2454
2455static void
2456modifier_reset(png_modifier *pm)
2457{
2458 store_read_reset(&pm->this);
2459 pm->limit = 4E-3;
2460 pm->pending_len = pm->pending_chunk = 0;
2461 pm->flush = pm->buffer_count = pm->buffer_position = 0;
2462 pm->modifications = NULL;
2463 pm->state = modifier_start;
2464 modifier_encoding_iterate(pm);
2465 /* The following must be set in the next run. In particular
2466 * test_uses_encodings must be set in the _ini function of each transform
2467 * that looks at the encodings. (Not the 'add' function!)
2468 */
2469 pm->test_uses_encoding = 0;
2470 pm->current_gamma = 0;
2471 pm->current_encoding = 0;
2472 pm->encoding_ignored = 0;
2473 /* These only become value after IHDR is read: */
2474 pm->bit_depth = pm->colour_type = 0;
2475}
2476
2477/* The following must be called before anything else to get the encoding set up
2478 * on the modifier. In particular it must be called before the transform init
2479 * functions are called.
2480 */
2481static void
2482modifier_set_encoding(png_modifier *pm)
2483{
2484 /* Set the encoding to the one specified by the current encoding counter,
2485 * first clear out all the settings - this corresponds to an encoding_counter
2486 * of 0.
2487 */
2488 pm->current_gamma = 0;
2489 pm->current_encoding = 0;
2490 pm->encoding_ignored = 0; /* not ignored yet - happens in _ini functions. */
2491
2492 /* Now, if required, set the gamma and encoding fields. */
2493 if (pm->encoding_counter > 0)
2494 {
2495 /* The gammas[] array is an array of screen gammas, not encoding gammas,
2496 * so we need the inverse:
2497 */
2498 if (pm->encoding_counter <= pm->ngammas)
2499 pm->current_gamma = 1/pm->gammas[pm->encoding_counter-1];
2500
2501 else
2502 {
2503 unsigned int i = pm->encoding_counter - pm->ngammas;
2504
2505 if (i >= pm->nencodings)
2506 {
2507 i %= pm->nencodings;
2508 pm->current_gamma = 1; /* Linear, only in the 16 bit case */
2509 }
2510
2511 else
2512 pm->current_gamma = pm->encodings[i].gamma;
2513
2514 pm->current_encoding = pm->encodings + i;
2515 }
2516 }
2517}
2518
2519/* Enquiry functions to find out what is set. Notice that there is an implicit
2520 * assumption below that the first encoding in the list is the one for sRGB.
2521 */
2522static int
Matt Sarett9ea75692016-01-08 13:00:42 -05002523modifier_color_encoding_is_sRGB(const png_modifier *pm)
Chris Craikb50c2172013-07-29 15:28:30 -07002524{
2525 return pm->current_encoding != 0 && pm->current_encoding == pm->encodings &&
2526 pm->current_encoding->gamma == pm->current_gamma;
2527}
2528
2529static int
Matt Sarett9ea75692016-01-08 13:00:42 -05002530modifier_color_encoding_is_set(const png_modifier *pm)
Chris Craikb50c2172013-07-29 15:28:30 -07002531{
2532 return pm->current_gamma != 0;
2533}
2534
2535/* Convenience macros. */
2536#define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d))
2537#define CHUNK_IHDR CHUNK(73,72,68,82)
2538#define CHUNK_PLTE CHUNK(80,76,84,69)
2539#define CHUNK_IDAT CHUNK(73,68,65,84)
2540#define CHUNK_IEND CHUNK(73,69,78,68)
2541#define CHUNK_cHRM CHUNK(99,72,82,77)
2542#define CHUNK_gAMA CHUNK(103,65,77,65)
2543#define CHUNK_sBIT CHUNK(115,66,73,84)
2544#define CHUNK_sRGB CHUNK(115,82,71,66)
2545
2546/* The guts of modification are performed during a read. */
2547static void
2548modifier_crc(png_bytep buffer)
2549{
2550 /* Recalculate the chunk CRC - a complete chunk must be in
2551 * the buffer, at the start.
2552 */
2553 uInt datalen = png_get_uint_32(buffer);
2554 uLong crc = crc32(0, buffer+4, datalen+4);
2555 /* The cast to png_uint_32 is safe because a crc32 is always a 32 bit value.
2556 */
2557 png_save_uint_32(buffer+datalen+8, (png_uint_32)crc);
2558}
2559
2560static void
2561modifier_setbuffer(png_modifier *pm)
2562{
2563 modifier_crc(pm->buffer);
2564 pm->buffer_count = png_get_uint_32(pm->buffer)+12;
2565 pm->buffer_position = 0;
2566}
2567
2568/* Separate the callback into the actual implementation (which is passed the
2569 * png_modifier explicitly) and the callback, which gets the modifier from the
2570 * png_struct.
2571 */
2572static void
2573modifier_read_imp(png_modifier *pm, png_bytep pb, png_size_t st)
2574{
2575 while (st > 0)
2576 {
2577 size_t cb;
2578 png_uint_32 len, chunk;
2579 png_modification *mod;
2580
2581 if (pm->buffer_position >= pm->buffer_count) switch (pm->state)
2582 {
2583 static png_byte sign[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
2584 case modifier_start:
2585 store_read_imp(&pm->this, pm->buffer, 8); /* size of signature. */
2586 pm->buffer_count = 8;
2587 pm->buffer_position = 0;
2588
2589 if (memcmp(pm->buffer, sign, 8) != 0)
2590 png_error(pm->this.pread, "invalid PNG file signature");
2591 pm->state = modifier_signature;
2592 break;
2593
2594 case modifier_signature:
2595 store_read_imp(&pm->this, pm->buffer, 13+12); /* size of IHDR */
2596 pm->buffer_count = 13+12;
2597 pm->buffer_position = 0;
2598
2599 if (png_get_uint_32(pm->buffer) != 13 ||
2600 png_get_uint_32(pm->buffer+4) != CHUNK_IHDR)
2601 png_error(pm->this.pread, "invalid IHDR");
2602
2603 /* Check the list of modifiers for modifications to the IHDR. */
2604 mod = pm->modifications;
2605 while (mod != NULL)
2606 {
2607 if (mod->chunk == CHUNK_IHDR && mod->modify_fn &&
2608 (*mod->modify_fn)(pm, mod, 0))
2609 {
2610 mod->modified = 1;
2611 modifier_setbuffer(pm);
2612 }
2613
2614 /* Ignore removal or add if IHDR! */
2615 mod = mod->next;
2616 }
2617
2618 /* Cache information from the IHDR (the modified one.) */
2619 pm->bit_depth = pm->buffer[8+8];
2620 pm->colour_type = pm->buffer[8+8+1];
2621
2622 pm->state = modifier_IHDR;
2623 pm->flush = 0;
2624 break;
2625
2626 case modifier_IHDR:
2627 default:
2628 /* Read a new chunk and process it until we see PLTE, IDAT or
2629 * IEND. 'flush' indicates that there is still some data to
2630 * output from the preceding chunk.
2631 */
2632 if ((cb = pm->flush) > 0)
2633 {
2634 if (cb > st) cb = st;
2635 pm->flush -= cb;
2636 store_read_imp(&pm->this, pb, cb);
2637 pb += cb;
2638 st -= cb;
2639 if (st == 0) return;
2640 }
2641
2642 /* No more bytes to flush, read a header, or handle a pending
2643 * chunk.
2644 */
2645 if (pm->pending_chunk != 0)
2646 {
2647 png_save_uint_32(pm->buffer, pm->pending_len);
2648 png_save_uint_32(pm->buffer+4, pm->pending_chunk);
2649 pm->pending_len = 0;
2650 pm->pending_chunk = 0;
2651 }
2652 else
2653 store_read_imp(&pm->this, pm->buffer, 8);
2654
2655 pm->buffer_count = 8;
2656 pm->buffer_position = 0;
2657
2658 /* Check for something to modify or a terminator chunk. */
2659 len = png_get_uint_32(pm->buffer);
2660 chunk = png_get_uint_32(pm->buffer+4);
2661
2662 /* Terminators first, they may have to be delayed for added
2663 * chunks
2664 */
2665 if (chunk == CHUNK_PLTE || chunk == CHUNK_IDAT ||
2666 chunk == CHUNK_IEND)
2667 {
2668 mod = pm->modifications;
2669
2670 while (mod != NULL)
2671 {
2672 if ((mod->add == chunk ||
2673 (mod->add == CHUNK_PLTE && chunk == CHUNK_IDAT)) &&
2674 mod->modify_fn != NULL && !mod->modified && !mod->added)
2675 {
2676 /* Regardless of what the modify function does do not run
2677 * this again.
2678 */
2679 mod->added = 1;
2680
2681 if ((*mod->modify_fn)(pm, mod, 1 /*add*/))
2682 {
2683 /* Reset the CRC on a new chunk */
2684 if (pm->buffer_count > 0)
2685 modifier_setbuffer(pm);
2686
2687 else
2688 {
2689 pm->buffer_position = 0;
2690 mod->removed = 1;
2691 }
2692
2693 /* The buffer has been filled with something (we assume)
2694 * so output this. Pend the current chunk.
2695 */
2696 pm->pending_len = len;
2697 pm->pending_chunk = chunk;
2698 break; /* out of while */
2699 }
2700 }
2701
2702 mod = mod->next;
2703 }
2704
2705 /* Don't do any further processing if the buffer was modified -
2706 * otherwise the code will end up modifying a chunk that was
2707 * just added.
2708 */
2709 if (mod != NULL)
2710 break; /* out of switch */
2711 }
2712
2713 /* If we get to here then this chunk may need to be modified. To
2714 * do this it must be less than 1024 bytes in total size, otherwise
2715 * it just gets flushed.
2716 */
2717 if (len+12 <= sizeof pm->buffer)
2718 {
2719 store_read_imp(&pm->this, pm->buffer+pm->buffer_count,
2720 len+12-pm->buffer_count);
2721 pm->buffer_count = len+12;
2722
2723 /* Check for a modification, else leave it be. */
2724 mod = pm->modifications;
2725 while (mod != NULL)
2726 {
2727 if (mod->chunk == chunk)
2728 {
2729 if (mod->modify_fn == NULL)
2730 {
2731 /* Remove this chunk */
2732 pm->buffer_count = pm->buffer_position = 0;
2733 mod->removed = 1;
2734 break; /* Terminate the while loop */
2735 }
2736
2737 else if ((*mod->modify_fn)(pm, mod, 0))
2738 {
2739 mod->modified = 1;
2740 /* The chunk may have been removed: */
2741 if (pm->buffer_count == 0)
2742 {
2743 pm->buffer_position = 0;
2744 break;
2745 }
2746 modifier_setbuffer(pm);
2747 }
2748 }
2749
2750 mod = mod->next;
2751 }
2752 }
2753
2754 else
2755 pm->flush = len+12 - pm->buffer_count; /* data + crc */
2756
2757 /* Take the data from the buffer (if there is any). */
2758 break;
2759 }
2760
2761 /* Here to read from the modifier buffer (not directly from
2762 * the store, as in the flush case above.)
2763 */
2764 cb = pm->buffer_count - pm->buffer_position;
2765
2766 if (cb > st)
2767 cb = st;
2768
2769 memcpy(pb, pm->buffer + pm->buffer_position, cb);
2770 st -= cb;
2771 pb += cb;
2772 pm->buffer_position += cb;
2773 }
2774}
2775
2776/* The callback: */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302777static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07002778modifier_read(png_structp ppIn, png_bytep pb, png_size_t st)
2779{
2780 png_const_structp pp = ppIn;
2781 png_modifier *pm = voidcast(png_modifier*, png_get_io_ptr(pp));
2782
2783 if (pm == NULL || pm->this.pread != pp)
2784 png_error(pp, "bad modifier_read call");
2785
2786 modifier_read_imp(pm, pb, st);
2787}
2788
2789/* Like store_progressive_read but the data is getting changed as we go so we
2790 * need a local buffer.
2791 */
2792static void
2793modifier_progressive_read(png_modifier *pm, png_structp pp, png_infop pi)
2794{
2795 if (pm->this.pread != pp || pm->this.current == NULL ||
2796 pm->this.next == NULL)
2797 png_error(pp, "store state damaged (progressive)");
2798
2799 /* This is another Horowitz and Hill random noise generator. In this case
2800 * the aim is to stress the progressive reader with truly horrible variable
2801 * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers
2802 * is generated. We could probably just count from 1 to 32767 and get as
2803 * good a result.
2804 */
2805 for (;;)
2806 {
2807 static png_uint_32 noise = 1;
2808 png_size_t cb, cbAvail;
2809 png_byte buffer[512];
2810
2811 /* Generate 15 more bits of stuff: */
2812 noise = (noise << 9) | ((noise ^ (noise >> (9-5))) & 0x1ff);
2813 cb = noise & 0x1ff;
2814
2815 /* Check that this number of bytes are available (in the current buffer.)
2816 * (This doesn't quite work - the modifier might delete a chunk; unlikely
2817 * but possible, it doesn't happen at present because the modifier only
2818 * adds chunks to standard images.)
2819 */
2820 cbAvail = store_read_buffer_avail(&pm->this);
2821 if (pm->buffer_count > pm->buffer_position)
2822 cbAvail += pm->buffer_count - pm->buffer_position;
2823
2824 if (cb > cbAvail)
2825 {
2826 /* Check for EOF: */
2827 if (cbAvail == 0)
2828 break;
2829
2830 cb = cbAvail;
2831 }
2832
2833 modifier_read_imp(pm, buffer, cb);
2834 png_process_data(pp, pi, buffer, cb);
2835 }
2836
2837 /* Check the invariants at the end (if this fails it's a problem in this
2838 * file!)
2839 */
2840 if (pm->buffer_count > pm->buffer_position ||
2841 pm->this.next != &pm->this.current->data ||
2842 pm->this.readpos < pm->this.current->datacount)
2843 png_error(pp, "progressive read implementation error");
2844}
2845
2846/* Set up a modifier. */
2847static png_structp
2848set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id,
Matt Sarett9ea75692016-01-08 13:00:42 -05002849 const char *name)
Chris Craikb50c2172013-07-29 15:28:30 -07002850{
2851 /* Do this first so that the modifier fields are cleared even if an error
2852 * happens allocating the png_struct. No allocation is done here so no
2853 * cleanup is required.
2854 */
2855 pm->state = modifier_start;
2856 pm->bit_depth = 0;
2857 pm->colour_type = 255;
2858
2859 pm->pending_len = 0;
2860 pm->pending_chunk = 0;
2861 pm->flush = 0;
2862 pm->buffer_count = 0;
2863 pm->buffer_position = 0;
2864
2865 return set_store_for_read(&pm->this, ppi, id, name);
2866}
2867
2868
2869/******************************** MODIFICATIONS *******************************/
2870/* Standard modifications to add chunks. These do not require the _SUPPORTED
2871 * macros because the chunks can be there regardless of whether this specific
2872 * libpng supports them.
2873 */
2874typedef struct gama_modification
2875{
2876 png_modification this;
2877 png_fixed_point gamma;
2878} gama_modification;
2879
2880static int
2881gama_modify(png_modifier *pm, png_modification *me, int add)
2882{
2883 UNUSED(add)
2884 /* This simply dumps the given gamma value into the buffer. */
2885 png_save_uint_32(pm->buffer, 4);
2886 png_save_uint_32(pm->buffer+4, CHUNK_gAMA);
2887 png_save_uint_32(pm->buffer+8, ((gama_modification*)me)->gamma);
2888 return 1;
2889}
2890
2891static void
2892gama_modification_init(gama_modification *me, png_modifier *pm, double gammad)
2893{
2894 double g;
2895
2896 modification_init(&me->this);
2897 me->this.chunk = CHUNK_gAMA;
2898 me->this.modify_fn = gama_modify;
2899 me->this.add = CHUNK_PLTE;
2900 g = fix(gammad);
2901 me->gamma = (png_fixed_point)g;
2902 me->this.next = pm->modifications;
2903 pm->modifications = &me->this;
2904}
2905
2906typedef struct chrm_modification
2907{
2908 png_modification this;
Matt Sarett9ea75692016-01-08 13:00:42 -05002909 const color_encoding *encoding;
Chris Craikb50c2172013-07-29 15:28:30 -07002910 png_fixed_point wx, wy, rx, ry, gx, gy, bx, by;
2911} chrm_modification;
2912
2913static int
2914chrm_modify(png_modifier *pm, png_modification *me, int add)
2915{
2916 UNUSED(add)
2917 /* As with gAMA this just adds the required cHRM chunk to the buffer. */
2918 png_save_uint_32(pm->buffer , 32);
2919 png_save_uint_32(pm->buffer+ 4, CHUNK_cHRM);
2920 png_save_uint_32(pm->buffer+ 8, ((chrm_modification*)me)->wx);
2921 png_save_uint_32(pm->buffer+12, ((chrm_modification*)me)->wy);
2922 png_save_uint_32(pm->buffer+16, ((chrm_modification*)me)->rx);
2923 png_save_uint_32(pm->buffer+20, ((chrm_modification*)me)->ry);
2924 png_save_uint_32(pm->buffer+24, ((chrm_modification*)me)->gx);
2925 png_save_uint_32(pm->buffer+28, ((chrm_modification*)me)->gy);
2926 png_save_uint_32(pm->buffer+32, ((chrm_modification*)me)->bx);
2927 png_save_uint_32(pm->buffer+36, ((chrm_modification*)me)->by);
2928 return 1;
2929}
2930
2931static void
2932chrm_modification_init(chrm_modification *me, png_modifier *pm,
Matt Sarett9ea75692016-01-08 13:00:42 -05002933 const color_encoding *encoding)
Chris Craikb50c2172013-07-29 15:28:30 -07002934{
2935 CIE_color white = white_point(encoding);
2936
2937 /* Original end points: */
2938 me->encoding = encoding;
2939
2940 /* Chromaticities (in fixed point): */
2941 me->wx = fix(chromaticity_x(white));
2942 me->wy = fix(chromaticity_y(white));
2943
2944 me->rx = fix(chromaticity_x(encoding->red));
2945 me->ry = fix(chromaticity_y(encoding->red));
2946 me->gx = fix(chromaticity_x(encoding->green));
2947 me->gy = fix(chromaticity_y(encoding->green));
2948 me->bx = fix(chromaticity_x(encoding->blue));
2949 me->by = fix(chromaticity_y(encoding->blue));
2950
2951 modification_init(&me->this);
2952 me->this.chunk = CHUNK_cHRM;
2953 me->this.modify_fn = chrm_modify;
2954 me->this.add = CHUNK_PLTE;
2955 me->this.next = pm->modifications;
2956 pm->modifications = &me->this;
2957}
2958
2959typedef struct srgb_modification
2960{
2961 png_modification this;
2962 png_byte intent;
2963} srgb_modification;
2964
2965static int
2966srgb_modify(png_modifier *pm, png_modification *me, int add)
2967{
2968 UNUSED(add)
2969 /* As above, ignore add and just make a new chunk */
2970 png_save_uint_32(pm->buffer, 1);
2971 png_save_uint_32(pm->buffer+4, CHUNK_sRGB);
2972 pm->buffer[8] = ((srgb_modification*)me)->intent;
2973 return 1;
2974}
2975
2976static void
2977srgb_modification_init(srgb_modification *me, png_modifier *pm, png_byte intent)
2978{
2979 modification_init(&me->this);
2980 me->this.chunk = CHUNK_sBIT;
2981
2982 if (intent <= 3) /* if valid, else *delete* sRGB chunks */
2983 {
2984 me->this.modify_fn = srgb_modify;
2985 me->this.add = CHUNK_PLTE;
2986 me->intent = intent;
2987 }
2988
2989 else
2990 {
2991 me->this.modify_fn = 0;
2992 me->this.add = 0;
2993 me->intent = 0;
2994 }
2995
2996 me->this.next = pm->modifications;
2997 pm->modifications = &me->this;
2998}
2999
3000#ifdef PNG_READ_GAMMA_SUPPORTED
3001typedef struct sbit_modification
3002{
3003 png_modification this;
3004 png_byte sbit;
3005} sbit_modification;
3006
3007static int
3008sbit_modify(png_modifier *pm, png_modification *me, int add)
3009{
3010 png_byte sbit = ((sbit_modification*)me)->sbit;
3011 if (pm->bit_depth > sbit)
3012 {
3013 int cb = 0;
3014 switch (pm->colour_type)
3015 {
3016 case 0:
3017 cb = 1;
3018 break;
3019
3020 case 2:
3021 case 3:
3022 cb = 3;
3023 break;
3024
3025 case 4:
3026 cb = 2;
3027 break;
3028
3029 case 6:
3030 cb = 4;
3031 break;
3032
3033 default:
3034 png_error(pm->this.pread,
3035 "unexpected colour type in sBIT modification");
3036 }
3037
3038 png_save_uint_32(pm->buffer, cb);
3039 png_save_uint_32(pm->buffer+4, CHUNK_sBIT);
3040
3041 while (cb > 0)
3042 (pm->buffer+8)[--cb] = sbit;
3043
3044 return 1;
3045 }
3046 else if (!add)
3047 {
3048 /* Remove the sBIT chunk */
3049 pm->buffer_count = pm->buffer_position = 0;
3050 return 1;
3051 }
3052 else
3053 return 0; /* do nothing */
3054}
3055
3056static void
3057sbit_modification_init(sbit_modification *me, png_modifier *pm, png_byte sbit)
3058{
3059 modification_init(&me->this);
3060 me->this.chunk = CHUNK_sBIT;
3061 me->this.modify_fn = sbit_modify;
3062 me->this.add = CHUNK_PLTE;
3063 me->sbit = sbit;
3064 me->this.next = pm->modifications;
3065 pm->modifications = &me->this;
3066}
3067#endif /* PNG_READ_GAMMA_SUPPORTED */
3068#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
3069
3070/***************************** STANDARD PNG FILES *****************************/
3071/* Standard files - write and save standard files. */
3072/* There are two basic forms of standard images. Those which attempt to have
3073 * all the possible pixel values (not possible for 16bpp images, but a range of
3074 * values are produced) and those which have a range of image sizes. The former
3075 * are used for testing transforms, in particular gamma correction and bit
3076 * reduction and increase. The latter are reserved for testing the behavior of
3077 * libpng with respect to 'odd' image sizes - particularly small images where
3078 * rows become 1 byte and interlace passes disappear.
3079 *
3080 * The first, most useful, set are the 'transform' images, the second set of
3081 * small images are the 'size' images.
3082 *
3083 * The transform files are constructed with rows which fit into a 1024 byte row
3084 * buffer. This makes allocation easier below. Further regardless of the file
3085 * format every row has 128 pixels (giving 1024 bytes for 64bpp formats).
3086 *
3087 * Files are stored with no gAMA or sBIT chunks, with a PLTE only when needed
3088 * and with an ID derived from the colour type, bit depth and interlace type
3089 * as above (FILEID). The width (128) and height (variable) are not stored in
3090 * the FILEID - instead the fields are set to 0, indicating a transform file.
3091 *
3092 * The size files ar constructed with rows a maximum of 128 bytes wide, allowing
3093 * a maximum width of 16 pixels (for the 64bpp case.) They also have a maximum
3094 * height of 16 rows. The width and height are stored in the FILEID and, being
3095 * non-zero, indicate a size file.
3096 *
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303097 * Because the PNG filter code is typically the largest CPU consumer within
3098 * libpng itself there is a tendency to attempt to optimize it. This results in
3099 * special case code which needs to be validated. To cause this to happen the
3100 * 'size' images are made to use each possible filter, in so far as this is
3101 * possible for smaller images.
3102 *
Chris Craikb50c2172013-07-29 15:28:30 -07003103 * For palette image (colour type 3) multiple transform images are stored with
3104 * the same bit depth to allow testing of more colour combinations -
3105 * particularly important for testing the gamma code because libpng uses a
3106 * different code path for palette images. For size images a single palette is
3107 * used.
3108 */
3109
3110/* Make a 'standard' palette. Because there are only 256 entries in a palette
3111 * (maximum) this actually makes a random palette in the hope that enough tests
3112 * will catch enough errors. (Note that the same palette isn't produced every
3113 * time for the same test - it depends on what previous tests have been run -
3114 * but a given set of arguments to pngvalid will always produce the same palette
3115 * at the same test! This is why pseudo-random number generators are useful for
3116 * testing.)
3117 *
3118 * The store must be open for write when this is called, otherwise an internal
3119 * error will occur. This routine contains its own magic number seed, so the
3120 * palettes generated don't change if there are intervening errors (changing the
3121 * calls to the store_mark seed.)
3122 */
3123static store_palette_entry *
3124make_standard_palette(png_store* ps, int npalette, int do_tRNS)
3125{
3126 static png_uint_32 palette_seed[2] = { 0x87654321, 9 };
3127
3128 int i = 0;
3129 png_byte values[256][4];
3130
3131 /* Always put in black and white plus the six primary and secondary colors.
3132 */
3133 for (; i<8; ++i)
3134 {
3135 values[i][1] = (png_byte)((i&1) ? 255U : 0U);
3136 values[i][2] = (png_byte)((i&2) ? 255U : 0U);
3137 values[i][3] = (png_byte)((i&4) ? 255U : 0U);
3138 }
3139
3140 /* Then add 62 grays (one quarter of the remaining 256 slots). */
3141 {
3142 int j = 0;
3143 png_byte random_bytes[4];
3144 png_byte need[256];
3145
3146 need[0] = 0; /*got black*/
3147 memset(need+1, 1, (sizeof need)-2); /*need these*/
3148 need[255] = 0; /*but not white*/
3149
3150 while (i<70)
3151 {
3152 png_byte b;
3153
3154 if (j==0)
3155 {
3156 make_four_random_bytes(palette_seed, random_bytes);
3157 j = 4;
3158 }
3159
3160 b = random_bytes[--j];
3161 if (need[b])
3162 {
3163 values[i][1] = b;
3164 values[i][2] = b;
3165 values[i++][3] = b;
3166 }
3167 }
3168 }
3169
3170 /* Finally add 192 colors at random - don't worry about matches to things we
3171 * already have, chance is less than 1/65536. Don't worry about grays,
3172 * chance is the same, so we get a duplicate or extra gray less than 1 time
3173 * in 170.
3174 */
3175 for (; i<256; ++i)
3176 make_four_random_bytes(palette_seed, values[i]);
3177
3178 /* Fill in the alpha values in the first byte. Just use all possible values
3179 * (0..255) in an apparently random order:
3180 */
3181 {
3182 store_palette_entry *palette;
3183 png_byte selector[4];
3184
3185 make_four_random_bytes(palette_seed, selector);
3186
3187 if (do_tRNS)
3188 for (i=0; i<256; ++i)
3189 values[i][0] = (png_byte)(i ^ selector[0]);
3190
3191 else
3192 for (i=0; i<256; ++i)
3193 values[i][0] = 255; /* no transparency/tRNS chunk */
3194
3195 /* 'values' contains 256 ARGB values, but we only need 'npalette'.
3196 * 'npalette' will always be a power of 2: 2, 4, 16 or 256. In the low
3197 * bit depth cases select colors at random, else it is difficult to have
3198 * a set of low bit depth palette test with any chance of a reasonable
3199 * range of colors. Do this by randomly permuting values into the low
3200 * 'npalette' entries using an XOR mask generated here. This also
3201 * permutes the npalette == 256 case in a potentially useful way (there is
3202 * no relationship between palette index and the color value therein!)
3203 */
3204 palette = store_write_palette(ps, npalette);
3205
3206 for (i=0; i<npalette; ++i)
3207 {
3208 palette[i].alpha = values[i ^ selector[1]][0];
3209 palette[i].red = values[i ^ selector[1]][1];
3210 palette[i].green = values[i ^ selector[1]][2];
3211 palette[i].blue = values[i ^ selector[1]][3];
3212 }
3213
3214 return palette;
3215 }
3216}
3217
3218/* Initialize a standard palette on a write stream. The 'do_tRNS' argument
3219 * indicates whether or not to also set the tRNS chunk.
3220 */
3221/* TODO: the png_structp here can probably be 'const' in the future */
3222static void
3223init_standard_palette(png_store *ps, png_structp pp, png_infop pi, int npalette,
3224 int do_tRNS)
3225{
3226 store_palette_entry *ppal = make_standard_palette(ps, npalette, do_tRNS);
3227
3228 {
3229 int i;
3230 png_color palette[256];
3231
3232 /* Set all entries to detect overread errors. */
3233 for (i=0; i<npalette; ++i)
3234 {
3235 palette[i].red = ppal[i].red;
3236 palette[i].green = ppal[i].green;
3237 palette[i].blue = ppal[i].blue;
3238 }
3239
3240 /* Just in case fill in the rest with detectable values: */
3241 for (; i<256; ++i)
3242 palette[i].red = palette[i].green = palette[i].blue = 42;
3243
3244 png_set_PLTE(pp, pi, palette, npalette);
3245 }
3246
3247 if (do_tRNS)
3248 {
3249 int i, j;
3250 png_byte tRNS[256];
3251
3252 /* Set all the entries, but skip trailing opaque entries */
3253 for (i=j=0; i<npalette; ++i)
3254 if ((tRNS[i] = ppal[i].alpha) < 255)
3255 j = i+1;
3256
3257 /* Fill in the remainder with a detectable value: */
3258 for (; i<256; ++i)
3259 tRNS[i] = 24;
3260
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303261# ifdef PNG_WRITE_tRNS_SUPPORTED
3262 if (j > 0)
3263 png_set_tRNS(pp, pi, tRNS, j, 0/*color*/);
3264# endif
Chris Craikb50c2172013-07-29 15:28:30 -07003265 }
3266}
3267
Matt Sarett9ea75692016-01-08 13:00:42 -05003268#ifdef PNG_WRITE_tRNS_SUPPORTED
3269static void
3270set_random_tRNS(png_structp pp, png_infop pi, const png_byte colour_type,
3271 const int bit_depth)
3272{
3273 /* To make this useful the tRNS color needs to match at least one pixel.
3274 * Random values are fine for gray, including the 16-bit case where we know
3275 * that the test image contains all the gray values. For RGB we need more
3276 * method as only 65536 different RGB values are generated.
3277 */
3278 png_color_16 tRNS;
3279 const png_uint_16 mask = (png_uint_16)((1U << bit_depth)-1);
3280
3281 RANDOMIZE(tRNS);
3282
3283 if (colour_type & 2/*RGB*/)
3284 {
3285 if (bit_depth == 8)
3286 {
3287 tRNS.blue = tRNS.red ^ tRNS.green;
3288 tRNS.red &= mask;
3289 tRNS.green &= mask;
3290 tRNS.blue &= mask;
3291 }
3292
3293 else /* bit_depth == 16 */
3294 {
3295 tRNS.green = (png_uint_16)(tRNS.red * 257);
3296 tRNS.blue = (png_uint_16)(tRNS.green * 17);
3297 }
3298 }
3299
3300 else
3301 tRNS.gray &= mask;
3302
3303 png_set_tRNS(pp, pi, NULL, 0, &tRNS);
3304}
3305#endif
3306
Chris Craikb50c2172013-07-29 15:28:30 -07003307/* The number of passes is related to the interlace type. There was no libpng
3308 * API to determine this prior to 1.5, so we need an inquiry function:
3309 */
3310static int
3311npasses_from_interlace_type(png_const_structp pp, int interlace_type)
3312{
3313 switch (interlace_type)
3314 {
3315 default:
3316 png_error(pp, "invalid interlace type");
3317
3318 case PNG_INTERLACE_NONE:
3319 return 1;
3320
3321 case PNG_INTERLACE_ADAM7:
3322 return PNG_INTERLACE_ADAM7_PASSES;
3323 }
3324}
3325
3326static unsigned int
3327bit_size(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
3328{
3329 switch (colour_type)
3330 {
3331 default: png_error(pp, "invalid color type");
3332
3333 case 0: return bit_depth;
3334
3335 case 2: return 3*bit_depth;
3336
3337 case 3: return bit_depth;
3338
3339 case 4: return 2*bit_depth;
3340
3341 case 6: return 4*bit_depth;
3342 }
3343}
3344
3345#define TRANSFORM_WIDTH 128U
3346#define TRANSFORM_ROWMAX (TRANSFORM_WIDTH*8U)
3347#define SIZE_ROWMAX (16*8U) /* 16 pixels, max 8 bytes each - 128 bytes */
3348#define STANDARD_ROWMAX TRANSFORM_ROWMAX /* The larger of the two */
3349#define SIZE_HEIGHTMAX 16 /* Maximum range of size images */
3350
3351static size_t
3352transform_rowsize(png_const_structp pp, png_byte colour_type,
3353 png_byte bit_depth)
3354{
3355 return (TRANSFORM_WIDTH * bit_size(pp, colour_type, bit_depth)) / 8;
3356}
3357
3358/* transform_width(pp, colour_type, bit_depth) current returns the same number
3359 * every time, so just use a macro:
3360 */
3361#define transform_width(pp, colour_type, bit_depth) TRANSFORM_WIDTH
3362
3363static png_uint_32
3364transform_height(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
3365{
3366 switch (bit_size(pp, colour_type, bit_depth))
3367 {
3368 case 1:
3369 case 2:
3370 case 4:
3371 return 1; /* Total of 128 pixels */
3372
3373 case 8:
3374 return 2; /* Total of 256 pixels/bytes */
3375
3376 case 16:
3377 return 512; /* Total of 65536 pixels */
3378
3379 case 24:
3380 case 32:
3381 return 512; /* 65536 pixels */
3382
3383 case 48:
3384 case 64:
3385 return 2048;/* 4 x 65536 pixels. */
3386# define TRANSFORM_HEIGHTMAX 2048
3387
3388 default:
3389 return 0; /* Error, will be caught later */
3390 }
3391}
3392
3393#ifdef PNG_READ_SUPPORTED
3394/* The following can only be defined here, now we have the definitions
3395 * of the transform image sizes.
3396 */
3397static png_uint_32
3398standard_width(png_const_structp pp, png_uint_32 id)
3399{
3400 png_uint_32 width = WIDTH_FROM_ID(id);
3401 UNUSED(pp)
3402
3403 if (width == 0)
3404 width = transform_width(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
3405
3406 return width;
3407}
3408
3409static png_uint_32
3410standard_height(png_const_structp pp, png_uint_32 id)
3411{
3412 png_uint_32 height = HEIGHT_FROM_ID(id);
3413
3414 if (height == 0)
3415 height = transform_height(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
3416
3417 return height;
3418}
3419
3420static png_uint_32
3421standard_rowsize(png_const_structp pp, png_uint_32 id)
3422{
3423 png_uint_32 width = standard_width(pp, id);
3424
3425 /* This won't overflow: */
3426 width *= bit_size(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
3427 return (width + 7) / 8;
3428}
3429#endif /* PNG_READ_SUPPORTED */
3430
3431static void
3432transform_row(png_const_structp pp, png_byte buffer[TRANSFORM_ROWMAX],
3433 png_byte colour_type, png_byte bit_depth, png_uint_32 y)
3434{
3435 png_uint_32 v = y << 7;
3436 png_uint_32 i = 0;
3437
3438 switch (bit_size(pp, colour_type, bit_depth))
3439 {
3440 case 1:
3441 while (i<128/8) buffer[i] = (png_byte)(v & 0xff), v += 17, ++i;
3442 return;
3443
3444 case 2:
3445 while (i<128/4) buffer[i] = (png_byte)(v & 0xff), v += 33, ++i;
3446 return;
3447
3448 case 4:
3449 while (i<128/2) buffer[i] = (png_byte)(v & 0xff), v += 65, ++i;
3450 return;
3451
3452 case 8:
3453 /* 256 bytes total, 128 bytes in each row set as follows: */
3454 while (i<128) buffer[i] = (png_byte)(v & 0xff), ++v, ++i;
3455 return;
3456
3457 case 16:
3458 /* Generate all 65536 pixel values in order, which includes the 8 bit
3459 * GA case as well as the 16 bit G case.
3460 */
3461 while (i<128)
3462 {
3463 buffer[2*i] = (png_byte)((v>>8) & 0xff);
3464 buffer[2*i+1] = (png_byte)(v & 0xff);
3465 ++v;
3466 ++i;
3467 }
3468
3469 return;
3470
3471 case 24:
3472 /* 65535 pixels, but rotate the values. */
3473 while (i<128)
3474 {
3475 /* Three bytes per pixel, r, g, b, make b by r^g */
3476 buffer[3*i+0] = (png_byte)((v >> 8) & 0xff);
3477 buffer[3*i+1] = (png_byte)(v & 0xff);
3478 buffer[3*i+2] = (png_byte)(((v >> 8) ^ v) & 0xff);
3479 ++v;
3480 ++i;
3481 }
3482
3483 return;
3484
3485 case 32:
3486 /* 65535 pixels, r, g, b, a; just replicate */
3487 while (i<128)
3488 {
3489 buffer[4*i+0] = (png_byte)((v >> 8) & 0xff);
3490 buffer[4*i+1] = (png_byte)(v & 0xff);
3491 buffer[4*i+2] = (png_byte)((v >> 8) & 0xff);
3492 buffer[4*i+3] = (png_byte)(v & 0xff);
3493 ++v;
3494 ++i;
3495 }
3496
3497 return;
3498
3499 case 48:
3500 /* y is maximum 2047, giving 4x65536 pixels, make 'r' increase by 1 at
3501 * each pixel, g increase by 257 (0x101) and 'b' by 0x1111:
3502 */
3503 while (i<128)
3504 {
3505 png_uint_32 t = v++;
3506 buffer[6*i+0] = (png_byte)((t >> 8) & 0xff);
3507 buffer[6*i+1] = (png_byte)(t & 0xff);
3508 t *= 257;
3509 buffer[6*i+2] = (png_byte)((t >> 8) & 0xff);
3510 buffer[6*i+3] = (png_byte)(t & 0xff);
3511 t *= 17;
3512 buffer[6*i+4] = (png_byte)((t >> 8) & 0xff);
3513 buffer[6*i+5] = (png_byte)(t & 0xff);
3514 ++i;
3515 }
3516
3517 return;
3518
3519 case 64:
3520 /* As above in the 32 bit case. */
3521 while (i<128)
3522 {
3523 png_uint_32 t = v++;
3524 buffer[8*i+0] = (png_byte)((t >> 8) & 0xff);
3525 buffer[8*i+1] = (png_byte)(t & 0xff);
3526 buffer[8*i+4] = (png_byte)((t >> 8) & 0xff);
3527 buffer[8*i+5] = (png_byte)(t & 0xff);
3528 t *= 257;
3529 buffer[8*i+2] = (png_byte)((t >> 8) & 0xff);
3530 buffer[8*i+3] = (png_byte)(t & 0xff);
3531 buffer[8*i+6] = (png_byte)((t >> 8) & 0xff);
3532 buffer[8*i+7] = (png_byte)(t & 0xff);
3533 ++i;
3534 }
3535 return;
3536
3537 default:
3538 break;
3539 }
3540
3541 png_error(pp, "internal error");
3542}
3543
3544/* This is just to do the right cast - could be changed to a function to check
3545 * 'bd' but there isn't much point.
3546 */
3547#define DEPTH(bd) ((png_byte)(1U << (bd)))
3548
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303549/* This is just a helper for compiling on minimal systems with no write
3550 * interlacing support. If there is no write interlacing we can't generate test
3551 * cases with interlace:
3552 */
3553#ifdef PNG_WRITE_INTERLACING_SUPPORTED
3554# define INTERLACE_LAST PNG_INTERLACE_LAST
3555# define check_interlace_type(type) ((void)(type))
Matt Sarett9ea75692016-01-08 13:00:42 -05003556# define set_write_interlace_handling(pp,type) png_set_interlace_handling(pp)
3557# define do_own_interlace 0
3558#elif PNG_LIBPNG_VER < 10700
3559# define set_write_interlace_handling(pp,type) (1)
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303560static void
Matt Sarett9ea75692016-01-08 13:00:42 -05003561check_interlace_type(int const interlace_type)
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303562{
Matt Sarett9ea75692016-01-08 13:00:42 -05003563 /* Prior to 1.7.0 libpng does not support the write of an interlaced image
3564 * unless PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the
3565 * code here does the pixel interlace itself, so:
3566 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303567 if (interlace_type != PNG_INTERLACE_NONE)
3568 {
3569 /* This is an internal error - --interlace tests should be skipped, not
3570 * attempted.
3571 */
3572 fprintf(stderr, "pngvalid: no interlace support\n");
3573 exit(99);
3574 }
3575}
Matt Sarett9ea75692016-01-08 13:00:42 -05003576# define INTERLACE_LAST (PNG_INTERLACE_NONE+1)
3577# define do_own_interlace 0
3578#else /* libpng 1.7+ */
3579# define set_write_interlace_handling(pp,type)\
3580 npasses_from_interlace_type(pp,type)
3581# define check_interlace_type(type) ((void)(type))
3582# define INTERLACE_LAST PNG_INTERLACE_LAST
3583# define do_own_interlace 1
3584#endif /* WRITE_INTERLACING tests */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303585
Matt Sarett9ea75692016-01-08 13:00:42 -05003586#define CAN_WRITE_INTERLACE\
3587 PNG_LIBPNG_VER >= 10700 || defined PNG_WRITE_INTERLACING_SUPPORTED
3588
3589/* Do the same thing for read interlacing; this controls whether read tests do
3590 * their own de-interlace or use libpng.
3591 */
3592#ifdef PNG_READ_INTERLACING_SUPPORTED
3593# define do_read_interlace 0
3594#else /* no libpng read interlace support */
3595# define do_read_interlace 1
3596#endif
3597/* The following two routines use the PNG interlace support macros from
3598 * png.h to interlace or deinterlace rows.
3599 */
3600static void
3601interlace_row(png_bytep buffer, png_const_bytep imageRow,
3602 unsigned int pixel_size, png_uint_32 w, int pass, int littleendian)
3603{
3604 png_uint_32 xin, xout, xstep;
3605
3606 /* Note that this can, trivially, be optimized to a memcpy on pass 7, the
3607 * code is presented this way to make it easier to understand. In practice
3608 * consult the code in the libpng source to see other ways of doing this.
3609 *
3610 * It is OK for buffer and imageRow to be identical, because 'xin' moves
3611 * faster than 'xout' and we copy up.
3612 */
3613 xin = PNG_PASS_START_COL(pass);
3614 xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
3615
3616 for (xout=0; xin<w; xin+=xstep)
3617 {
3618 pixel_copy(buffer, xout, imageRow, xin, pixel_size, littleendian);
3619 ++xout;
3620 }
3621}
3622
3623#ifdef PNG_READ_SUPPORTED
3624static void
3625deinterlace_row(png_bytep buffer, png_const_bytep row,
3626 unsigned int pixel_size, png_uint_32 w, int pass, int littleendian)
3627{
3628 /* The inverse of the above, 'row' is part of row 'y' of the output image,
3629 * in 'buffer'. The image is 'w' wide and this is pass 'pass', distribute
3630 * the pixels of row into buffer and return the number written (to allow
3631 * this to be checked).
3632 */
3633 png_uint_32 xin, xout, xstep;
3634
3635 xout = PNG_PASS_START_COL(pass);
3636 xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
3637
3638 for (xin=0; xout<w; xout+=xstep)
3639 {
3640 pixel_copy(buffer, xout, row, xin, pixel_size, littleendian);
3641 ++xin;
3642 }
3643}
3644#endif /* PNG_READ_SUPPORTED */
3645
3646/* Make a standardized image given an image colour type, bit depth and
Chris Craikb50c2172013-07-29 15:28:30 -07003647 * interlace type. The standard images have a very restricted range of
3648 * rows and heights and are used for testing transforms rather than image
3649 * layout details. See make_size_images below for a way to make images
3650 * that test odd sizes along with the libpng interlace handling.
3651 */
3652static void
Matt Sarett9ea75692016-01-08 13:00:42 -05003653make_transform_image(png_store* const ps, png_byte const colour_type,
3654 png_byte const bit_depth, unsigned int palette_number,
Chris Craikb50c2172013-07-29 15:28:30 -07003655 int interlace_type, png_const_charp name)
3656{
3657 context(ps, fault);
3658
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303659 check_interlace_type(interlace_type);
3660
Chris Craikb50c2172013-07-29 15:28:30 -07003661 Try
3662 {
3663 png_infop pi;
3664 png_structp pp = set_store_for_write(ps, &pi, name);
Matt Sarett9ea75692016-01-08 13:00:42 -05003665 png_uint_32 h, w;
Chris Craikb50c2172013-07-29 15:28:30 -07003666
3667 /* In the event of a problem return control to the Catch statement below
3668 * to do the clean up - it is not possible to 'return' directly from a Try
3669 * block.
3670 */
3671 if (pp == NULL)
3672 Throw ps;
3673
Matt Sarett9ea75692016-01-08 13:00:42 -05003674 w = transform_width(pp, colour_type, bit_depth);
Chris Craikb50c2172013-07-29 15:28:30 -07003675 h = transform_height(pp, colour_type, bit_depth);
3676
Matt Sarett9ea75692016-01-08 13:00:42 -05003677 png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
Chris Craikb50c2172013-07-29 15:28:30 -07003678 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
3679
3680#ifdef PNG_TEXT_SUPPORTED
3681# if defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED)
3682# define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_zTXt
3683# else
3684# define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_NONE
3685# endif
3686 {
3687 static char key[] = "image name"; /* must be writeable */
3688 size_t pos;
3689 png_text text;
3690 char copy[FILE_NAME_SIZE];
3691
3692 /* Use a compressed text string to test the correct interaction of text
3693 * compression and IDAT compression.
3694 */
3695 text.compression = TEXT_COMPRESSION;
3696 text.key = key;
3697 /* Yuck: the text must be writable! */
3698 pos = safecat(copy, sizeof copy, 0, ps->wname);
3699 text.text = copy;
3700 text.text_length = pos;
3701 text.itxt_length = 0;
3702 text.lang = 0;
3703 text.lang_key = 0;
3704
3705 png_set_text(pp, pi, &text, 1);
3706 }
3707#endif
3708
3709 if (colour_type == 3) /* palette */
3710 init_standard_palette(ps, pp, pi, 1U << bit_depth, 1/*do tRNS*/);
3711
Matt Sarett9ea75692016-01-08 13:00:42 -05003712# ifdef PNG_WRITE_tRNS_SUPPORTED
3713 else if (palette_number)
3714 set_random_tRNS(pp, pi, colour_type, bit_depth);
3715# endif
3716
Chris Craikb50c2172013-07-29 15:28:30 -07003717 png_write_info(pp, pi);
3718
3719 if (png_get_rowbytes(pp, pi) !=
3720 transform_rowsize(pp, colour_type, bit_depth))
Matt Sarett9ea75692016-01-08 13:00:42 -05003721 png_error(pp, "transform row size incorrect");
Chris Craikb50c2172013-07-29 15:28:30 -07003722
3723 else
3724 {
3725 /* Somewhat confusingly this must be called *after* png_write_info
3726 * because if it is called before, the information in *pp has not been
3727 * updated to reflect the interlaced image.
3728 */
Matt Sarett9ea75692016-01-08 13:00:42 -05003729 int npasses = set_write_interlace_handling(pp, interlace_type);
Chris Craikb50c2172013-07-29 15:28:30 -07003730 int pass;
3731
3732 if (npasses != npasses_from_interlace_type(pp, interlace_type))
3733 png_error(pp, "write: png_set_interlace_handling failed");
3734
3735 for (pass=0; pass<npasses; ++pass)
3736 {
3737 png_uint_32 y;
3738
Matt Sarett9ea75692016-01-08 13:00:42 -05003739 /* do_own_interlace is a pre-defined boolean (a #define) which is
3740 * set if we have to work out the interlaced rows here.
3741 */
Chris Craikb50c2172013-07-29 15:28:30 -07003742 for (y=0; y<h; ++y)
3743 {
3744 png_byte buffer[TRANSFORM_ROWMAX];
3745
3746 transform_row(pp, buffer, colour_type, bit_depth, y);
Matt Sarett9ea75692016-01-08 13:00:42 -05003747
3748# if do_own_interlace
3749 /* If do_own_interlace *and* the image is interlaced we need a
3750 * reduced interlace row; this may be reduced to empty.
3751 */
3752 if (interlace_type == PNG_INTERLACE_ADAM7)
3753 {
3754 /* The row must not be written if it doesn't exist, notice
3755 * that there are two conditions here, either the row isn't
3756 * ever in the pass or the row would be but isn't wide
3757 * enough to contribute any pixels. In fact the wPass test
3758 * can be used to skip the whole y loop in this case.
3759 */
3760 if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
3761 PNG_PASS_COLS(w, pass) > 0)
3762 interlace_row(buffer, buffer,
3763 bit_size(pp, colour_type, bit_depth), w, pass,
3764 0/*data always bigendian*/);
3765 else
3766 continue;
3767 }
3768# endif /* do_own_interlace */
3769
Chris Craikb50c2172013-07-29 15:28:30 -07003770 png_write_row(pp, buffer);
3771 }
3772 }
3773 }
3774
3775#ifdef PNG_TEXT_SUPPORTED
3776 {
3777 static char key[] = "end marker";
3778 static char comment[] = "end";
3779 png_text text;
3780
3781 /* Use a compressed text string to test the correct interaction of text
3782 * compression and IDAT compression.
3783 */
3784 text.compression = TEXT_COMPRESSION;
3785 text.key = key;
3786 text.text = comment;
3787 text.text_length = (sizeof comment)-1;
3788 text.itxt_length = 0;
3789 text.lang = 0;
3790 text.lang_key = 0;
3791
3792 png_set_text(pp, pi, &text, 1);
3793 }
3794#endif
3795
3796 png_write_end(pp, pi);
3797
3798 /* And store this under the appropriate id, then clean up. */
3799 store_storefile(ps, FILEID(colour_type, bit_depth, palette_number,
3800 interlace_type, 0, 0, 0));
3801
3802 store_write_reset(ps);
3803 }
3804
3805 Catch(fault)
3806 {
3807 /* Use the png_store returned by the exception. This may help the compiler
3808 * because 'ps' is not used in this branch of the setjmp. Note that fault
3809 * and ps will always be the same value.
3810 */
3811 store_write_reset(fault);
3812 }
3813}
3814
3815static void
Matt Sarett9ea75692016-01-08 13:00:42 -05003816make_transform_images(png_modifier *pm)
Chris Craikb50c2172013-07-29 15:28:30 -07003817{
3818 png_byte colour_type = 0;
3819 png_byte bit_depth = 0;
3820 unsigned int palette_number = 0;
3821
3822 /* This is in case of errors. */
Matt Sarett9ea75692016-01-08 13:00:42 -05003823 safecat(pm->this.test, sizeof pm->this.test, 0, "make standard images");
Chris Craikb50c2172013-07-29 15:28:30 -07003824
3825 /* Use next_format to enumerate all the combinations we test, including
Matt Sarett9ea75692016-01-08 13:00:42 -05003826 * generating multiple low bit depth palette images. Non-A images (palette
3827 * and direct) are created with and without tRNS chunks.
Chris Craikb50c2172013-07-29 15:28:30 -07003828 */
Matt Sarett9ea75692016-01-08 13:00:42 -05003829 while (next_format(&colour_type, &bit_depth, &palette_number, 1, 1))
Chris Craikb50c2172013-07-29 15:28:30 -07003830 {
3831 int interlace_type;
3832
3833 for (interlace_type = PNG_INTERLACE_NONE;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303834 interlace_type < INTERLACE_LAST; ++interlace_type)
Chris Craikb50c2172013-07-29 15:28:30 -07003835 {
3836 char name[FILE_NAME_SIZE];
3837
3838 standard_name(name, sizeof name, 0, colour_type, bit_depth,
Matt Sarett9ea75692016-01-08 13:00:42 -05003839 palette_number, interlace_type, 0, 0, do_own_interlace);
3840 make_transform_image(&pm->this, colour_type, bit_depth, palette_number,
Chris Craikb50c2172013-07-29 15:28:30 -07003841 interlace_type, name);
3842 }
3843 }
3844}
3845
Chris Craikb50c2172013-07-29 15:28:30 -07003846/* Build a single row for the 'size' test images; this fills in only the
3847 * first bit_width bits of the sample row.
3848 */
3849static void
3850size_row(png_byte buffer[SIZE_ROWMAX], png_uint_32 bit_width, png_uint_32 y)
3851{
3852 /* height is in the range 1 to 16, so: */
3853 y = ((y & 1) << 7) + ((y & 2) << 6) + ((y & 4) << 5) + ((y & 8) << 4);
3854 /* the following ensures bits are set in small images: */
3855 y ^= 0xA5;
3856
3857 while (bit_width >= 8)
3858 *buffer++ = (png_byte)y++, bit_width -= 8;
3859
3860 /* There may be up to 7 remaining bits, these go in the most significant
3861 * bits of the byte.
3862 */
3863 if (bit_width > 0)
3864 {
3865 png_uint_32 mask = (1U<<(8-bit_width))-1;
3866 *buffer = (png_byte)((*buffer & mask) | (y & ~mask));
3867 }
3868}
3869
3870static void
Matt Sarett9ea75692016-01-08 13:00:42 -05003871make_size_image(png_store* const ps, png_byte const colour_type,
3872 png_byte const bit_depth, int const interlace_type,
3873 png_uint_32 const w, png_uint_32 const h,
3874 int const do_interlace)
Chris Craikb50c2172013-07-29 15:28:30 -07003875{
3876 context(ps, fault);
3877
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303878 check_interlace_type(interlace_type);
3879
Chris Craikb50c2172013-07-29 15:28:30 -07003880 Try
3881 {
3882 png_infop pi;
3883 png_structp pp;
3884 unsigned int pixel_size;
3885
3886 /* Make a name and get an appropriate id for the store: */
3887 char name[FILE_NAME_SIZE];
Matt Sarett9ea75692016-01-08 13:00:42 -05003888 const png_uint_32 id = FILEID(colour_type, bit_depth, 0/*palette*/,
Chris Craikb50c2172013-07-29 15:28:30 -07003889 interlace_type, w, h, do_interlace);
3890
3891 standard_name_from_id(name, sizeof name, 0, id);
3892 pp = set_store_for_write(ps, &pi, name);
3893
3894 /* In the event of a problem return control to the Catch statement below
3895 * to do the clean up - it is not possible to 'return' directly from a Try
3896 * block.
3897 */
3898 if (pp == NULL)
3899 Throw ps;
3900
3901 png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
3902 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
3903
3904#ifdef PNG_TEXT_SUPPORTED
3905 {
3906 static char key[] = "image name"; /* must be writeable */
3907 size_t pos;
3908 png_text text;
3909 char copy[FILE_NAME_SIZE];
3910
3911 /* Use a compressed text string to test the correct interaction of text
3912 * compression and IDAT compression.
3913 */
3914 text.compression = TEXT_COMPRESSION;
3915 text.key = key;
3916 /* Yuck: the text must be writable! */
3917 pos = safecat(copy, sizeof copy, 0, ps->wname);
3918 text.text = copy;
3919 text.text_length = pos;
3920 text.itxt_length = 0;
3921 text.lang = 0;
3922 text.lang_key = 0;
3923
3924 png_set_text(pp, pi, &text, 1);
3925 }
3926#endif
3927
3928 if (colour_type == 3) /* palette */
3929 init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
3930
3931 png_write_info(pp, pi);
3932
3933 /* Calculate the bit size, divide by 8 to get the byte size - this won't
3934 * overflow because we know the w values are all small enough even for
3935 * a system where 'unsigned int' is only 16 bits.
3936 */
3937 pixel_size = bit_size(pp, colour_type, bit_depth);
3938 if (png_get_rowbytes(pp, pi) != ((w * pixel_size) + 7) / 8)
Matt Sarett9ea75692016-01-08 13:00:42 -05003939 png_error(pp, "size row size incorrect");
Chris Craikb50c2172013-07-29 15:28:30 -07003940
3941 else
3942 {
3943 int npasses = npasses_from_interlace_type(pp, interlace_type);
3944 png_uint_32 y;
3945 int pass;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303946# ifdef PNG_WRITE_FILTER_SUPPORTED
3947 int nfilter = PNG_FILTER_VALUE_LAST;
3948# endif
Chris Craikb50c2172013-07-29 15:28:30 -07003949 png_byte image[16][SIZE_ROWMAX];
3950
3951 /* To help consistent error detection make the parts of this buffer
3952 * that aren't set below all '1':
3953 */
3954 memset(image, 0xff, sizeof image);
3955
Matt Sarett9ea75692016-01-08 13:00:42 -05003956 if (!do_interlace &&
3957 npasses != set_write_interlace_handling(pp, interlace_type))
Chris Craikb50c2172013-07-29 15:28:30 -07003958 png_error(pp, "write: png_set_interlace_handling failed");
3959
3960 /* Prepare the whole image first to avoid making it 7 times: */
3961 for (y=0; y<h; ++y)
3962 size_row(image[y], w * pixel_size, y);
3963
3964 for (pass=0; pass<npasses; ++pass)
3965 {
3966 /* The following two are for checking the macros: */
Matt Sarett9ea75692016-01-08 13:00:42 -05003967 const png_uint_32 wPass = PNG_PASS_COLS(w, pass);
Chris Craikb50c2172013-07-29 15:28:30 -07003968
3969 /* If do_interlace is set we don't call png_write_row for every
3970 * row because some of them are empty. In fact, for a 1x1 image,
3971 * most of them are empty!
3972 */
3973 for (y=0; y<h; ++y)
3974 {
3975 png_const_bytep row = image[y];
3976 png_byte tempRow[SIZE_ROWMAX];
3977
3978 /* If do_interlace *and* the image is interlaced we
3979 * need a reduced interlace row; this may be reduced
3980 * to empty.
3981 */
3982 if (do_interlace && interlace_type == PNG_INTERLACE_ADAM7)
3983 {
3984 /* The row must not be written if it doesn't exist, notice
3985 * that there are two conditions here, either the row isn't
3986 * ever in the pass or the row would be but isn't wide
3987 * enough to contribute any pixels. In fact the wPass test
3988 * can be used to skip the whole y loop in this case.
3989 */
3990 if (PNG_ROW_IN_INTERLACE_PASS(y, pass) && wPass > 0)
3991 {
3992 /* Set to all 1's for error detection (libpng tends to
3993 * set unset things to 0).
3994 */
3995 memset(tempRow, 0xff, sizeof tempRow);
Matt Sarett9ea75692016-01-08 13:00:42 -05003996 interlace_row(tempRow, row, pixel_size, w, pass,
3997 0/*data always bigendian*/);
Chris Craikb50c2172013-07-29 15:28:30 -07003998 row = tempRow;
3999 }
4000 else
4001 continue;
4002 }
4003
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304004# ifdef PNG_WRITE_FILTER_SUPPORTED
4005 /* Only get to here if the row has some pixels in it, set the
4006 * filters to 'all' for the very first row and thereafter to a
4007 * single filter. It isn't well documented, but png_set_filter
4008 * does accept a filter number (per the spec) as well as a bit
4009 * mask.
4010 *
4011 * The apparent wackiness of decrementing nfilter rather than
4012 * incrementing is so that Paeth gets used in all images bigger
4013 * than 1 row - it's the tricky one.
4014 */
4015 png_set_filter(pp, 0/*method*/,
4016 nfilter >= PNG_FILTER_VALUE_LAST ? PNG_ALL_FILTERS : nfilter);
4017
4018 if (nfilter-- == 0)
4019 nfilter = PNG_FILTER_VALUE_LAST-1;
4020# endif
4021
Chris Craikb50c2172013-07-29 15:28:30 -07004022 png_write_row(pp, row);
4023 }
4024 }
4025 }
4026
4027#ifdef PNG_TEXT_SUPPORTED
4028 {
4029 static char key[] = "end marker";
4030 static char comment[] = "end";
4031 png_text text;
4032
4033 /* Use a compressed text string to test the correct interaction of text
4034 * compression and IDAT compression.
4035 */
4036 text.compression = TEXT_COMPRESSION;
4037 text.key = key;
4038 text.text = comment;
4039 text.text_length = (sizeof comment)-1;
4040 text.itxt_length = 0;
4041 text.lang = 0;
4042 text.lang_key = 0;
4043
4044 png_set_text(pp, pi, &text, 1);
4045 }
4046#endif
4047
4048 png_write_end(pp, pi);
4049
4050 /* And store this under the appropriate id, then clean up. */
4051 store_storefile(ps, id);
4052
4053 store_write_reset(ps);
4054 }
4055
4056 Catch(fault)
4057 {
4058 /* Use the png_store returned by the exception. This may help the compiler
4059 * because 'ps' is not used in this branch of the setjmp. Note that fault
4060 * and ps will always be the same value.
4061 */
4062 store_write_reset(fault);
4063 }
4064}
4065
4066static void
Matt Sarett9ea75692016-01-08 13:00:42 -05004067make_size(png_store* const ps, png_byte const colour_type, int bdlo,
4068 int const bdhi)
Chris Craikb50c2172013-07-29 15:28:30 -07004069{
4070 for (; bdlo <= bdhi; ++bdlo)
4071 {
4072 png_uint_32 width;
4073
4074 for (width = 1; width <= 16; ++width)
4075 {
4076 png_uint_32 height;
4077
4078 for (height = 1; height <= 16; ++height)
4079 {
4080 /* The four combinations of DIY interlace and interlace or not -
4081 * no interlace + DIY should be identical to no interlace with
4082 * libpng doing it.
4083 */
4084 make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
4085 width, height, 0);
4086 make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
4087 width, height, 1);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304088# ifdef PNG_WRITE_INTERLACING_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07004089 make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
4090 width, height, 0);
Matt Sarett9ea75692016-01-08 13:00:42 -05004091# endif
4092# if CAN_WRITE_INTERLACE
4093 /* 1.7.0 removes the hack that prevented app write of an interlaced
4094 * image if WRITE_INTERLACE was not supported
4095 */
Chris Craikb50c2172013-07-29 15:28:30 -07004096 make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
4097 width, height, 1);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304098# endif
Chris Craikb50c2172013-07-29 15:28:30 -07004099 }
4100 }
4101 }
4102}
4103
4104static void
4105make_size_images(png_store *ps)
4106{
4107 /* This is in case of errors. */
4108 safecat(ps->test, sizeof ps->test, 0, "make size images");
4109
4110 /* Arguments are colour_type, low bit depth, high bit depth
4111 */
4112 make_size(ps, 0, 0, WRITE_BDHI);
4113 make_size(ps, 2, 3, WRITE_BDHI);
4114 make_size(ps, 3, 0, 3 /*palette: max 8 bits*/);
4115 make_size(ps, 4, 3, WRITE_BDHI);
4116 make_size(ps, 6, 3, WRITE_BDHI);
4117}
4118
4119#ifdef PNG_READ_SUPPORTED
4120/* Return a row based on image id and 'y' for checking: */
4121static void
4122standard_row(png_const_structp pp, png_byte std[STANDARD_ROWMAX],
4123 png_uint_32 id, png_uint_32 y)
4124{
4125 if (WIDTH_FROM_ID(id) == 0)
4126 transform_row(pp, std, COL_FROM_ID(id), DEPTH_FROM_ID(id), y);
4127 else
4128 size_row(std, WIDTH_FROM_ID(id) * bit_size(pp, COL_FROM_ID(id),
4129 DEPTH_FROM_ID(id)), y);
4130}
4131#endif /* PNG_READ_SUPPORTED */
4132
4133/* Tests - individual test cases */
4134/* Like 'make_standard' but errors are deliberately introduced into the calls
4135 * to ensure that they get detected - it should not be possible to write an
4136 * invalid image with libpng!
4137 */
4138/* TODO: the 'set' functions can probably all be made to take a
4139 * png_const_structp rather than a modifiable one.
4140 */
4141#ifdef PNG_WARNINGS_SUPPORTED
4142static void
4143sBIT0_error_fn(png_structp pp, png_infop pi)
4144{
4145 /* 0 is invalid... */
4146 png_color_8 bad;
4147 bad.red = bad.green = bad.blue = bad.gray = bad.alpha = 0;
4148 png_set_sBIT(pp, pi, &bad);
4149}
4150
4151static void
4152sBIT_error_fn(png_structp pp, png_infop pi)
4153{
4154 png_byte bit_depth;
4155 png_color_8 bad;
4156
4157 if (png_get_color_type(pp, pi) == PNG_COLOR_TYPE_PALETTE)
4158 bit_depth = 8;
4159
4160 else
4161 bit_depth = png_get_bit_depth(pp, pi);
4162
4163 /* Now we know the bit depth we can easily generate an invalid sBIT entry */
4164 bad.red = bad.green = bad.blue = bad.gray = bad.alpha =
4165 (png_byte)(bit_depth+1);
4166 png_set_sBIT(pp, pi, &bad);
4167}
4168
Matt Sarett9ea75692016-01-08 13:00:42 -05004169static const struct
Chris Craikb50c2172013-07-29 15:28:30 -07004170{
4171 void (*fn)(png_structp, png_infop);
Matt Sarett9ea75692016-01-08 13:00:42 -05004172 const char *msg;
Chris Craikb50c2172013-07-29 15:28:30 -07004173 unsigned int warning :1; /* the error is a warning... */
4174} error_test[] =
4175 {
Matt Sarett9ea75692016-01-08 13:00:42 -05004176 /* no warnings makes these errors undetectable prior to 1.7.0 */
4177 { sBIT0_error_fn, "sBIT(0): failed to detect error",
4178 PNG_LIBPNG_VER < 10700 },
4179
4180 { sBIT_error_fn, "sBIT(too big): failed to detect error",
4181 PNG_LIBPNG_VER < 10700 },
Chris Craikb50c2172013-07-29 15:28:30 -07004182 };
4183
4184static void
Matt Sarett9ea75692016-01-08 13:00:42 -05004185make_error(png_store* const ps, png_byte const colour_type,
Chris Craikb50c2172013-07-29 15:28:30 -07004186 png_byte bit_depth, int interlace_type, int test, png_const_charp name)
4187{
Chris Craikb50c2172013-07-29 15:28:30 -07004188 context(ps, fault);
4189
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304190 check_interlace_type(interlace_type);
4191
Chris Craikb50c2172013-07-29 15:28:30 -07004192 Try
4193 {
Chris Craikb50c2172013-07-29 15:28:30 -07004194 png_infop pi;
Matt Sarett9ea75692016-01-08 13:00:42 -05004195 const png_structp pp = set_store_for_write(ps, &pi, name);
4196 png_uint_32 w, h;
4197 gnu_volatile(pp)
Chris Craikb50c2172013-07-29 15:28:30 -07004198
4199 if (pp == NULL)
4200 Throw ps;
4201
Matt Sarett9ea75692016-01-08 13:00:42 -05004202 w = transform_width(pp, colour_type, bit_depth);
4203 gnu_volatile(w)
4204 h = transform_height(pp, colour_type, bit_depth);
4205 gnu_volatile(h)
4206 png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
4207 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
Chris Craikb50c2172013-07-29 15:28:30 -07004208
4209 if (colour_type == 3) /* palette */
4210 init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
4211
4212 /* Time for a few errors; these are in various optional chunks, the
4213 * standard tests test the standard chunks pretty well.
4214 */
4215# define exception__prev exception_prev_1
4216# define exception__env exception_env_1
4217 Try
4218 {
Matt Sarett9ea75692016-01-08 13:00:42 -05004219 gnu_volatile(exception__prev)
4220
Chris Craikb50c2172013-07-29 15:28:30 -07004221 /* Expect this to throw: */
4222 ps->expect_error = !error_test[test].warning;
4223 ps->expect_warning = error_test[test].warning;
4224 ps->saw_warning = 0;
4225 error_test[test].fn(pp, pi);
4226
4227 /* Normally the error is only detected here: */
4228 png_write_info(pp, pi);
4229
4230 /* And handle the case where it was only a warning: */
4231 if (ps->expect_warning && ps->saw_warning)
4232 Throw ps;
4233
4234 /* If we get here there is a problem, we have success - no error or
4235 * no warning - when we shouldn't have success. Log an error.
4236 */
4237 store_log(ps, pp, error_test[test].msg, 1 /*error*/);
4238 }
4239
4240 Catch (fault)
Matt Sarett9ea75692016-01-08 13:00:42 -05004241 { /* expected exit */
4242 }
Chris Craikb50c2172013-07-29 15:28:30 -07004243#undef exception__prev
4244#undef exception__env
4245
4246 /* And clear these flags */
4247 ps->expect_error = 0;
4248 ps->expect_warning = 0;
4249
4250 /* Now write the whole image, just to make sure that the detected, or
4251 * undetected, errro has not created problems inside libpng.
4252 */
4253 if (png_get_rowbytes(pp, pi) !=
4254 transform_rowsize(pp, colour_type, bit_depth))
4255 png_error(pp, "row size incorrect");
4256
4257 else
4258 {
Matt Sarett9ea75692016-01-08 13:00:42 -05004259 int npasses = set_write_interlace_handling(pp, interlace_type);
Chris Craikb50c2172013-07-29 15:28:30 -07004260 int pass;
4261
4262 if (npasses != npasses_from_interlace_type(pp, interlace_type))
4263 png_error(pp, "write: png_set_interlace_handling failed");
4264
4265 for (pass=0; pass<npasses; ++pass)
4266 {
4267 png_uint_32 y;
4268
4269 for (y=0; y<h; ++y)
4270 {
4271 png_byte buffer[TRANSFORM_ROWMAX];
4272
4273 transform_row(pp, buffer, colour_type, bit_depth, y);
Matt Sarett9ea75692016-01-08 13:00:42 -05004274
4275# if do_own_interlace
4276 /* If do_own_interlace *and* the image is interlaced we need a
4277 * reduced interlace row; this may be reduced to empty.
4278 */
4279 if (interlace_type == PNG_INTERLACE_ADAM7)
4280 {
4281 /* The row must not be written if it doesn't exist, notice
4282 * that there are two conditions here, either the row isn't
4283 * ever in the pass or the row would be but isn't wide
4284 * enough to contribute any pixels. In fact the wPass test
4285 * can be used to skip the whole y loop in this case.
4286 */
4287 if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
4288 PNG_PASS_COLS(w, pass) > 0)
4289 interlace_row(buffer, buffer,
4290 bit_size(pp, colour_type, bit_depth), w, pass,
4291 0/*data always bigendian*/);
4292 else
4293 continue;
4294 }
4295# endif /* do_own_interlace */
4296
Chris Craikb50c2172013-07-29 15:28:30 -07004297 png_write_row(pp, buffer);
4298 }
4299 }
4300 }
4301
4302 png_write_end(pp, pi);
4303
4304 /* The following deletes the file that was just written. */
4305 store_write_reset(ps);
4306 }
4307
4308 Catch(fault)
4309 {
4310 store_write_reset(fault);
4311 }
4312}
4313
4314static int
Matt Sarett9ea75692016-01-08 13:00:42 -05004315make_errors(png_modifier* const pm, png_byte const colour_type,
4316 int bdlo, int const bdhi)
Chris Craikb50c2172013-07-29 15:28:30 -07004317{
4318 for (; bdlo <= bdhi; ++bdlo)
4319 {
4320 int interlace_type;
4321
4322 for (interlace_type = PNG_INTERLACE_NONE;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304323 interlace_type < INTERLACE_LAST; ++interlace_type)
Chris Craikb50c2172013-07-29 15:28:30 -07004324 {
4325 unsigned int test;
4326 char name[FILE_NAME_SIZE];
4327
4328 standard_name(name, sizeof name, 0, colour_type, 1<<bdlo, 0,
Matt Sarett9ea75692016-01-08 13:00:42 -05004329 interlace_type, 0, 0, do_own_interlace);
Chris Craikb50c2172013-07-29 15:28:30 -07004330
Matt Sarett9ea75692016-01-08 13:00:42 -05004331 for (test=0; test<ARRAY_SIZE(error_test); ++test)
Chris Craikb50c2172013-07-29 15:28:30 -07004332 {
4333 make_error(&pm->this, colour_type, DEPTH(bdlo), interlace_type,
4334 test, name);
4335
4336 if (fail(pm))
4337 return 0;
4338 }
4339 }
4340 }
4341
4342 return 1; /* keep going */
4343}
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304344#endif /* PNG_WARNINGS_SUPPORTED */
Chris Craikb50c2172013-07-29 15:28:30 -07004345
4346static void
4347perform_error_test(png_modifier *pm)
4348{
4349#ifdef PNG_WARNINGS_SUPPORTED /* else there are no cases that work! */
4350 /* Need to do this here because we just write in this test. */
4351 safecat(pm->this.test, sizeof pm->this.test, 0, "error test");
4352
4353 if (!make_errors(pm, 0, 0, WRITE_BDHI))
4354 return;
4355
4356 if (!make_errors(pm, 2, 3, WRITE_BDHI))
4357 return;
4358
4359 if (!make_errors(pm, 3, 0, 3))
4360 return;
4361
4362 if (!make_errors(pm, 4, 3, WRITE_BDHI))
4363 return;
4364
4365 if (!make_errors(pm, 6, 3, WRITE_BDHI))
4366 return;
4367#else
4368 UNUSED(pm)
4369#endif
4370}
4371
4372/* This is just to validate the internal PNG formatting code - if this fails
4373 * then the warning messages the library outputs will probably be garbage.
4374 */
4375static void
Matt Sarett9ea75692016-01-08 13:00:42 -05004376perform_formatting_test(png_store *ps)
Chris Craikb50c2172013-07-29 15:28:30 -07004377{
4378#ifdef PNG_TIME_RFC1123_SUPPORTED
4379 /* The handle into the formatting code is the RFC1123 support; this test does
4380 * nothing if that is compiled out.
4381 */
4382 context(ps, fault);
4383
4384 Try
4385 {
4386 png_const_charp correct = "29 Aug 2079 13:53:60 +0000";
4387 png_const_charp result;
4388# if PNG_LIBPNG_VER >= 10600
4389 char timestring[29];
4390# endif
4391 png_structp pp;
4392 png_time pt;
4393
4394 pp = set_store_for_write(ps, NULL, "libpng formatting test");
4395
4396 if (pp == NULL)
4397 Throw ps;
4398
4399
4400 /* Arbitrary settings: */
4401 pt.year = 2079;
4402 pt.month = 8;
4403 pt.day = 29;
4404 pt.hour = 13;
4405 pt.minute = 53;
4406 pt.second = 60; /* a leap second */
4407
4408# if PNG_LIBPNG_VER < 10600
4409 result = png_convert_to_rfc1123(pp, &pt);
4410# else
4411 if (png_convert_to_rfc1123_buffer(timestring, &pt))
4412 result = timestring;
4413
4414 else
4415 result = NULL;
4416# endif
4417
4418 if (result == NULL)
4419 png_error(pp, "png_convert_to_rfc1123 failed");
4420
4421 if (strcmp(result, correct) != 0)
4422 {
4423 size_t pos = 0;
4424 char msg[128];
4425
4426 pos = safecat(msg, sizeof msg, pos, "png_convert_to_rfc1123(");
4427 pos = safecat(msg, sizeof msg, pos, correct);
4428 pos = safecat(msg, sizeof msg, pos, ") returned: '");
4429 pos = safecat(msg, sizeof msg, pos, result);
4430 pos = safecat(msg, sizeof msg, pos, "'");
4431
4432 png_error(pp, msg);
4433 }
4434
4435 store_write_reset(ps);
4436 }
4437
4438 Catch(fault)
4439 {
4440 store_write_reset(fault);
4441 }
4442#else
4443 UNUSED(ps)
4444#endif
4445}
4446
4447#ifdef PNG_READ_SUPPORTED
4448/* Because we want to use the same code in both the progressive reader and the
4449 * sequential reader it is necessary to deal with the fact that the progressive
4450 * reader callbacks only have one parameter (png_get_progressive_ptr()), so this
4451 * must contain all the test parameters and all the local variables directly
4452 * accessible to the sequential reader implementation.
4453 *
4454 * The technique adopted is to reinvent part of what Dijkstra termed a
4455 * 'display'; an array of pointers to the stack frames of enclosing functions so
4456 * that a nested function definition can access the local (C auto) variables of
4457 * the functions that contain its definition. In fact C provides the first
4458 * pointer (the local variables - the stack frame pointer) and the last (the
4459 * global variables - the BCPL global vector typically implemented as global
4460 * addresses), this code requires one more pointer to make the display - the
4461 * local variables (and function call parameters) of the function that actually
4462 * invokes either the progressive or sequential reader.
4463 *
4464 * Perhaps confusingly this technique is confounded with classes - the
4465 * 'standard_display' defined here is sub-classed as the 'gamma_display' below.
4466 * A gamma_display is a standard_display, taking advantage of the ANSI-C
4467 * requirement that the pointer to the first member of a structure must be the
4468 * same as the pointer to the structure. This allows us to reuse standard_
4469 * functions in the gamma test code; something that could not be done with
4470 * nested functions!
4471 */
4472typedef struct standard_display
4473{
4474 png_store* ps; /* Test parameters (passed to the function) */
4475 png_byte colour_type;
4476 png_byte bit_depth;
4477 png_byte red_sBIT; /* Input data sBIT values. */
4478 png_byte green_sBIT;
4479 png_byte blue_sBIT;
4480 png_byte alpha_sBIT;
Matt Sarett9ea75692016-01-08 13:00:42 -05004481 png_byte interlace_type;
4482 png_byte filler; /* Output has a filler */
Chris Craikb50c2172013-07-29 15:28:30 -07004483 png_uint_32 id; /* Calculated file ID */
4484 png_uint_32 w; /* Width of image */
4485 png_uint_32 h; /* Height of image */
4486 int npasses; /* Number of interlaced passes */
4487 png_uint_32 pixel_size; /* Width of one pixel in bits */
4488 png_uint_32 bit_width; /* Width of output row in bits */
4489 size_t cbRow; /* Bytes in a row of the output image */
4490 int do_interlace; /* Do interlacing internally */
Matt Sarett9ea75692016-01-08 13:00:42 -05004491 int littleendian; /* App (row) data is little endian */
Chris Craikb50c2172013-07-29 15:28:30 -07004492 int is_transparent; /* Transparency information was present. */
Matt Sarett9ea75692016-01-08 13:00:42 -05004493 int has_tRNS; /* color type GRAY or RGB with a tRNS chunk. */
Chris Craikb50c2172013-07-29 15:28:30 -07004494 int speed; /* Doing a speed test */
4495 int use_update_info;/* Call update_info, not start_image */
4496 struct
4497 {
4498 png_uint_16 red;
4499 png_uint_16 green;
4500 png_uint_16 blue;
4501 } transparent; /* The transparent color, if set. */
4502 int npalette; /* Number of entries in the palette. */
4503 store_palette
4504 palette;
4505} standard_display;
4506
4507static void
4508standard_display_init(standard_display *dp, png_store* ps, png_uint_32 id,
4509 int do_interlace, int use_update_info)
4510{
4511 memset(dp, 0, sizeof *dp);
4512
4513 dp->ps = ps;
4514 dp->colour_type = COL_FROM_ID(id);
4515 dp->bit_depth = DEPTH_FROM_ID(id);
4516 if (dp->bit_depth < 1 || dp->bit_depth > 16)
4517 internal_error(ps, "internal: bad bit depth");
4518 if (dp->colour_type == 3)
4519 dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = 8;
4520 else
4521 dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT =
4522 dp->bit_depth;
4523 dp->interlace_type = INTERLACE_FROM_ID(id);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304524 check_interlace_type(dp->interlace_type);
Chris Craikb50c2172013-07-29 15:28:30 -07004525 dp->id = id;
4526 /* All the rest are filled in after the read_info: */
4527 dp->w = 0;
4528 dp->h = 0;
4529 dp->npasses = 0;
4530 dp->pixel_size = 0;
4531 dp->bit_width = 0;
4532 dp->cbRow = 0;
4533 dp->do_interlace = do_interlace;
Matt Sarett9ea75692016-01-08 13:00:42 -05004534 dp->littleendian = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07004535 dp->is_transparent = 0;
4536 dp->speed = ps->speed;
4537 dp->use_update_info = use_update_info;
4538 dp->npalette = 0;
4539 /* Preset the transparent color to black: */
4540 memset(&dp->transparent, 0, sizeof dp->transparent);
4541 /* Preset the palette to full intensity/opaque througout: */
4542 memset(dp->palette, 0xff, sizeof dp->palette);
4543}
4544
4545/* Initialize the palette fields - this must be done later because the palette
4546 * comes from the particular png_store_file that is selected.
4547 */
4548static void
4549standard_palette_init(standard_display *dp)
4550{
4551 store_palette_entry *palette = store_current_palette(dp->ps, &dp->npalette);
4552
4553 /* The remaining entries remain white/opaque. */
4554 if (dp->npalette > 0)
4555 {
4556 int i = dp->npalette;
4557 memcpy(dp->palette, palette, i * sizeof *palette);
4558
4559 /* Check for a non-opaque palette entry: */
4560 while (--i >= 0)
4561 if (palette[i].alpha < 255)
4562 break;
4563
4564# ifdef __GNUC__
4565 /* GCC can't handle the more obviously optimizable version. */
4566 if (i >= 0)
4567 dp->is_transparent = 1;
4568 else
4569 dp->is_transparent = 0;
4570# else
4571 dp->is_transparent = (i >= 0);
4572# endif
4573 }
4574}
4575
4576/* Utility to read the palette from the PNG file and convert it into
4577 * store_palette format. This returns 1 if there is any transparency in the
4578 * palette (it does not check for a transparent colour in the non-palette case.)
4579 */
4580static int
4581read_palette(store_palette palette, int *npalette, png_const_structp pp,
4582 png_infop pi)
4583{
4584 png_colorp pal;
4585 png_bytep trans_alpha;
4586 int num;
4587
4588 pal = 0;
4589 *npalette = -1;
4590
4591 if (png_get_PLTE(pp, pi, &pal, npalette) & PNG_INFO_PLTE)
4592 {
4593 int i = *npalette;
4594
4595 if (i <= 0 || i > 256)
4596 png_error(pp, "validate: invalid PLTE count");
4597
4598 while (--i >= 0)
4599 {
4600 palette[i].red = pal[i].red;
4601 palette[i].green = pal[i].green;
4602 palette[i].blue = pal[i].blue;
4603 }
4604
4605 /* Mark the remainder of the entries with a flag value (other than
4606 * white/opaque which is the flag value stored above.)
4607 */
4608 memset(palette + *npalette, 126, (256-*npalette) * sizeof *palette);
4609 }
4610
4611 else /* !png_get_PLTE */
4612 {
4613 if (*npalette != (-1))
4614 png_error(pp, "validate: invalid PLTE result");
4615 /* But there is no palette, so record this: */
4616 *npalette = 0;
4617 memset(palette, 113, sizeof (store_palette));
4618 }
4619
4620 trans_alpha = 0;
4621 num = 2; /* force error below */
4622 if ((png_get_tRNS(pp, pi, &trans_alpha, &num, 0) & PNG_INFO_tRNS) != 0 &&
4623 (trans_alpha != NULL || num != 1/*returns 1 for a transparent color*/) &&
4624 /* Oops, if a palette tRNS gets expanded png_read_update_info (at least so
4625 * far as 1.5.4) does not remove the trans_alpha pointer, only num_trans,
4626 * so in the above call we get a success, we get a pointer (who knows what
4627 * to) and we get num_trans == 0:
4628 */
4629 !(trans_alpha != NULL && num == 0)) /* TODO: fix this in libpng. */
4630 {
4631 int i;
4632
4633 /* Any of these are crash-worthy - given the implementation of
4634 * png_get_tRNS up to 1.5 an app won't crash if it just checks the
4635 * result above and fails to check that the variables it passed have
4636 * actually been filled in! Note that if the app were to pass the
4637 * last, png_color_16p, variable too it couldn't rely on this.
4638 */
4639 if (trans_alpha == NULL || num <= 0 || num > 256 || num > *npalette)
4640 png_error(pp, "validate: unexpected png_get_tRNS (palette) result");
4641
4642 for (i=0; i<num; ++i)
4643 palette[i].alpha = trans_alpha[i];
4644
4645 for (num=*npalette; i<num; ++i)
4646 palette[i].alpha = 255;
4647
4648 for (; i<256; ++i)
4649 palette[i].alpha = 33; /* flag value */
4650
4651 return 1; /* transparency */
4652 }
4653
4654 else
4655 {
4656 /* No palette transparency - just set the alpha channel to opaque. */
4657 int i;
4658
4659 for (i=0, num=*npalette; i<num; ++i)
4660 palette[i].alpha = 255;
4661
4662 for (; i<256; ++i)
4663 palette[i].alpha = 55; /* flag value */
4664
4665 return 0; /* no transparency */
4666 }
4667}
4668
4669/* Utility to validate the palette if it should not have changed (the
4670 * non-transform case).
4671 */
4672static void
4673standard_palette_validate(standard_display *dp, png_const_structp pp,
4674 png_infop pi)
4675{
4676 int npalette;
4677 store_palette palette;
4678
4679 if (read_palette(palette, &npalette, pp, pi) != dp->is_transparent)
4680 png_error(pp, "validate: palette transparency changed");
4681
4682 if (npalette != dp->npalette)
4683 {
4684 size_t pos = 0;
4685 char msg[64];
4686
4687 pos = safecat(msg, sizeof msg, pos, "validate: palette size changed: ");
4688 pos = safecatn(msg, sizeof msg, pos, dp->npalette);
4689 pos = safecat(msg, sizeof msg, pos, " -> ");
4690 pos = safecatn(msg, sizeof msg, pos, npalette);
4691 png_error(pp, msg);
4692 }
4693
4694 {
4695 int i = npalette; /* npalette is aliased */
4696
4697 while (--i >= 0)
4698 if (palette[i].red != dp->palette[i].red ||
4699 palette[i].green != dp->palette[i].green ||
4700 palette[i].blue != dp->palette[i].blue ||
4701 palette[i].alpha != dp->palette[i].alpha)
4702 png_error(pp, "validate: PLTE or tRNS chunk changed");
4703 }
4704}
4705
4706/* By passing a 'standard_display' the progressive callbacks can be used
4707 * directly by the sequential code, the functions suffixed "_imp" are the
4708 * implementations, the functions without the suffix are the callbacks.
4709 *
4710 * The code for the info callback is split into two because this callback calls
4711 * png_read_update_info or png_start_read_image and what gets called depends on
4712 * whether the info needs updating (we want to test both calls in pngvalid.)
4713 */
4714static void
4715standard_info_part1(standard_display *dp, png_structp pp, png_infop pi)
4716{
4717 if (png_get_bit_depth(pp, pi) != dp->bit_depth)
4718 png_error(pp, "validate: bit depth changed");
4719
4720 if (png_get_color_type(pp, pi) != dp->colour_type)
4721 png_error(pp, "validate: color type changed");
4722
4723 if (png_get_filter_type(pp, pi) != PNG_FILTER_TYPE_BASE)
4724 png_error(pp, "validate: filter type changed");
4725
4726 if (png_get_interlace_type(pp, pi) != dp->interlace_type)
4727 png_error(pp, "validate: interlacing changed");
4728
4729 if (png_get_compression_type(pp, pi) != PNG_COMPRESSION_TYPE_BASE)
4730 png_error(pp, "validate: compression type changed");
4731
4732 dp->w = png_get_image_width(pp, pi);
4733
4734 if (dp->w != standard_width(pp, dp->id))
4735 png_error(pp, "validate: image width changed");
4736
4737 dp->h = png_get_image_height(pp, pi);
4738
4739 if (dp->h != standard_height(pp, dp->id))
4740 png_error(pp, "validate: image height changed");
4741
4742 /* Record (but don't check at present) the input sBIT according to the colour
4743 * type information.
4744 */
4745 {
4746 png_color_8p sBIT = 0;
4747
4748 if (png_get_sBIT(pp, pi, &sBIT) & PNG_INFO_sBIT)
4749 {
4750 int sBIT_invalid = 0;
4751
4752 if (sBIT == 0)
4753 png_error(pp, "validate: unexpected png_get_sBIT result");
4754
4755 if (dp->colour_type & PNG_COLOR_MASK_COLOR)
4756 {
4757 if (sBIT->red == 0 || sBIT->red > dp->bit_depth)
4758 sBIT_invalid = 1;
4759 else
4760 dp->red_sBIT = sBIT->red;
4761
4762 if (sBIT->green == 0 || sBIT->green > dp->bit_depth)
4763 sBIT_invalid = 1;
4764 else
4765 dp->green_sBIT = sBIT->green;
4766
4767 if (sBIT->blue == 0 || sBIT->blue > dp->bit_depth)
4768 sBIT_invalid = 1;
4769 else
4770 dp->blue_sBIT = sBIT->blue;
4771 }
4772
4773 else /* !COLOR */
4774 {
4775 if (sBIT->gray == 0 || sBIT->gray > dp->bit_depth)
4776 sBIT_invalid = 1;
4777 else
4778 dp->blue_sBIT = dp->green_sBIT = dp->red_sBIT = sBIT->gray;
4779 }
4780
4781 /* All 8 bits in tRNS for a palette image are significant - see the
4782 * spec.
4783 */
4784 if (dp->colour_type & PNG_COLOR_MASK_ALPHA)
4785 {
4786 if (sBIT->alpha == 0 || sBIT->alpha > dp->bit_depth)
4787 sBIT_invalid = 1;
4788 else
4789 dp->alpha_sBIT = sBIT->alpha;
4790 }
4791
4792 if (sBIT_invalid)
4793 png_error(pp, "validate: sBIT value out of range");
4794 }
4795 }
4796
4797 /* Important: this is validating the value *before* any transforms have been
4798 * put in place. It doesn't matter for the standard tests, where there are
4799 * no transforms, but it does for other tests where rowbytes may change after
4800 * png_read_update_info.
4801 */
4802 if (png_get_rowbytes(pp, pi) != standard_rowsize(pp, dp->id))
4803 png_error(pp, "validate: row size changed");
4804
4805 /* Validate the colour type 3 palette (this can be present on other color
4806 * types.)
4807 */
4808 standard_palette_validate(dp, pp, pi);
4809
4810 /* In any case always check for a tranparent color (notice that the
4811 * colour type 3 case must not give a successful return on the get_tRNS call
4812 * with these arguments!)
4813 */
4814 {
4815 png_color_16p trans_color = 0;
4816
4817 if (png_get_tRNS(pp, pi, 0, 0, &trans_color) & PNG_INFO_tRNS)
4818 {
4819 if (trans_color == 0)
4820 png_error(pp, "validate: unexpected png_get_tRNS (color) result");
4821
4822 switch (dp->colour_type)
4823 {
4824 case 0:
4825 dp->transparent.red = dp->transparent.green = dp->transparent.blue =
4826 trans_color->gray;
Matt Sarett9ea75692016-01-08 13:00:42 -05004827 dp->has_tRNS = 1;
Chris Craikb50c2172013-07-29 15:28:30 -07004828 break;
4829
4830 case 2:
4831 dp->transparent.red = trans_color->red;
4832 dp->transparent.green = trans_color->green;
4833 dp->transparent.blue = trans_color->blue;
Matt Sarett9ea75692016-01-08 13:00:42 -05004834 dp->has_tRNS = 1;
Chris Craikb50c2172013-07-29 15:28:30 -07004835 break;
4836
4837 case 3:
4838 /* Not expected because it should result in the array case
4839 * above.
4840 */
4841 png_error(pp, "validate: unexpected png_get_tRNS result");
4842 break;
4843
4844 default:
4845 png_error(pp, "validate: invalid tRNS chunk with alpha image");
4846 }
4847 }
4848 }
4849
4850 /* Read the number of passes - expected to match the value used when
4851 * creating the image (interlaced or not). This has the side effect of
4852 * turning on interlace handling (if do_interlace is not set.)
4853 */
4854 dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type);
Matt Sarett9ea75692016-01-08 13:00:42 -05004855 if (!dp->do_interlace)
4856 {
4857# ifdef PNG_READ_INTERLACING_SUPPORTED
4858 if (dp->npasses != png_set_interlace_handling(pp))
4859 png_error(pp, "validate: file changed interlace type");
4860# else /* !READ_INTERLACING */
4861 /* This should never happen: the relevant tests (!do_interlace) should
4862 * not be run.
4863 */
4864 if (dp->npasses > 1)
4865 png_error(pp, "validate: no libpng interlace support");
4866# endif /* !READ_INTERLACING */
4867 }
Chris Craikb50c2172013-07-29 15:28:30 -07004868
4869 /* Caller calls png_read_update_info or png_start_read_image now, then calls
4870 * part2.
4871 */
4872}
4873
4874/* This must be called *after* the png_read_update_info call to get the correct
4875 * 'rowbytes' value, otherwise png_get_rowbytes will refer to the untransformed
4876 * image.
4877 */
4878static void
4879standard_info_part2(standard_display *dp, png_const_structp pp,
4880 png_const_infop pi, int nImages)
4881{
4882 /* Record cbRow now that it can be found. */
Matt Sarett9ea75692016-01-08 13:00:42 -05004883 {
4884 png_byte ct = png_get_color_type(pp, pi);
4885 png_byte bd = png_get_bit_depth(pp, pi);
4886
4887 if (bd >= 8 && (ct == PNG_COLOR_TYPE_RGB || ct == PNG_COLOR_TYPE_GRAY) &&
4888 dp->filler)
4889 ct |= 4; /* handle filler as faked alpha channel */
4890
4891 dp->pixel_size = bit_size(pp, ct, bd);
4892 }
Chris Craikb50c2172013-07-29 15:28:30 -07004893 dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
4894 dp->cbRow = png_get_rowbytes(pp, pi);
4895
4896 /* Validate the rowbytes here again. */
4897 if (dp->cbRow != (dp->bit_width+7)/8)
4898 png_error(pp, "bad png_get_rowbytes calculation");
4899
4900 /* Then ensure there is enough space for the output image(s). */
4901 store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
4902}
4903
4904static void
4905standard_info_imp(standard_display *dp, png_structp pp, png_infop pi,
4906 int nImages)
4907{
4908 /* Note that the validation routine has the side effect of turning on
4909 * interlace handling in the subsequent code.
4910 */
4911 standard_info_part1(dp, pp, pi);
4912
4913 /* And the info callback has to call this (or png_read_update_info - see
4914 * below in the png_modifier code for that variant.
4915 */
4916 if (dp->use_update_info)
4917 {
4918 /* For debugging the effect of multiple calls: */
4919 int i = dp->use_update_info;
4920 while (i-- > 0)
4921 png_read_update_info(pp, pi);
4922 }
4923
4924 else
4925 png_start_read_image(pp);
4926
4927 /* Validate the height, width and rowbytes plus ensure that sufficient buffer
4928 * exists for decoding the image.
4929 */
4930 standard_info_part2(dp, pp, pi, nImages);
4931}
4932
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304933static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07004934standard_info(png_structp pp, png_infop pi)
4935{
4936 standard_display *dp = voidcast(standard_display*,
4937 png_get_progressive_ptr(pp));
4938
4939 /* Call with nImages==1 because the progressive reader can only produce one
4940 * image.
4941 */
4942 standard_info_imp(dp, pp, pi, 1 /*only one image*/);
4943}
4944
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304945static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07004946progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass)
4947{
4948 png_const_structp pp = ppIn;
Matt Sarett9ea75692016-01-08 13:00:42 -05004949 const standard_display *dp = voidcast(standard_display*,
Chris Craikb50c2172013-07-29 15:28:30 -07004950 png_get_progressive_ptr(pp));
4951
4952 /* When handling interlacing some rows will be absent in each pass, the
4953 * callback still gets called, but with a NULL pointer. This is checked
4954 * in the 'else' clause below. We need our own 'cbRow', but we can't call
4955 * png_get_rowbytes because we got no info structure.
4956 */
4957 if (new_row != NULL)
4958 {
4959 png_bytep row;
4960
4961 /* In the case where the reader doesn't do the interlace it gives
4962 * us the y in the sub-image:
4963 */
4964 if (dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7)
4965 {
4966#ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED
4967 /* Use this opportunity to validate the png 'current' APIs: */
4968 if (y != png_get_current_row_number(pp))
4969 png_error(pp, "png_get_current_row_number is broken");
4970
4971 if (pass != png_get_current_pass_number(pp))
4972 png_error(pp, "png_get_current_pass_number is broken");
Matt Sarett9ea75692016-01-08 13:00:42 -05004973#endif /* USER_TRANSFORM_INFO */
Chris Craikb50c2172013-07-29 15:28:30 -07004974
4975 y = PNG_ROW_FROM_PASS_ROW(y, pass);
4976 }
4977
4978 /* Validate this just in case. */
4979 if (y >= dp->h)
4980 png_error(pp, "invalid y to progressive row callback");
4981
4982 row = store_image_row(dp->ps, pp, 0, y);
4983
Chris Craikb50c2172013-07-29 15:28:30 -07004984 /* Combine the new row into the old: */
Matt Sarett9ea75692016-01-08 13:00:42 -05004985#ifdef PNG_READ_INTERLACING_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07004986 if (dp->do_interlace)
Matt Sarett9ea75692016-01-08 13:00:42 -05004987#endif /* READ_INTERLACING */
Chris Craikb50c2172013-07-29 15:28:30 -07004988 {
4989 if (dp->interlace_type == PNG_INTERLACE_ADAM7)
Matt Sarett9ea75692016-01-08 13:00:42 -05004990 deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass,
4991 dp->littleendian);
Chris Craikb50c2172013-07-29 15:28:30 -07004992 else
Matt Sarett9ea75692016-01-08 13:00:42 -05004993 row_copy(row, new_row, dp->pixel_size * dp->w, dp->littleendian);
Chris Craikb50c2172013-07-29 15:28:30 -07004994 }
Matt Sarett9ea75692016-01-08 13:00:42 -05004995#ifdef PNG_READ_INTERLACING_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07004996 else
4997 png_progressive_combine_row(pp, row, new_row);
4998#endif /* PNG_READ_INTERLACING_SUPPORTED */
4999 }
5000
Chris Craikb50c2172013-07-29 15:28:30 -07005001 else if (dp->interlace_type == PNG_INTERLACE_ADAM7 &&
5002 PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
5003 PNG_PASS_COLS(dp->w, pass) > 0)
5004 png_error(pp, "missing row in progressive de-interlacing");
Chris Craikb50c2172013-07-29 15:28:30 -07005005}
5006
5007static void
5008sequential_row(standard_display *dp, png_structp pp, png_infop pi,
Matt Sarett9ea75692016-01-08 13:00:42 -05005009 const int iImage, const int iDisplay)
Chris Craikb50c2172013-07-29 15:28:30 -07005010{
Matt Sarett9ea75692016-01-08 13:00:42 -05005011 const int npasses = dp->npasses;
5012 const int do_interlace = dp->do_interlace &&
Chris Craikb50c2172013-07-29 15:28:30 -07005013 dp->interlace_type == PNG_INTERLACE_ADAM7;
Matt Sarett9ea75692016-01-08 13:00:42 -05005014 const png_uint_32 height = standard_height(pp, dp->id);
5015 const png_uint_32 width = standard_width(pp, dp->id);
5016 const png_store* ps = dp->ps;
Chris Craikb50c2172013-07-29 15:28:30 -07005017 int pass;
5018
5019 for (pass=0; pass<npasses; ++pass)
5020 {
5021 png_uint_32 y;
5022 png_uint_32 wPass = PNG_PASS_COLS(width, pass);
5023
5024 for (y=0; y<height; ++y)
5025 {
5026 if (do_interlace)
5027 {
5028 /* wPass may be zero or this row may not be in this pass.
5029 * png_read_row must not be called in either case.
5030 */
5031 if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass))
5032 {
5033 /* Read the row into a pair of temporary buffers, then do the
5034 * merge here into the output rows.
5035 */
5036 png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX];
5037
5038 /* The following aids (to some extent) error detection - we can
5039 * see where png_read_row wrote. Use opposite values in row and
5040 * display to make this easier. Don't use 0xff (which is used in
5041 * the image write code to fill unused bits) or 0 (which is a
5042 * likely value to overwrite unused bits with).
5043 */
5044 memset(row, 0xc5, sizeof row);
5045 memset(display, 0x5c, sizeof display);
5046
5047 png_read_row(pp, row, display);
5048
5049 if (iImage >= 0)
5050 deinterlace_row(store_image_row(ps, pp, iImage, y), row,
Matt Sarett9ea75692016-01-08 13:00:42 -05005051 dp->pixel_size, dp->w, pass, dp->littleendian);
Chris Craikb50c2172013-07-29 15:28:30 -07005052
5053 if (iDisplay >= 0)
5054 deinterlace_row(store_image_row(ps, pp, iDisplay, y), display,
Matt Sarett9ea75692016-01-08 13:00:42 -05005055 dp->pixel_size, dp->w, pass, dp->littleendian);
Chris Craikb50c2172013-07-29 15:28:30 -07005056 }
5057 }
5058 else
5059 png_read_row(pp,
5060 iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL,
5061 iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL);
5062 }
5063 }
5064
5065 /* And finish the read operation (only really necessary if the caller wants
5066 * to find additional data in png_info from chunks after the last IDAT.)
5067 */
5068 png_read_end(pp, pi);
5069}
5070
5071#ifdef PNG_TEXT_SUPPORTED
5072static void
5073standard_check_text(png_const_structp pp, png_const_textp tp,
5074 png_const_charp keyword, png_const_charp text)
5075{
5076 char msg[1024];
5077 size_t pos = safecat(msg, sizeof msg, 0, "text: ");
5078 size_t ok;
5079
5080 pos = safecat(msg, sizeof msg, pos, keyword);
5081 pos = safecat(msg, sizeof msg, pos, ": ");
5082 ok = pos;
5083
5084 if (tp->compression != TEXT_COMPRESSION)
5085 {
5086 char buf[64];
5087
5088 sprintf(buf, "compression [%d->%d], ", TEXT_COMPRESSION,
5089 tp->compression);
5090 pos = safecat(msg, sizeof msg, pos, buf);
5091 }
5092
5093 if (tp->key == NULL || strcmp(tp->key, keyword) != 0)
5094 {
5095 pos = safecat(msg, sizeof msg, pos, "keyword \"");
5096 if (tp->key != NULL)
5097 {
5098 pos = safecat(msg, sizeof msg, pos, tp->key);
5099 pos = safecat(msg, sizeof msg, pos, "\", ");
5100 }
5101
5102 else
5103 pos = safecat(msg, sizeof msg, pos, "null, ");
5104 }
5105
5106 if (tp->text == NULL)
5107 pos = safecat(msg, sizeof msg, pos, "text lost, ");
5108
5109 else
5110 {
5111 if (tp->text_length != strlen(text))
5112 {
5113 char buf[64];
5114 sprintf(buf, "text length changed[%lu->%lu], ",
5115 (unsigned long)strlen(text), (unsigned long)tp->text_length);
5116 pos = safecat(msg, sizeof msg, pos, buf);
5117 }
5118
5119 if (strcmp(tp->text, text) != 0)
5120 {
5121 pos = safecat(msg, sizeof msg, pos, "text becomes \"");
5122 pos = safecat(msg, sizeof msg, pos, tp->text);
5123 pos = safecat(msg, sizeof msg, pos, "\" (was \"");
5124 pos = safecat(msg, sizeof msg, pos, text);
5125 pos = safecat(msg, sizeof msg, pos, "\"), ");
5126 }
5127 }
5128
5129 if (tp->itxt_length != 0)
5130 pos = safecat(msg, sizeof msg, pos, "iTXt length set, ");
5131
5132 if (tp->lang != NULL)
5133 {
5134 pos = safecat(msg, sizeof msg, pos, "iTXt language \"");
5135 pos = safecat(msg, sizeof msg, pos, tp->lang);
5136 pos = safecat(msg, sizeof msg, pos, "\", ");
5137 }
5138
5139 if (tp->lang_key != NULL)
5140 {
5141 pos = safecat(msg, sizeof msg, pos, "iTXt keyword \"");
5142 pos = safecat(msg, sizeof msg, pos, tp->lang_key);
5143 pos = safecat(msg, sizeof msg, pos, "\", ");
5144 }
5145
5146 if (pos > ok)
5147 {
5148 msg[pos-2] = '\0'; /* Remove the ", " at the end */
5149 png_error(pp, msg);
5150 }
5151}
5152
5153static void
5154standard_text_validate(standard_display *dp, png_const_structp pp,
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305155 png_infop pi, int check_end)
Chris Craikb50c2172013-07-29 15:28:30 -07005156{
5157 png_textp tp = NULL;
5158 png_uint_32 num_text = png_get_text(pp, pi, &tp, NULL);
5159
5160 if (num_text == 2 && tp != NULL)
5161 {
5162 standard_check_text(pp, tp, "image name", dp->ps->current->name);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305163
5164 /* This exists because prior to 1.5.18 the progressive reader left the
5165 * png_struct z_stream unreset at the end of the image, so subsequent
5166 * attempts to use it simply returns Z_STREAM_END.
5167 */
5168 if (check_end)
5169 standard_check_text(pp, tp+1, "end marker", "end");
Chris Craikb50c2172013-07-29 15:28:30 -07005170 }
5171
5172 else
5173 {
5174 char msg[64];
5175
5176 sprintf(msg, "expected two text items, got %lu",
5177 (unsigned long)num_text);
5178 png_error(pp, msg);
5179 }
5180}
5181#else
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305182# define standard_text_validate(dp,pp,pi,check_end) ((void)0)
Chris Craikb50c2172013-07-29 15:28:30 -07005183#endif
5184
5185static void
5186standard_row_validate(standard_display *dp, png_const_structp pp,
5187 int iImage, int iDisplay, png_uint_32 y)
5188{
5189 int where;
5190 png_byte std[STANDARD_ROWMAX];
5191
5192 /* The row must be pre-initialized to the magic number here for the size
5193 * tests to pass:
5194 */
5195 memset(std, 178, sizeof std);
5196 standard_row(pp, std, dp->id, y);
5197
5198 /* At the end both the 'row' and 'display' arrays should end up identical.
5199 * In earlier passes 'row' will be partially filled in, with only the pixels
5200 * that have been read so far, but 'display' will have those pixels
5201 * replicated to fill the unread pixels while reading an interlaced image.
Chris Craikb50c2172013-07-29 15:28:30 -07005202 */
5203 if (iImage >= 0 &&
5204 (where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y),
5205 dp->bit_width)) != 0)
5206 {
5207 char msg[64];
5208 sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x",
5209 (unsigned long)y, where-1, std[where-1],
5210 store_image_row(dp->ps, pp, iImage, y)[where-1]);
5211 png_error(pp, msg);
5212 }
5213
Chris Craikb50c2172013-07-29 15:28:30 -07005214 if (iDisplay >= 0 &&
5215 (where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y),
5216 dp->bit_width)) != 0)
5217 {
5218 char msg[64];
Matt Sarett9ea75692016-01-08 13:00:42 -05005219 sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x",
Chris Craikb50c2172013-07-29 15:28:30 -07005220 (unsigned long)y, where-1, std[where-1],
5221 store_image_row(dp->ps, pp, iDisplay, y)[where-1]);
5222 png_error(pp, msg);
5223 }
5224}
5225
5226static void
5227standard_image_validate(standard_display *dp, png_const_structp pp, int iImage,
5228 int iDisplay)
5229{
5230 png_uint_32 y;
5231
5232 if (iImage >= 0)
5233 store_image_check(dp->ps, pp, iImage);
5234
5235 if (iDisplay >= 0)
5236 store_image_check(dp->ps, pp, iDisplay);
5237
5238 for (y=0; y<dp->h; ++y)
5239 standard_row_validate(dp, pp, iImage, iDisplay, y);
5240
5241 /* This avoids false positives if the validation code is never called! */
5242 dp->ps->validated = 1;
5243}
5244
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305245static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07005246standard_end(png_structp ppIn, png_infop pi)
5247{
5248 png_const_structp pp = ppIn;
5249 standard_display *dp = voidcast(standard_display*,
5250 png_get_progressive_ptr(pp));
5251
5252 UNUSED(pi)
5253
5254 /* Validate the image - progressive reading only produces one variant for
5255 * interlaced images.
5256 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305257 standard_text_validate(dp, pp, pi,
5258 PNG_LIBPNG_VER >= 10518/*check_end: see comments above*/);
Chris Craikb50c2172013-07-29 15:28:30 -07005259 standard_image_validate(dp, pp, 0, -1);
5260}
5261
5262/* A single test run checking the standard image to ensure it is not damaged. */
5263static void
Matt Sarett9ea75692016-01-08 13:00:42 -05005264standard_test(png_store* const psIn, png_uint_32 const id,
Chris Craikb50c2172013-07-29 15:28:30 -07005265 int do_interlace, int use_update_info)
5266{
5267 standard_display d;
5268 context(psIn, fault);
5269
5270 /* Set up the display (stack frame) variables from the arguments to the
5271 * function and initialize the locals that are filled in later.
5272 */
5273 standard_display_init(&d, psIn, id, do_interlace, use_update_info);
5274
5275 /* Everything is protected by a Try/Catch. The functions called also
5276 * typically have local Try/Catch blocks.
5277 */
5278 Try
5279 {
5280 png_structp pp;
5281 png_infop pi;
5282
5283 /* Get a png_struct for reading the image. This will throw an error if it
5284 * fails, so we don't need to check the result.
5285 */
5286 pp = set_store_for_read(d.ps, &pi, d.id,
5287 d.do_interlace ? (d.ps->progressive ?
5288 "pngvalid progressive deinterlacer" :
5289 "pngvalid sequential deinterlacer") : (d.ps->progressive ?
5290 "progressive reader" : "sequential reader"));
5291
5292 /* Initialize the palette correctly from the png_store_file. */
5293 standard_palette_init(&d);
5294
5295 /* Introduce the correct read function. */
5296 if (d.ps->progressive)
5297 {
5298 png_set_progressive_read_fn(pp, &d, standard_info, progressive_row,
5299 standard_end);
5300
5301 /* Now feed data into the reader until we reach the end: */
5302 store_progressive_read(d.ps, pp, pi);
5303 }
5304 else
5305 {
5306 /* Note that this takes the store, not the display. */
5307 png_set_read_fn(pp, d.ps, store_read);
5308
5309 /* Check the header values: */
5310 png_read_info(pp, pi);
5311
5312 /* The code tests both versions of the images that the sequential
5313 * reader can produce.
5314 */
5315 standard_info_imp(&d, pp, pi, 2 /*images*/);
5316
5317 /* Need the total bytes in the image below; we can't get to this point
5318 * unless the PNG file values have been checked against the expected
5319 * values.
5320 */
5321 {
5322 sequential_row(&d, pp, pi, 0, 1);
5323
5324 /* After the last pass loop over the rows again to check that the
5325 * image is correct.
5326 */
5327 if (!d.speed)
5328 {
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305329 standard_text_validate(&d, pp, pi, 1/*check_end*/);
Chris Craikb50c2172013-07-29 15:28:30 -07005330 standard_image_validate(&d, pp, 0, 1);
5331 }
5332 else
5333 d.ps->validated = 1;
5334 }
5335 }
5336
5337 /* Check for validation. */
5338 if (!d.ps->validated)
5339 png_error(pp, "image read failed silently");
5340
5341 /* Successful completion. */
5342 }
5343
5344 Catch(fault)
5345 d.ps = fault; /* make sure this hasn't been clobbered. */
5346
5347 /* In either case clean up the store. */
5348 store_read_reset(d.ps);
5349}
5350
5351static int
Matt Sarett9ea75692016-01-08 13:00:42 -05005352test_standard(png_modifier* const pm, png_byte const colour_type,
5353 int bdlo, int const bdhi)
Chris Craikb50c2172013-07-29 15:28:30 -07005354{
5355 for (; bdlo <= bdhi; ++bdlo)
5356 {
5357 int interlace_type;
5358
5359 for (interlace_type = PNG_INTERLACE_NONE;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305360 interlace_type < INTERLACE_LAST; ++interlace_type)
Chris Craikb50c2172013-07-29 15:28:30 -07005361 {
5362 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
Matt Sarett9ea75692016-01-08 13:00:42 -05005363 interlace_type, 0, 0, 0), do_read_interlace, pm->use_update_info);
Chris Craikb50c2172013-07-29 15:28:30 -07005364
5365 if (fail(pm))
5366 return 0;
5367 }
5368 }
5369
5370 return 1; /* keep going */
5371}
5372
5373static void
5374perform_standard_test(png_modifier *pm)
5375{
5376 /* Test each colour type over the valid range of bit depths (expressed as
5377 * log2(bit_depth) in turn, stop as soon as any error is detected.
5378 */
5379 if (!test_standard(pm, 0, 0, READ_BDHI))
5380 return;
5381
5382 if (!test_standard(pm, 2, 3, READ_BDHI))
5383 return;
5384
5385 if (!test_standard(pm, 3, 0, 3))
5386 return;
5387
5388 if (!test_standard(pm, 4, 3, READ_BDHI))
5389 return;
5390
5391 if (!test_standard(pm, 6, 3, READ_BDHI))
5392 return;
5393}
5394
5395
5396/********************************** SIZE TESTS ********************************/
5397static int
Matt Sarett9ea75692016-01-08 13:00:42 -05005398test_size(png_modifier* const pm, png_byte const colour_type,
5399 int bdlo, int const bdhi)
Chris Craikb50c2172013-07-29 15:28:30 -07005400{
5401 /* Run the tests on each combination.
5402 *
5403 * NOTE: on my 32 bit x86 each of the following blocks takes
5404 * a total of 3.5 seconds if done across every combo of bit depth
5405 * width and height. This is a waste of time in practice, hence the
5406 * hinc and winc stuff:
5407 */
Matt Sarett9ea75692016-01-08 13:00:42 -05005408 static const png_byte hinc[] = {1, 3, 11, 1, 5};
5409 static const png_byte winc[] = {1, 9, 5, 7, 1};
5410 const int save_bdlo = bdlo;
5411
Chris Craikb50c2172013-07-29 15:28:30 -07005412 for (; bdlo <= bdhi; ++bdlo)
5413 {
5414 png_uint_32 h, w;
5415
5416 for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo])
5417 {
5418 /* First test all the 'size' images against the sequential
5419 * reader using libpng to deinterlace (where required.) This
5420 * validates the write side of libpng. There are four possibilities
5421 * to validate.
5422 */
5423 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5424 PNG_INTERLACE_NONE, w, h, 0), 0/*do_interlace*/,
5425 pm->use_update_info);
5426
5427 if (fail(pm))
5428 return 0;
5429
5430 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5431 PNG_INTERLACE_NONE, w, h, 1), 0/*do_interlace*/,
5432 pm->use_update_info);
5433
5434 if (fail(pm))
5435 return 0;
5436
Chris Craikb50c2172013-07-29 15:28:30 -07005437 /* Now validate the interlaced read side - do_interlace true,
5438 * in the progressive case this does actually make a difference
5439 * to the code used in the non-interlaced case too.
5440 */
5441 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5442 PNG_INTERLACE_NONE, w, h, 0), 1/*do_interlace*/,
5443 pm->use_update_info);
5444
5445 if (fail(pm))
5446 return 0;
5447
Matt Sarett9ea75692016-01-08 13:00:42 -05005448# if CAN_WRITE_INTERLACE
5449 /* Validate the pngvalid code itself: */
5450 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5451 PNG_INTERLACE_ADAM7, w, h, 1), 1/*do_interlace*/,
5452 pm->use_update_info);
5453
5454 if (fail(pm))
5455 return 0;
5456# endif
5457 }
5458 }
5459
5460 /* Now do the tests of libpng interlace handling, after we have made sure
5461 * that the pngvalid version works:
5462 */
5463 for (bdlo = save_bdlo; bdlo <= bdhi; ++bdlo)
5464 {
5465 png_uint_32 h, w;
5466
5467 for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo])
5468 {
5469# ifdef PNG_READ_INTERLACING_SUPPORTED
5470 /* Test with pngvalid generated interlaced images first; we have
5471 * already verify these are ok (unless pngvalid has self-consistent
5472 * read/write errors, which is unlikely), so this detects errors in the
5473 * read side first:
5474 */
5475# if CAN_WRITE_INTERLACE
5476 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5477 PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/,
5478 pm->use_update_info);
5479
5480 if (fail(pm))
5481 return 0;
5482# endif
5483# endif /* READ_INTERLACING */
5484
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305485# ifdef PNG_WRITE_INTERLACING_SUPPORTED
Matt Sarett9ea75692016-01-08 13:00:42 -05005486 /* Test the libpng write side against the pngvalid read side: */
Chris Craikb50c2172013-07-29 15:28:30 -07005487 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5488 PNG_INTERLACE_ADAM7, w, h, 0), 1/*do_interlace*/,
5489 pm->use_update_info);
5490
5491 if (fail(pm))
5492 return 0;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305493# endif
Matt Sarett9ea75692016-01-08 13:00:42 -05005494
5495# ifdef PNG_READ_INTERLACING_SUPPORTED
5496# ifdef PNG_WRITE_INTERLACING_SUPPORTED
5497 /* Test both together: */
5498 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5499 PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/,
5500 pm->use_update_info);
5501
5502 if (fail(pm))
5503 return 0;
5504# endif
5505# endif /* READ_INTERLACING */
Chris Craikb50c2172013-07-29 15:28:30 -07005506 }
5507 }
5508
5509 return 1; /* keep going */
5510}
5511
5512static void
5513perform_size_test(png_modifier *pm)
5514{
5515 /* Test each colour type over the valid range of bit depths (expressed as
5516 * log2(bit_depth) in turn, stop as soon as any error is detected.
5517 */
5518 if (!test_size(pm, 0, 0, READ_BDHI))
5519 return;
5520
5521 if (!test_size(pm, 2, 3, READ_BDHI))
5522 return;
5523
5524 /* For the moment don't do the palette test - it's a waste of time when
5525 * compared to the grayscale test.
5526 */
5527#if 0
5528 if (!test_size(pm, 3, 0, 3))
5529 return;
5530#endif
5531
5532 if (!test_size(pm, 4, 3, READ_BDHI))
5533 return;
5534
5535 if (!test_size(pm, 6, 3, READ_BDHI))
5536 return;
5537}
5538
5539
5540/******************************* TRANSFORM TESTS ******************************/
5541#ifdef PNG_READ_TRANSFORMS_SUPPORTED
5542/* A set of tests to validate libpng image transforms. The possibilities here
5543 * are legion because the transforms can be combined in a combinatorial
5544 * fashion. To deal with this some measure of restraint is required, otherwise
5545 * the tests would take forever.
5546 */
5547typedef struct image_pixel
5548{
5549 /* A local (pngvalid) representation of a PNG pixel, in all its
5550 * various forms.
5551 */
5552 unsigned int red, green, blue, alpha; /* For non-palette images. */
5553 unsigned int palette_index; /* For a palette image. */
Matt Sarett9ea75692016-01-08 13:00:42 -05005554 png_byte colour_type; /* As in the spec. */
5555 png_byte bit_depth; /* Defines bit size in row */
5556 png_byte sample_depth; /* Scale of samples */
5557 unsigned int have_tRNS :1; /* tRNS chunk may need processing */
5558 unsigned int swap_rgb :1; /* RGB swapped to BGR */
5559 unsigned int alpha_first :1; /* Alpha at start, not end */
5560 unsigned int alpha_inverted :1; /* Alpha channel inverted */
5561 unsigned int mono_inverted :1; /* Gray channel inverted */
5562 unsigned int swap16 :1; /* Byte swap 16-bit components */
5563 unsigned int littleendian :1; /* High bits on right */
5564 unsigned int sig_bits :1; /* Pixel shifted (sig bits only) */
Chris Craikb50c2172013-07-29 15:28:30 -07005565
5566 /* For checking the code calculates double precision floating point values
5567 * along with an error value, accumulated from the transforms. Because an
5568 * sBIT setting allows larger error bounds (indeed, by the spec, apparently
5569 * up to just less than +/-1 in the scaled value) the *lowest* sBIT for each
5570 * channel is stored. This sBIT value is folded in to the stored error value
5571 * at the end of the application of the transforms to the pixel.
Matt Sarett9ea75692016-01-08 13:00:42 -05005572 *
5573 * If sig_bits is set above the red, green, blue and alpha values have been
5574 * scaled so they only contain the significant bits of the component values.
Chris Craikb50c2172013-07-29 15:28:30 -07005575 */
5576 double redf, greenf, bluef, alphaf;
5577 double rede, greene, bluee, alphae;
5578 png_byte red_sBIT, green_sBIT, blue_sBIT, alpha_sBIT;
5579} image_pixel;
5580
5581/* Shared utility function, see below. */
5582static void
Matt Sarett9ea75692016-01-08 13:00:42 -05005583image_pixel_setf(image_pixel *this, unsigned int rMax, unsigned int gMax,
5584 unsigned int bMax, unsigned int aMax)
Chris Craikb50c2172013-07-29 15:28:30 -07005585{
Matt Sarett9ea75692016-01-08 13:00:42 -05005586 this->redf = this->red / (double)rMax;
5587 this->greenf = this->green / (double)gMax;
5588 this->bluef = this->blue / (double)bMax;
5589 this->alphaf = this->alpha / (double)aMax;
Chris Craikb50c2172013-07-29 15:28:30 -07005590
Matt Sarett9ea75692016-01-08 13:00:42 -05005591 if (this->red < rMax)
Chris Craikb50c2172013-07-29 15:28:30 -07005592 this->rede = this->redf * DBL_EPSILON;
5593 else
5594 this->rede = 0;
Matt Sarett9ea75692016-01-08 13:00:42 -05005595 if (this->green < gMax)
Chris Craikb50c2172013-07-29 15:28:30 -07005596 this->greene = this->greenf * DBL_EPSILON;
5597 else
5598 this->greene = 0;
Matt Sarett9ea75692016-01-08 13:00:42 -05005599 if (this->blue < bMax)
Chris Craikb50c2172013-07-29 15:28:30 -07005600 this->bluee = this->bluef * DBL_EPSILON;
5601 else
5602 this->bluee = 0;
Matt Sarett9ea75692016-01-08 13:00:42 -05005603 if (this->alpha < aMax)
Chris Craikb50c2172013-07-29 15:28:30 -07005604 this->alphae = this->alphaf * DBL_EPSILON;
5605 else
5606 this->alphae = 0;
5607}
5608
5609/* Initialize the structure for the next pixel - call this before doing any
5610 * transforms and call it for each pixel since all the fields may need to be
5611 * reset.
5612 */
5613static void
5614image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type,
Matt Sarett9ea75692016-01-08 13:00:42 -05005615 png_byte bit_depth, png_uint_32 x, store_palette palette,
5616 const image_pixel *format /*from pngvalid transform of input*/)
Chris Craikb50c2172013-07-29 15:28:30 -07005617{
Matt Sarett9ea75692016-01-08 13:00:42 -05005618 const png_byte sample_depth = (png_byte)(colour_type ==
Chris Craikb50c2172013-07-29 15:28:30 -07005619 PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth);
Matt Sarett9ea75692016-01-08 13:00:42 -05005620 const unsigned int max = (1U<<sample_depth)-1;
5621 const int swap16 = (format != 0 && format->swap16);
5622 const int littleendian = (format != 0 && format->littleendian);
5623 const int sig_bits = (format != 0 && format->sig_bits);
Chris Craikb50c2172013-07-29 15:28:30 -07005624
5625 /* Initially just set everything to the same number and the alpha to opaque.
5626 * Note that this currently assumes a simple palette where entry x has colour
5627 * rgb(x,x,x)!
5628 */
5629 this->palette_index = this->red = this->green = this->blue =
Matt Sarett9ea75692016-01-08 13:00:42 -05005630 sample(row, colour_type, bit_depth, x, 0, swap16, littleendian);
Chris Craikb50c2172013-07-29 15:28:30 -07005631 this->alpha = max;
5632 this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT =
5633 sample_depth;
5634
5635 /* Then override as appropriate: */
5636 if (colour_type == 3) /* palette */
5637 {
5638 /* This permits the caller to default to the sample value. */
5639 if (palette != 0)
5640 {
Matt Sarett9ea75692016-01-08 13:00:42 -05005641 const unsigned int i = this->palette_index;
Chris Craikb50c2172013-07-29 15:28:30 -07005642
5643 this->red = palette[i].red;
5644 this->green = palette[i].green;
5645 this->blue = palette[i].blue;
5646 this->alpha = palette[i].alpha;
5647 }
5648 }
5649
5650 else /* not palette */
5651 {
5652 unsigned int i = 0;
5653
Matt Sarett9ea75692016-01-08 13:00:42 -05005654 if ((colour_type & 4) != 0 && format != 0 && format->alpha_first)
5655 {
5656 this->alpha = this->red;
5657 /* This handles the gray case for 'AG' pixels */
5658 this->palette_index = this->red = this->green = this->blue =
5659 sample(row, colour_type, bit_depth, x, 1, swap16, littleendian);
5660 i = 1;
5661 }
5662
Chris Craikb50c2172013-07-29 15:28:30 -07005663 if (colour_type & 2)
5664 {
Matt Sarett9ea75692016-01-08 13:00:42 -05005665 /* Green is second for both BGR and RGB: */
5666 this->green = sample(row, colour_type, bit_depth, x, ++i, swap16,
5667 littleendian);
5668
5669 if (format != 0 && format->swap_rgb) /* BGR */
5670 this->red = sample(row, colour_type, bit_depth, x, ++i, swap16,
5671 littleendian);
5672 else
5673 this->blue = sample(row, colour_type, bit_depth, x, ++i, swap16,
5674 littleendian);
Chris Craikb50c2172013-07-29 15:28:30 -07005675 }
Matt Sarett9ea75692016-01-08 13:00:42 -05005676
5677 else /* grayscale */ if (format != 0 && format->mono_inverted)
5678 this->red = this->green = this->blue = this->red ^ max;
5679
5680 if ((colour_type & 4) != 0) /* alpha */
5681 {
5682 if (format == 0 || !format->alpha_first)
5683 this->alpha = sample(row, colour_type, bit_depth, x, ++i, swap16,
5684 littleendian);
5685
5686 if (format != 0 && format->alpha_inverted)
5687 this->alpha ^= max;
5688 }
Chris Craikb50c2172013-07-29 15:28:30 -07005689 }
5690
5691 /* Calculate the scaled values, these are simply the values divided by
5692 * 'max' and the error is initialized to the double precision epsilon value
5693 * from the header file.
5694 */
Matt Sarett9ea75692016-01-08 13:00:42 -05005695 image_pixel_setf(this,
5696 sig_bits ? (1U << format->red_sBIT)-1 : max,
5697 sig_bits ? (1U << format->green_sBIT)-1 : max,
5698 sig_bits ? (1U << format->blue_sBIT)-1 : max,
5699 sig_bits ? (1U << format->alpha_sBIT)-1 : max);
Chris Craikb50c2172013-07-29 15:28:30 -07005700
5701 /* Store the input information for use in the transforms - these will
5702 * modify the information.
5703 */
5704 this->colour_type = colour_type;
5705 this->bit_depth = bit_depth;
5706 this->sample_depth = sample_depth;
5707 this->have_tRNS = 0;
Matt Sarett9ea75692016-01-08 13:00:42 -05005708 this->swap_rgb = 0;
5709 this->alpha_first = 0;
5710 this->alpha_inverted = 0;
5711 this->mono_inverted = 0;
5712 this->swap16 = 0;
5713 this->littleendian = 0;
5714 this->sig_bits = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07005715}
5716
Matt Sarett9ea75692016-01-08 13:00:42 -05005717#if defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_GRAY_TO_RGB_SUPPORTED\
5718 || defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_EXPAND_16_SUPPORTED\
5719 || defined PNG_READ_BACKGROUND_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07005720/* Convert a palette image to an rgb image. This necessarily converts the tRNS
5721 * chunk at the same time, because the tRNS will be in palette form. The way
5722 * palette validation works means that the original palette is never updated,
5723 * instead the image_pixel value from the row contains the RGB of the
5724 * corresponding palette entry and *this* is updated. Consequently this routine
5725 * only needs to change the colour type information.
5726 */
5727static void
5728image_pixel_convert_PLTE(image_pixel *this)
5729{
5730 if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
5731 {
5732 if (this->have_tRNS)
5733 {
5734 this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
5735 this->have_tRNS = 0;
5736 }
5737 else
5738 this->colour_type = PNG_COLOR_TYPE_RGB;
5739
5740 /* The bit depth of the row changes at this point too (notice that this is
5741 * the row format, not the sample depth, which is separate.)
5742 */
5743 this->bit_depth = 8;
5744 }
5745}
5746
5747/* Add an alpha channel; this will import the tRNS information because tRNS is
5748 * not valid in an alpha image. The bit depth will invariably be set to at
Matt Sarett9ea75692016-01-08 13:00:42 -05005749 * least 8 prior to 1.7.0. Palette images will be converted to alpha (using
5750 * the above API). With png_set_background the alpha channel is never expanded
5751 * but this routine is used by pngvalid to simplify code; 'for_background'
5752 * records this.
Chris Craikb50c2172013-07-29 15:28:30 -07005753 */
5754static void
Matt Sarett9ea75692016-01-08 13:00:42 -05005755image_pixel_add_alpha(image_pixel *this, const standard_display *display,
5756 int for_background)
Chris Craikb50c2172013-07-29 15:28:30 -07005757{
5758 if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
5759 image_pixel_convert_PLTE(this);
5760
5761 if ((this->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
5762 {
5763 if (this->colour_type == PNG_COLOR_TYPE_GRAY)
5764 {
Matt Sarett9ea75692016-01-08 13:00:42 -05005765# if PNG_LIBPNG_VER < 10700
5766 if (!for_background && this->bit_depth < 8)
5767 this->bit_depth = this->sample_depth = 8;
5768# endif
Chris Craikb50c2172013-07-29 15:28:30 -07005769
5770 if (this->have_tRNS)
5771 {
Matt Sarett9ea75692016-01-08 13:00:42 -05005772 /* After 1.7 the expansion of bit depth only happens if there is a
5773 * tRNS chunk to expand at this point.
5774 */
5775# if PNG_LIBPNG_VER >= 10700
5776 if (!for_background && this->bit_depth < 8)
5777 this->bit_depth = this->sample_depth = 8;
5778# endif
5779
Chris Craikb50c2172013-07-29 15:28:30 -07005780 this->have_tRNS = 0;
5781
5782 /* Check the input, original, channel value here against the
5783 * original tRNS gray chunk valie.
5784 */
5785 if (this->red == display->transparent.red)
5786 this->alphaf = 0;
5787 else
5788 this->alphaf = 1;
5789 }
5790 else
5791 this->alphaf = 1;
5792
5793 this->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
5794 }
5795
5796 else if (this->colour_type == PNG_COLOR_TYPE_RGB)
5797 {
5798 if (this->have_tRNS)
5799 {
5800 this->have_tRNS = 0;
5801
5802 /* Again, check the exact input values, not the current transformed
5803 * value!
5804 */
5805 if (this->red == display->transparent.red &&
5806 this->green == display->transparent.green &&
5807 this->blue == display->transparent.blue)
5808 this->alphaf = 0;
5809 else
5810 this->alphaf = 1;
Chris Craikb50c2172013-07-29 15:28:30 -07005811 }
Matt Sarett9ea75692016-01-08 13:00:42 -05005812 else
5813 this->alphaf = 1;
5814
5815 this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
Chris Craikb50c2172013-07-29 15:28:30 -07005816 }
5817
5818 /* The error in the alpha is zero and the sBIT value comes from the
5819 * original sBIT data (actually it will always be the original bit depth).
5820 */
5821 this->alphae = 0;
5822 this->alpha_sBIT = display->alpha_sBIT;
5823 }
5824}
Matt Sarett9ea75692016-01-08 13:00:42 -05005825#endif /* transforms that need image_pixel_add_alpha */
Chris Craikb50c2172013-07-29 15:28:30 -07005826
5827struct transform_display;
5828typedef struct image_transform
5829{
5830 /* The name of this transform: a string. */
Matt Sarett9ea75692016-01-08 13:00:42 -05005831 const char *name;
Chris Craikb50c2172013-07-29 15:28:30 -07005832
5833 /* Each transform can be disabled from the command line: */
5834 int enable;
5835
5836 /* The global list of transforms; read only. */
Matt Sarett9ea75692016-01-08 13:00:42 -05005837 struct image_transform *const list;
Chris Craikb50c2172013-07-29 15:28:30 -07005838
5839 /* The global count of the number of times this transform has been set on an
5840 * image.
5841 */
5842 unsigned int global_use;
5843
5844 /* The local count of the number of times this transform has been set. */
5845 unsigned int local_use;
5846
5847 /* The next transform in the list, each transform must call its own next
5848 * transform after it has processed the pixel successfully.
5849 */
Matt Sarett9ea75692016-01-08 13:00:42 -05005850 const struct image_transform *next;
Chris Craikb50c2172013-07-29 15:28:30 -07005851
5852 /* A single transform for the image, expressed as a series of function
5853 * callbacks and some space for values.
5854 *
5855 * First a callback to add any required modifications to the png_modifier;
5856 * this gets called just before the modifier is set up for read.
5857 */
Matt Sarett9ea75692016-01-08 13:00:42 -05005858 void (*ini)(const struct image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07005859 struct transform_display *that);
5860
5861 /* And a callback to set the transform on the current png_read_struct:
5862 */
Matt Sarett9ea75692016-01-08 13:00:42 -05005863 void (*set)(const struct image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07005864 struct transform_display *that, png_structp pp, png_infop pi);
5865
5866 /* Then a transform that takes an input pixel in one PNG format or another
5867 * and modifies it by a pngvalid implementation of the transform (thus
5868 * duplicating the libpng intent without, we hope, duplicating the bugs
5869 * in the libpng implementation!) The png_structp is solely to allow error
5870 * reporting via png_error and png_warning.
5871 */
Matt Sarett9ea75692016-01-08 13:00:42 -05005872 void (*mod)(const struct image_transform *this, image_pixel *that,
5873 png_const_structp pp, const struct transform_display *display);
Chris Craikb50c2172013-07-29 15:28:30 -07005874
5875 /* Add this transform to the list and return true if the transform is
5876 * meaningful for this colour type and bit depth - if false then the
5877 * transform should have no effect on the image so there's not a lot of
5878 * point running it.
5879 */
5880 int (*add)(struct image_transform *this,
Matt Sarett9ea75692016-01-08 13:00:42 -05005881 const struct image_transform **that, png_byte colour_type,
Chris Craikb50c2172013-07-29 15:28:30 -07005882 png_byte bit_depth);
5883} image_transform;
5884
5885typedef struct transform_display
5886{
5887 standard_display this;
5888
5889 /* Parameters */
5890 png_modifier* pm;
Matt Sarett9ea75692016-01-08 13:00:42 -05005891 const image_transform* transform_list;
5892 unsigned int max_gamma_8;
Chris Craikb50c2172013-07-29 15:28:30 -07005893
5894 /* Local variables */
5895 png_byte output_colour_type;
5896 png_byte output_bit_depth;
Matt Sarett9ea75692016-01-08 13:00:42 -05005897 png_byte unpacked;
Chris Craikb50c2172013-07-29 15:28:30 -07005898
5899 /* Modifications (not necessarily used.) */
5900 gama_modification gama_mod;
5901 chrm_modification chrm_mod;
5902 srgb_modification srgb_mod;
5903} transform_display;
5904
5905/* Set sRGB, cHRM and gAMA transforms as required by the current encoding. */
5906static void
5907transform_set_encoding(transform_display *this)
5908{
5909 /* Set up the png_modifier '_current' fields then use these to determine how
5910 * to add appropriate chunks.
5911 */
5912 png_modifier *pm = this->pm;
5913
5914 modifier_set_encoding(pm);
5915
5916 if (modifier_color_encoding_is_set(pm))
5917 {
5918 if (modifier_color_encoding_is_sRGB(pm))
5919 srgb_modification_init(&this->srgb_mod, pm, PNG_sRGB_INTENT_ABSOLUTE);
5920
5921 else
5922 {
5923 /* Set gAMA and cHRM separately. */
5924 gama_modification_init(&this->gama_mod, pm, pm->current_gamma);
5925
5926 if (pm->current_encoding != 0)
5927 chrm_modification_init(&this->chrm_mod, pm, pm->current_encoding);
5928 }
5929 }
5930}
5931
5932/* Three functions to end the list: */
5933static void
Matt Sarett9ea75692016-01-08 13:00:42 -05005934image_transform_ini_end(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07005935 transform_display *that)
5936{
5937 UNUSED(this)
5938 UNUSED(that)
5939}
5940
5941static void
Matt Sarett9ea75692016-01-08 13:00:42 -05005942image_transform_set_end(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07005943 transform_display *that, png_structp pp, png_infop pi)
5944{
5945 UNUSED(this)
5946 UNUSED(that)
5947 UNUSED(pp)
5948 UNUSED(pi)
5949}
5950
5951/* At the end of the list recalculate the output image pixel value from the
5952 * double precision values set up by the preceding 'mod' calls:
5953 */
5954static unsigned int
5955sample_scale(double sample_value, unsigned int scale)
5956{
5957 sample_value = floor(sample_value * scale + .5);
5958
5959 /* Return NaN as 0: */
5960 if (!(sample_value > 0))
5961 sample_value = 0;
5962 else if (sample_value > scale)
5963 sample_value = scale;
5964
5965 return (unsigned int)sample_value;
5966}
5967
5968static void
Matt Sarett9ea75692016-01-08 13:00:42 -05005969image_transform_mod_end(const image_transform *this, image_pixel *that,
5970 png_const_structp pp, const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07005971{
Matt Sarett9ea75692016-01-08 13:00:42 -05005972 const unsigned int scale = (1U<<that->sample_depth)-1;
5973 const int sig_bits = that->sig_bits;
Chris Craikb50c2172013-07-29 15:28:30 -07005974
5975 UNUSED(this)
5976 UNUSED(pp)
5977 UNUSED(display)
5978
5979 /* At the end recalculate the digitized red green and blue values according
5980 * to the current sample_depth of the pixel.
5981 *
5982 * The sample value is simply scaled to the maximum, checking for over
5983 * and underflow (which can both happen for some image transforms,
5984 * including simple size scaling, though libpng doesn't do that at present.
5985 */
5986 that->red = sample_scale(that->redf, scale);
5987
Matt Sarett9ea75692016-01-08 13:00:42 -05005988 /* This is a bit bogus; really the above calculation should use the red_sBIT
5989 * value, not sample_depth, but because libpng does png_set_shift by just
5990 * shifting the bits we get errors if we don't do it the same way.
5991 */
5992 if (sig_bits && that->red_sBIT < that->sample_depth)
5993 that->red >>= that->sample_depth - that->red_sBIT;
5994
Chris Craikb50c2172013-07-29 15:28:30 -07005995 /* The error value is increased, at the end, according to the lowest sBIT
5996 * value seen. Common sense tells us that the intermediate integer
5997 * representations are no more accurate than +/- 0.5 in the integral values,
5998 * the sBIT allows the implementation to be worse than this. In addition the
5999 * PNG specification actually permits any error within the range (-1..+1),
6000 * but that is ignored here. Instead the final digitized value is compared,
6001 * below to the digitized value of the error limits - this has the net effect
6002 * of allowing (almost) +/-1 in the output value. It's difficult to see how
6003 * any algorithm that digitizes intermediate results can be more accurate.
6004 */
6005 that->rede += 1./(2*((1U<<that->red_sBIT)-1));
6006
6007 if (that->colour_type & PNG_COLOR_MASK_COLOR)
6008 {
6009 that->green = sample_scale(that->greenf, scale);
Matt Sarett9ea75692016-01-08 13:00:42 -05006010 if (sig_bits && that->green_sBIT < that->sample_depth)
6011 that->green >>= that->sample_depth - that->green_sBIT;
6012
Chris Craikb50c2172013-07-29 15:28:30 -07006013 that->blue = sample_scale(that->bluef, scale);
Matt Sarett9ea75692016-01-08 13:00:42 -05006014 if (sig_bits && that->blue_sBIT < that->sample_depth)
6015 that->blue >>= that->sample_depth - that->blue_sBIT;
6016
Chris Craikb50c2172013-07-29 15:28:30 -07006017 that->greene += 1./(2*((1U<<that->green_sBIT)-1));
6018 that->bluee += 1./(2*((1U<<that->blue_sBIT)-1));
6019 }
6020 else
6021 {
6022 that->blue = that->green = that->red;
6023 that->bluef = that->greenf = that->redf;
6024 that->bluee = that->greene = that->rede;
6025 }
6026
6027 if ((that->colour_type & PNG_COLOR_MASK_ALPHA) ||
6028 that->colour_type == PNG_COLOR_TYPE_PALETTE)
6029 {
6030 that->alpha = sample_scale(that->alphaf, scale);
6031 that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1));
6032 }
6033 else
6034 {
6035 that->alpha = scale; /* opaque */
Matt Sarett9ea75692016-01-08 13:00:42 -05006036 that->alphaf = 1; /* Override this. */
Chris Craikb50c2172013-07-29 15:28:30 -07006037 that->alphae = 0; /* It's exact ;-) */
6038 }
Matt Sarett9ea75692016-01-08 13:00:42 -05006039
6040 if (sig_bits && that->alpha_sBIT < that->sample_depth)
6041 that->alpha >>= that->sample_depth - that->alpha_sBIT;
Chris Craikb50c2172013-07-29 15:28:30 -07006042}
6043
6044/* Static 'end' structure: */
6045static image_transform image_transform_end =
6046{
6047 "(end)", /* name */
6048 1, /* enable */
6049 0, /* list */
6050 0, /* global_use */
6051 0, /* local_use */
6052 0, /* next */
6053 image_transform_ini_end,
6054 image_transform_set_end,
6055 image_transform_mod_end,
6056 0 /* never called, I want it to crash if it is! */
6057};
6058
6059/* Reader callbacks and implementations, where they differ from the standard
6060 * ones.
6061 */
6062static void
6063transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id,
Matt Sarett9ea75692016-01-08 13:00:42 -05006064 const image_transform *transform_list)
Chris Craikb50c2172013-07-29 15:28:30 -07006065{
6066 memset(dp, 0, sizeof *dp);
6067
6068 /* Standard fields */
Matt Sarett9ea75692016-01-08 13:00:42 -05006069 standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
Chris Craikb50c2172013-07-29 15:28:30 -07006070 pm->use_update_info);
6071
6072 /* Parameter fields */
6073 dp->pm = pm;
6074 dp->transform_list = transform_list;
Matt Sarett9ea75692016-01-08 13:00:42 -05006075 dp->max_gamma_8 = 16;
Chris Craikb50c2172013-07-29 15:28:30 -07006076
6077 /* Local variable fields */
6078 dp->output_colour_type = 255; /* invalid */
6079 dp->output_bit_depth = 255; /* invalid */
Matt Sarett9ea75692016-01-08 13:00:42 -05006080 dp->unpacked = 0; /* not unpacked */
Chris Craikb50c2172013-07-29 15:28:30 -07006081}
6082
6083static void
6084transform_info_imp(transform_display *dp, png_structp pp, png_infop pi)
6085{
6086 /* Reuse the standard stuff as appropriate. */
6087 standard_info_part1(&dp->this, pp, pi);
6088
6089 /* Now set the list of transforms. */
6090 dp->transform_list->set(dp->transform_list, dp, pp, pi);
6091
6092 /* Update the info structure for these transforms: */
6093 {
6094 int i = dp->this.use_update_info;
6095 /* Always do one call, even if use_update_info is 0. */
6096 do
6097 png_read_update_info(pp, pi);
6098 while (--i > 0);
6099 }
6100
6101 /* And get the output information into the standard_display */
6102 standard_info_part2(&dp->this, pp, pi, 1/*images*/);
6103
6104 /* Plus the extra stuff we need for the transform tests: */
6105 dp->output_colour_type = png_get_color_type(pp, pi);
6106 dp->output_bit_depth = png_get_bit_depth(pp, pi);
6107
Matt Sarett9ea75692016-01-08 13:00:42 -05006108 /* If png_set_filler is in action then fake the output color type to include
6109 * an alpha channel where appropriate.
6110 */
6111 if (dp->output_bit_depth >= 8 &&
6112 (dp->output_colour_type == PNG_COLOR_TYPE_RGB ||
6113 dp->output_colour_type == PNG_COLOR_TYPE_GRAY) && dp->this.filler)
6114 dp->output_colour_type |= 4;
6115
Chris Craikb50c2172013-07-29 15:28:30 -07006116 /* Validate the combination of colour type and bit depth that we are getting
6117 * out of libpng; the semantics of something not in the PNG spec are, at
6118 * best, unclear.
6119 */
6120 switch (dp->output_colour_type)
6121 {
6122 case PNG_COLOR_TYPE_PALETTE:
6123 if (dp->output_bit_depth > 8) goto error;
6124 /*FALL THROUGH*/
6125 case PNG_COLOR_TYPE_GRAY:
6126 if (dp->output_bit_depth == 1 || dp->output_bit_depth == 2 ||
6127 dp->output_bit_depth == 4)
6128 break;
6129 /*FALL THROUGH*/
6130 default:
6131 if (dp->output_bit_depth == 8 || dp->output_bit_depth == 16)
6132 break;
6133 /*FALL THROUGH*/
6134 error:
6135 {
6136 char message[128];
6137 size_t pos;
6138
6139 pos = safecat(message, sizeof message, 0,
6140 "invalid final bit depth: colour type(");
6141 pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
6142 pos = safecat(message, sizeof message, pos, ") with bit depth: ");
6143 pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
6144
6145 png_error(pp, message);
6146 }
6147 }
6148
6149 /* Use a test pixel to check that the output agrees with what we expect -
Matt Sarett9ea75692016-01-08 13:00:42 -05006150 * this avoids running the whole test if the output is unexpected. This also
6151 * checks for internal errors.
Chris Craikb50c2172013-07-29 15:28:30 -07006152 */
6153 {
6154 image_pixel test_pixel;
6155
6156 memset(&test_pixel, 0, sizeof test_pixel);
6157 test_pixel.colour_type = dp->this.colour_type; /* input */
6158 test_pixel.bit_depth = dp->this.bit_depth;
6159 if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
6160 test_pixel.sample_depth = 8;
6161 else
6162 test_pixel.sample_depth = test_pixel.bit_depth;
6163 /* Don't need sBIT here, but it must be set to non-zero to avoid
6164 * arithmetic overflows.
6165 */
Matt Sarett9ea75692016-01-08 13:00:42 -05006166 test_pixel.have_tRNS = dp->this.is_transparent != 0;
Chris Craikb50c2172013-07-29 15:28:30 -07006167 test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT =
6168 test_pixel.alpha_sBIT = test_pixel.sample_depth;
6169
6170 dp->transform_list->mod(dp->transform_list, &test_pixel, pp, dp);
6171
6172 if (test_pixel.colour_type != dp->output_colour_type)
6173 {
6174 char message[128];
6175 size_t pos = safecat(message, sizeof message, 0, "colour type ");
6176
6177 pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
6178 pos = safecat(message, sizeof message, pos, " expected ");
6179 pos = safecatn(message, sizeof message, pos, test_pixel.colour_type);
6180
6181 png_error(pp, message);
6182 }
6183
6184 if (test_pixel.bit_depth != dp->output_bit_depth)
6185 {
6186 char message[128];
6187 size_t pos = safecat(message, sizeof message, 0, "bit depth ");
6188
6189 pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
6190 pos = safecat(message, sizeof message, pos, " expected ");
6191 pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
6192
6193 png_error(pp, message);
6194 }
6195
6196 /* If both bit depth and colour type are correct check the sample depth.
Chris Craikb50c2172013-07-29 15:28:30 -07006197 */
Matt Sarett9ea75692016-01-08 13:00:42 -05006198 if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE &&
6199 test_pixel.sample_depth != 8) /* oops - internal error! */
6200 png_error(pp, "pngvalid: internal: palette sample depth not 8");
6201 else if (dp->unpacked && test_pixel.bit_depth != 8)
6202 png_error(pp, "pngvalid: internal: bad unpacked pixel depth");
6203 else if (!dp->unpacked && test_pixel.colour_type != PNG_COLOR_TYPE_PALETTE
6204 && test_pixel.bit_depth != test_pixel.sample_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07006205 {
6206 char message[128];
6207 size_t pos = safecat(message, sizeof message, 0,
6208 "internal: sample depth ");
6209
Matt Sarett9ea75692016-01-08 13:00:42 -05006210 /* Because unless something has set 'unpacked' or the image is palette
6211 * mapped we expect the transform to keep sample depth and bit depth
6212 * the same.
6213 */
6214 pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth);
6215 pos = safecat(message, sizeof message, pos, " expected ");
6216 pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
6217
6218 png_error(pp, message);
6219 }
6220 else if (test_pixel.bit_depth != dp->output_bit_depth)
6221 {
6222 /* This could be a libpng error too; libpng has not produced what we
6223 * expect for the output bit depth.
6224 */
6225 char message[128];
6226 size_t pos = safecat(message, sizeof message, 0,
6227 "internal: bit depth ");
6228
Chris Craikb50c2172013-07-29 15:28:30 -07006229 pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
6230 pos = safecat(message, sizeof message, pos, " expected ");
Matt Sarett9ea75692016-01-08 13:00:42 -05006231 pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
Chris Craikb50c2172013-07-29 15:28:30 -07006232
6233 png_error(pp, message);
6234 }
6235 }
6236}
6237
Sireesh Tripurarib478e662014-05-09 15:15:10 +05306238static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07006239transform_info(png_structp pp, png_infop pi)
6240{
6241 transform_info_imp(voidcast(transform_display*, png_get_progressive_ptr(pp)),
6242 pp, pi);
6243}
6244
6245static void
6246transform_range_check(png_const_structp pp, unsigned int r, unsigned int g,
6247 unsigned int b, unsigned int a, unsigned int in_digitized, double in,
6248 unsigned int out, png_byte sample_depth, double err, double limit,
Matt Sarett9ea75692016-01-08 13:00:42 -05006249 const char *name, double digitization_error)
Chris Craikb50c2172013-07-29 15:28:30 -07006250{
6251 /* Compare the scaled, digitzed, values of our local calculation (in+-err)
6252 * with the digitized values libpng produced; 'sample_depth' is the actual
6253 * digitization depth of the libpng output colors (the bit depth except for
6254 * palette images where it is always 8.) The check on 'err' is to detect
6255 * internal errors in pngvalid itself.
6256 */
6257 unsigned int max = (1U<<sample_depth)-1;
6258 double in_min = ceil((in-err)*max - digitization_error);
6259 double in_max = floor((in+err)*max + digitization_error);
6260 if (err > limit || !(out >= in_min && out <= in_max))
6261 {
6262 char message[256];
6263 size_t pos;
6264
6265 pos = safecat(message, sizeof message, 0, name);
6266 pos = safecat(message, sizeof message, pos, " output value error: rgba(");
6267 pos = safecatn(message, sizeof message, pos, r);
6268 pos = safecat(message, sizeof message, pos, ",");
6269 pos = safecatn(message, sizeof message, pos, g);
6270 pos = safecat(message, sizeof message, pos, ",");
6271 pos = safecatn(message, sizeof message, pos, b);
6272 pos = safecat(message, sizeof message, pos, ",");
6273 pos = safecatn(message, sizeof message, pos, a);
6274 pos = safecat(message, sizeof message, pos, "): ");
6275 pos = safecatn(message, sizeof message, pos, out);
6276 pos = safecat(message, sizeof message, pos, " expected: ");
6277 pos = safecatn(message, sizeof message, pos, in_digitized);
6278 pos = safecat(message, sizeof message, pos, " (");
6279 pos = safecatd(message, sizeof message, pos, (in-err)*max, 3);
6280 pos = safecat(message, sizeof message, pos, "..");
6281 pos = safecatd(message, sizeof message, pos, (in+err)*max, 3);
6282 pos = safecat(message, sizeof message, pos, ")");
6283
6284 png_error(pp, message);
6285 }
6286}
6287
6288static void
6289transform_image_validate(transform_display *dp, png_const_structp pp,
6290 png_infop pi)
6291{
6292 /* Constants for the loop below: */
Matt Sarett9ea75692016-01-08 13:00:42 -05006293 const png_store* const ps = dp->this.ps;
6294 const png_byte in_ct = dp->this.colour_type;
6295 const png_byte in_bd = dp->this.bit_depth;
6296 const png_uint_32 w = dp->this.w;
6297 const png_uint_32 h = dp->this.h;
6298 const png_byte out_ct = dp->output_colour_type;
6299 const png_byte out_bd = dp->output_bit_depth;
6300 const png_byte sample_depth = (png_byte)(out_ct ==
Chris Craikb50c2172013-07-29 15:28:30 -07006301 PNG_COLOR_TYPE_PALETTE ? 8 : out_bd);
Matt Sarett9ea75692016-01-08 13:00:42 -05006302 const png_byte red_sBIT = dp->this.red_sBIT;
6303 const png_byte green_sBIT = dp->this.green_sBIT;
6304 const png_byte blue_sBIT = dp->this.blue_sBIT;
6305 const png_byte alpha_sBIT = dp->this.alpha_sBIT;
6306 const int have_tRNS = dp->this.is_transparent;
Chris Craikb50c2172013-07-29 15:28:30 -07006307 double digitization_error;
6308
6309 store_palette out_palette;
6310 png_uint_32 y;
6311
6312 UNUSED(pi)
6313
6314 /* Check for row overwrite errors */
6315 store_image_check(dp->this.ps, pp, 0);
6316
6317 /* Read the palette corresponding to the output if the output colour type
6318 * indicates a palette, othewise set out_palette to garbage.
6319 */
6320 if (out_ct == PNG_COLOR_TYPE_PALETTE)
6321 {
6322 /* Validate that the palette count itself has not changed - this is not
6323 * expected.
6324 */
6325 int npalette = (-1);
6326
6327 (void)read_palette(out_palette, &npalette, pp, pi);
6328 if (npalette != dp->this.npalette)
6329 png_error(pp, "unexpected change in palette size");
6330
6331 digitization_error = .5;
6332 }
6333 else
6334 {
6335 png_byte in_sample_depth;
6336
6337 memset(out_palette, 0x5e, sizeof out_palette);
6338
Sireesh Tripurarib478e662014-05-09 15:15:10 +05306339 /* use-input-precision means assume that if the input has 8 bit (or less)
6340 * samples and the output has 16 bit samples the calculations will be done
6341 * with 8 bit precision, not 16.
Chris Craikb50c2172013-07-29 15:28:30 -07006342 */
6343 if (in_ct == PNG_COLOR_TYPE_PALETTE || in_bd < 16)
6344 in_sample_depth = 8;
6345 else
6346 in_sample_depth = in_bd;
6347
6348 if (sample_depth != 16 || in_sample_depth > 8 ||
6349 !dp->pm->calculations_use_input_precision)
6350 digitization_error = .5;
6351
Sireesh Tripurarib478e662014-05-09 15:15:10 +05306352 /* Else calculations are at 8 bit precision, and the output actually
6353 * consists of scaled 8-bit values, so scale .5 in 8 bits to the 16 bits:
Chris Craikb50c2172013-07-29 15:28:30 -07006354 */
6355 else
6356 digitization_error = .5 * 257;
6357 }
6358
6359 for (y=0; y<h; ++y)
6360 {
Matt Sarett9ea75692016-01-08 13:00:42 -05006361 png_const_bytep const pRow = store_image_row(ps, pp, 0, y);
Chris Craikb50c2172013-07-29 15:28:30 -07006362 png_uint_32 x;
6363
6364 /* The original, standard, row pre-transforms. */
6365 png_byte std[STANDARD_ROWMAX];
6366
6367 transform_row(pp, std, in_ct, in_bd, y);
6368
6369 /* Go through each original pixel transforming it and comparing with what
6370 * libpng did to the same pixel.
6371 */
6372 for (x=0; x<w; ++x)
6373 {
6374 image_pixel in_pixel, out_pixel;
6375 unsigned int r, g, b, a;
6376
6377 /* Find out what we think the pixel should be: */
Matt Sarett9ea75692016-01-08 13:00:42 -05006378 image_pixel_init(&in_pixel, std, in_ct, in_bd, x, dp->this.palette,
6379 NULL);
Chris Craikb50c2172013-07-29 15:28:30 -07006380
6381 in_pixel.red_sBIT = red_sBIT;
6382 in_pixel.green_sBIT = green_sBIT;
6383 in_pixel.blue_sBIT = blue_sBIT;
6384 in_pixel.alpha_sBIT = alpha_sBIT;
Matt Sarett9ea75692016-01-08 13:00:42 -05006385 in_pixel.have_tRNS = have_tRNS != 0;
Chris Craikb50c2172013-07-29 15:28:30 -07006386
6387 /* For error detection, below. */
6388 r = in_pixel.red;
6389 g = in_pixel.green;
6390 b = in_pixel.blue;
6391 a = in_pixel.alpha;
6392
Matt Sarett9ea75692016-01-08 13:00:42 -05006393 /* This applies the transforms to the input data, including output
6394 * format operations which must be used when reading the output
6395 * pixel that libpng produces.
6396 */
Chris Craikb50c2172013-07-29 15:28:30 -07006397 dp->transform_list->mod(dp->transform_list, &in_pixel, pp, dp);
6398
6399 /* Read the output pixel and compare it to what we got, we don't
Matt Sarett9ea75692016-01-08 13:00:42 -05006400 * use the error field here, so no need to update sBIT. in_pixel
6401 * says whether we expect libpng to change the output format.
Chris Craikb50c2172013-07-29 15:28:30 -07006402 */
Matt Sarett9ea75692016-01-08 13:00:42 -05006403 image_pixel_init(&out_pixel, pRow, out_ct, out_bd, x, out_palette,
6404 &in_pixel);
Chris Craikb50c2172013-07-29 15:28:30 -07006405
6406 /* We don't expect changes to the index here even if the bit depth is
6407 * changed.
6408 */
6409 if (in_ct == PNG_COLOR_TYPE_PALETTE &&
6410 out_ct == PNG_COLOR_TYPE_PALETTE)
6411 {
6412 if (in_pixel.palette_index != out_pixel.palette_index)
6413 png_error(pp, "unexpected transformed palette index");
6414 }
6415
6416 /* Check the colours for palette images too - in fact the palette could
6417 * be separately verified itself in most cases.
6418 */
6419 if (in_pixel.red != out_pixel.red)
6420 transform_range_check(pp, r, g, b, a, in_pixel.red, in_pixel.redf,
6421 out_pixel.red, sample_depth, in_pixel.rede,
6422 dp->pm->limit + 1./(2*((1U<<in_pixel.red_sBIT)-1)), "red/gray",
6423 digitization_error);
6424
6425 if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
6426 in_pixel.green != out_pixel.green)
6427 transform_range_check(pp, r, g, b, a, in_pixel.green,
6428 in_pixel.greenf, out_pixel.green, sample_depth, in_pixel.greene,
6429 dp->pm->limit + 1./(2*((1U<<in_pixel.green_sBIT)-1)), "green",
6430 digitization_error);
6431
6432 if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
6433 in_pixel.blue != out_pixel.blue)
6434 transform_range_check(pp, r, g, b, a, in_pixel.blue, in_pixel.bluef,
6435 out_pixel.blue, sample_depth, in_pixel.bluee,
6436 dp->pm->limit + 1./(2*((1U<<in_pixel.blue_sBIT)-1)), "blue",
6437 digitization_error);
6438
6439 if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0 &&
6440 in_pixel.alpha != out_pixel.alpha)
6441 transform_range_check(pp, r, g, b, a, in_pixel.alpha,
6442 in_pixel.alphaf, out_pixel.alpha, sample_depth, in_pixel.alphae,
6443 dp->pm->limit + 1./(2*((1U<<in_pixel.alpha_sBIT)-1)), "alpha",
6444 digitization_error);
6445 } /* pixel (x) loop */
6446 } /* row (y) loop */
6447
6448 /* Record that something was actually checked to avoid a false positive. */
6449 dp->this.ps->validated = 1;
6450}
6451
Sireesh Tripurarib478e662014-05-09 15:15:10 +05306452static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07006453transform_end(png_structp ppIn, png_infop pi)
6454{
6455 png_const_structp pp = ppIn;
6456 transform_display *dp = voidcast(transform_display*,
6457 png_get_progressive_ptr(pp));
6458
6459 if (!dp->this.speed)
6460 transform_image_validate(dp, pp, pi);
6461 else
6462 dp->this.ps->validated = 1;
6463}
6464
6465/* A single test run. */
6466static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006467transform_test(png_modifier *pmIn, const png_uint_32 idIn,
6468 const image_transform* transform_listIn, const char * const name)
Chris Craikb50c2172013-07-29 15:28:30 -07006469{
6470 transform_display d;
6471 context(&pmIn->this, fault);
6472
6473 transform_display_init(&d, pmIn, idIn, transform_listIn);
6474
6475 Try
6476 {
6477 size_t pos = 0;
6478 png_structp pp;
6479 png_infop pi;
6480 char full_name[256];
6481
6482 /* Make sure the encoding fields are correct and enter the required
6483 * modifications.
6484 */
6485 transform_set_encoding(&d);
6486
6487 /* Add any modifications required by the transform list. */
6488 d.transform_list->ini(d.transform_list, &d);
6489
6490 /* Add the color space information, if any, to the name. */
6491 pos = safecat(full_name, sizeof full_name, pos, name);
6492 pos = safecat_current_encoding(full_name, sizeof full_name, pos, d.pm);
6493
6494 /* Get a png_struct for reading the image. */
6495 pp = set_modifier_for_read(d.pm, &pi, d.this.id, full_name);
6496 standard_palette_init(&d.this);
6497
6498# if 0
6499 /* Logging (debugging only) */
6500 {
6501 char buffer[256];
6502
6503 (void)store_message(&d.pm->this, pp, buffer, sizeof buffer, 0,
6504 "running test");
6505
6506 fprintf(stderr, "%s\n", buffer);
6507 }
6508# endif
6509
6510 /* Introduce the correct read function. */
6511 if (d.pm->this.progressive)
6512 {
6513 /* Share the row function with the standard implementation. */
6514 png_set_progressive_read_fn(pp, &d, transform_info, progressive_row,
6515 transform_end);
6516
6517 /* Now feed data into the reader until we reach the end: */
6518 modifier_progressive_read(d.pm, pp, pi);
6519 }
6520 else
6521 {
6522 /* modifier_read expects a png_modifier* */
6523 png_set_read_fn(pp, d.pm, modifier_read);
6524
6525 /* Check the header values: */
6526 png_read_info(pp, pi);
6527
6528 /* Process the 'info' requirements. Only one image is generated */
6529 transform_info_imp(&d, pp, pi);
6530
6531 sequential_row(&d.this, pp, pi, -1, 0);
6532
6533 if (!d.this.speed)
6534 transform_image_validate(&d, pp, pi);
6535 else
6536 d.this.ps->validated = 1;
6537 }
6538
6539 modifier_reset(d.pm);
6540 }
6541
6542 Catch(fault)
6543 {
Sireesh Tripurarib478e662014-05-09 15:15:10 +05306544 modifier_reset(voidcast(png_modifier*,(void*)fault));
Chris Craikb50c2172013-07-29 15:28:30 -07006545 }
6546}
6547
6548/* The transforms: */
6549#define ITSTRUCT(name) image_transform_##name
6550#define ITDATA(name) image_transform_data_##name
6551#define image_transform_ini image_transform_default_ini
6552#define IT(name)\
6553static image_transform ITSTRUCT(name) =\
6554{\
6555 #name,\
6556 1, /*enable*/\
6557 &PT, /*list*/\
6558 0, /*global_use*/\
6559 0, /*local_use*/\
6560 0, /*next*/\
6561 image_transform_ini,\
6562 image_transform_png_set_##name##_set,\
6563 image_transform_png_set_##name##_mod,\
6564 image_transform_png_set_##name##_add\
6565}
6566#define PT ITSTRUCT(end) /* stores the previous transform */
6567
6568/* To save code: */
Matt Sarett9ea75692016-01-08 13:00:42 -05006569extern void image_transform_default_ini(const image_transform *this,
6570 transform_display *that); /* silence GCC warnings */
6571
6572void /* private, but almost always needed */
6573image_transform_default_ini(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006574 transform_display *that)
6575{
6576 this->next->ini(this->next, that);
6577}
6578
6579#ifdef PNG_READ_BACKGROUND_SUPPORTED
6580static int
6581image_transform_default_add(image_transform *this,
Matt Sarett9ea75692016-01-08 13:00:42 -05006582 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07006583{
6584 UNUSED(colour_type)
6585 UNUSED(bit_depth)
6586
6587 this->next = *that;
6588 *that = this;
6589
6590 return 1;
6591}
6592#endif
6593
6594#ifdef PNG_READ_EXPAND_SUPPORTED
6595/* png_set_palette_to_rgb */
6596static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006597image_transform_png_set_palette_to_rgb_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006598 transform_display *that, png_structp pp, png_infop pi)
6599{
6600 png_set_palette_to_rgb(pp);
6601 this->next->set(this->next, that, pp, pi);
6602}
6603
6604static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006605image_transform_png_set_palette_to_rgb_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006606 image_pixel *that, png_const_structp pp,
Matt Sarett9ea75692016-01-08 13:00:42 -05006607 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07006608{
6609 if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
6610 image_pixel_convert_PLTE(that);
6611
6612 this->next->mod(this->next, that, pp, display);
6613}
6614
6615static int
6616image_transform_png_set_palette_to_rgb_add(image_transform *this,
Matt Sarett9ea75692016-01-08 13:00:42 -05006617 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07006618{
6619 UNUSED(bit_depth)
6620
6621 this->next = *that;
6622 *that = this;
6623
6624 return colour_type == PNG_COLOR_TYPE_PALETTE;
6625}
6626
6627IT(palette_to_rgb);
6628#undef PT
6629#define PT ITSTRUCT(palette_to_rgb)
6630#endif /* PNG_READ_EXPAND_SUPPORTED */
6631
6632#ifdef PNG_READ_EXPAND_SUPPORTED
6633/* png_set_tRNS_to_alpha */
6634static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006635image_transform_png_set_tRNS_to_alpha_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006636 transform_display *that, png_structp pp, png_infop pi)
6637{
6638 png_set_tRNS_to_alpha(pp);
Matt Sarett9ea75692016-01-08 13:00:42 -05006639
6640 /* If there was a tRNS chunk that would get expanded and add an alpha
6641 * channel is_transparent must be updated:
6642 */
6643 if (that->this.has_tRNS)
6644 that->this.is_transparent = 1;
6645
Chris Craikb50c2172013-07-29 15:28:30 -07006646 this->next->set(this->next, that, pp, pi);
6647}
6648
6649static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006650image_transform_png_set_tRNS_to_alpha_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006651 image_pixel *that, png_const_structp pp,
Matt Sarett9ea75692016-01-08 13:00:42 -05006652 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07006653{
Matt Sarett9ea75692016-01-08 13:00:42 -05006654#if PNG_LIBPNG_VER < 10700
Chris Craikb50c2172013-07-29 15:28:30 -07006655 /* LIBPNG BUG: this always forces palette images to RGB. */
6656 if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
6657 image_pixel_convert_PLTE(that);
Matt Sarett9ea75692016-01-08 13:00:42 -05006658#endif
Chris Craikb50c2172013-07-29 15:28:30 -07006659
6660 /* This effectively does an 'expand' only if there is some transparency to
6661 * convert to an alpha channel.
6662 */
6663 if (that->have_tRNS)
Matt Sarett9ea75692016-01-08 13:00:42 -05006664# if PNG_LIBPNG_VER >= 10700
6665 if (that->colour_type != PNG_COLOR_TYPE_PALETTE &&
6666 (that->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
6667# endif
6668 image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
Chris Craikb50c2172013-07-29 15:28:30 -07006669
Matt Sarett9ea75692016-01-08 13:00:42 -05006670#if PNG_LIBPNG_VER < 10700
Chris Craikb50c2172013-07-29 15:28:30 -07006671 /* LIBPNG BUG: otherwise libpng still expands to 8 bits! */
6672 else
6673 {
6674 if (that->bit_depth < 8)
6675 that->bit_depth =8;
6676 if (that->sample_depth < 8)
6677 that->sample_depth = 8;
6678 }
Matt Sarett9ea75692016-01-08 13:00:42 -05006679#endif
Chris Craikb50c2172013-07-29 15:28:30 -07006680
6681 this->next->mod(this->next, that, pp, display);
6682}
6683
6684static int
6685image_transform_png_set_tRNS_to_alpha_add(image_transform *this,
Matt Sarett9ea75692016-01-08 13:00:42 -05006686 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07006687{
6688 UNUSED(bit_depth)
6689
6690 this->next = *that;
6691 *that = this;
6692
6693 /* We don't know yet whether there will be a tRNS chunk, but we know that
6694 * this transformation should do nothing if there already is an alpha
Matt Sarett9ea75692016-01-08 13:00:42 -05006695 * channel. In addition, after the bug fix in 1.7.0, there is no longer
6696 * any action on a palette image.
Chris Craikb50c2172013-07-29 15:28:30 -07006697 */
Matt Sarett9ea75692016-01-08 13:00:42 -05006698 return
6699# if PNG_LIBPNG_VER >= 10700
6700 colour_type != PNG_COLOR_TYPE_PALETTE &&
6701# endif
6702 (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
Chris Craikb50c2172013-07-29 15:28:30 -07006703}
6704
6705IT(tRNS_to_alpha);
6706#undef PT
6707#define PT ITSTRUCT(tRNS_to_alpha)
6708#endif /* PNG_READ_EXPAND_SUPPORTED */
6709
6710#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
6711/* png_set_gray_to_rgb */
6712static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006713image_transform_png_set_gray_to_rgb_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006714 transform_display *that, png_structp pp, png_infop pi)
6715{
6716 png_set_gray_to_rgb(pp);
Matt Sarett9ea75692016-01-08 13:00:42 -05006717 /* NOTE: this doesn't result in tRNS expansion. */
Chris Craikb50c2172013-07-29 15:28:30 -07006718 this->next->set(this->next, that, pp, pi);
6719}
6720
6721static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006722image_transform_png_set_gray_to_rgb_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006723 image_pixel *that, png_const_structp pp,
Matt Sarett9ea75692016-01-08 13:00:42 -05006724 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07006725{
6726 /* NOTE: we can actually pend the tRNS processing at this point because we
6727 * can correctly recognize the original pixel value even though we have
6728 * mapped the one gray channel to the three RGB ones, but in fact libpng
6729 * doesn't do this, so we don't either.
6730 */
6731 if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS)
Matt Sarett9ea75692016-01-08 13:00:42 -05006732 image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
Chris Craikb50c2172013-07-29 15:28:30 -07006733
6734 /* Simply expand the bit depth and alter the colour type as required. */
6735 if (that->colour_type == PNG_COLOR_TYPE_GRAY)
6736 {
6737 /* RGB images have a bit depth at least equal to '8' */
6738 if (that->bit_depth < 8)
6739 that->sample_depth = that->bit_depth = 8;
6740
6741 /* And just changing the colour type works here because the green and blue
6742 * channels are being maintained in lock-step with the red/gray:
6743 */
6744 that->colour_type = PNG_COLOR_TYPE_RGB;
6745 }
6746
6747 else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
6748 that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
6749
6750 this->next->mod(this->next, that, pp, display);
6751}
6752
6753static int
6754image_transform_png_set_gray_to_rgb_add(image_transform *this,
Matt Sarett9ea75692016-01-08 13:00:42 -05006755 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07006756{
6757 UNUSED(bit_depth)
6758
6759 this->next = *that;
6760 *that = this;
6761
6762 return (colour_type & PNG_COLOR_MASK_COLOR) == 0;
6763}
6764
6765IT(gray_to_rgb);
6766#undef PT
6767#define PT ITSTRUCT(gray_to_rgb)
6768#endif /* PNG_READ_GRAY_TO_RGB_SUPPORTED */
6769
6770#ifdef PNG_READ_EXPAND_SUPPORTED
6771/* png_set_expand */
6772static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006773image_transform_png_set_expand_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006774 transform_display *that, png_structp pp, png_infop pi)
6775{
6776 png_set_expand(pp);
Matt Sarett9ea75692016-01-08 13:00:42 -05006777
6778 if (that->this.has_tRNS)
6779 that->this.is_transparent = 1;
6780
Chris Craikb50c2172013-07-29 15:28:30 -07006781 this->next->set(this->next, that, pp, pi);
6782}
6783
6784static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006785image_transform_png_set_expand_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006786 image_pixel *that, png_const_structp pp,
Matt Sarett9ea75692016-01-08 13:00:42 -05006787 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07006788{
6789 /* The general expand case depends on what the colour type is: */
6790 if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
6791 image_pixel_convert_PLTE(that);
6792 else if (that->bit_depth < 8) /* grayscale */
6793 that->sample_depth = that->bit_depth = 8;
6794
6795 if (that->have_tRNS)
Matt Sarett9ea75692016-01-08 13:00:42 -05006796 image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
Chris Craikb50c2172013-07-29 15:28:30 -07006797
6798 this->next->mod(this->next, that, pp, display);
6799}
6800
6801static int
6802image_transform_png_set_expand_add(image_transform *this,
Matt Sarett9ea75692016-01-08 13:00:42 -05006803 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07006804{
6805 UNUSED(bit_depth)
6806
6807 this->next = *that;
6808 *that = this;
6809
6810 /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit
6811 * depth is at least 8 already.
6812 */
6813 return (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
6814}
6815
6816IT(expand);
6817#undef PT
6818#define PT ITSTRUCT(expand)
6819#endif /* PNG_READ_EXPAND_SUPPORTED */
6820
6821#ifdef PNG_READ_EXPAND_SUPPORTED
6822/* png_set_expand_gray_1_2_4_to_8
Matt Sarett9ea75692016-01-08 13:00:42 -05006823 * Pre 1.7.0 LIBPNG BUG: this just does an 'expand'
Chris Craikb50c2172013-07-29 15:28:30 -07006824 */
6825static void
6826image_transform_png_set_expand_gray_1_2_4_to_8_set(
Matt Sarett9ea75692016-01-08 13:00:42 -05006827 const image_transform *this, transform_display *that, png_structp pp,
Chris Craikb50c2172013-07-29 15:28:30 -07006828 png_infop pi)
6829{
6830 png_set_expand_gray_1_2_4_to_8(pp);
Matt Sarett9ea75692016-01-08 13:00:42 -05006831 /* NOTE: don't expect this to expand tRNS */
Chris Craikb50c2172013-07-29 15:28:30 -07006832 this->next->set(this->next, that, pp, pi);
6833}
6834
6835static void
6836image_transform_png_set_expand_gray_1_2_4_to_8_mod(
Matt Sarett9ea75692016-01-08 13:00:42 -05006837 const image_transform *this, image_pixel *that, png_const_structp pp,
6838 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07006839{
Matt Sarett9ea75692016-01-08 13:00:42 -05006840#if PNG_LIBPNG_VER < 10700
Chris Craikb50c2172013-07-29 15:28:30 -07006841 image_transform_png_set_expand_mod(this, that, pp, display);
Matt Sarett9ea75692016-01-08 13:00:42 -05006842#else
6843 /* Only expand grayscale of bit depth less than 8: */
6844 if (that->colour_type == PNG_COLOR_TYPE_GRAY &&
6845 that->bit_depth < 8)
6846 that->sample_depth = that->bit_depth = 8;
6847
6848 this->next->mod(this->next, that, pp, display);
6849#endif /* 1.7 or later */
Chris Craikb50c2172013-07-29 15:28:30 -07006850}
6851
6852static int
6853image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this,
Matt Sarett9ea75692016-01-08 13:00:42 -05006854 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07006855{
Matt Sarett9ea75692016-01-08 13:00:42 -05006856#if PNG_LIBPNG_VER < 10700
Chris Craikb50c2172013-07-29 15:28:30 -07006857 return image_transform_png_set_expand_add(this, that, colour_type,
6858 bit_depth);
Matt Sarett9ea75692016-01-08 13:00:42 -05006859#else
6860 UNUSED(bit_depth)
6861
6862 this->next = *that;
6863 *that = this;
6864
6865 /* This should do nothing unless the color type is gray and the bit depth is
6866 * less than 8:
6867 */
6868 return colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8;
6869#endif /* 1.7 or later */
Chris Craikb50c2172013-07-29 15:28:30 -07006870}
6871
6872IT(expand_gray_1_2_4_to_8);
6873#undef PT
6874#define PT ITSTRUCT(expand_gray_1_2_4_to_8)
6875#endif /* PNG_READ_EXPAND_SUPPORTED */
6876
6877#ifdef PNG_READ_EXPAND_16_SUPPORTED
6878/* png_set_expand_16 */
6879static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006880image_transform_png_set_expand_16_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006881 transform_display *that, png_structp pp, png_infop pi)
6882{
6883 png_set_expand_16(pp);
Matt Sarett9ea75692016-01-08 13:00:42 -05006884
6885 /* NOTE: prior to 1.7 libpng does SET_EXPAND as well, so tRNS is expanded. */
6886# if PNG_LIBPNG_VER < 10700
6887 if (that->this.has_tRNS)
6888 that->this.is_transparent = 1;
6889# endif
6890
Chris Craikb50c2172013-07-29 15:28:30 -07006891 this->next->set(this->next, that, pp, pi);
6892}
6893
6894static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006895image_transform_png_set_expand_16_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006896 image_pixel *that, png_const_structp pp,
Matt Sarett9ea75692016-01-08 13:00:42 -05006897 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07006898{
6899 /* Expect expand_16 to expand everything to 16 bits as a result of also
6900 * causing 'expand' to happen.
6901 */
6902 if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
6903 image_pixel_convert_PLTE(that);
6904
6905 if (that->have_tRNS)
Matt Sarett9ea75692016-01-08 13:00:42 -05006906 image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
Chris Craikb50c2172013-07-29 15:28:30 -07006907
6908 if (that->bit_depth < 16)
6909 that->sample_depth = that->bit_depth = 16;
6910
6911 this->next->mod(this->next, that, pp, display);
6912}
6913
6914static int
6915image_transform_png_set_expand_16_add(image_transform *this,
Matt Sarett9ea75692016-01-08 13:00:42 -05006916 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07006917{
6918 UNUSED(colour_type)
6919
6920 this->next = *that;
6921 *that = this;
6922
6923 /* expand_16 does something unless the bit depth is already 16. */
6924 return bit_depth < 16;
6925}
6926
6927IT(expand_16);
6928#undef PT
6929#define PT ITSTRUCT(expand_16)
6930#endif /* PNG_READ_EXPAND_16_SUPPORTED */
6931
6932#ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED /* API added in 1.5.4 */
6933/* png_set_scale_16 */
6934static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006935image_transform_png_set_scale_16_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006936 transform_display *that, png_structp pp, png_infop pi)
6937{
6938 png_set_scale_16(pp);
Matt Sarett9ea75692016-01-08 13:00:42 -05006939# if PNG_LIBPNG_VER < 10700
6940 /* libpng will limit the gamma table size: */
6941 that->max_gamma_8 = PNG_MAX_GAMMA_8;
6942# endif
Chris Craikb50c2172013-07-29 15:28:30 -07006943 this->next->set(this->next, that, pp, pi);
6944}
6945
6946static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006947image_transform_png_set_scale_16_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006948 image_pixel *that, png_const_structp pp,
Matt Sarett9ea75692016-01-08 13:00:42 -05006949 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07006950{
6951 if (that->bit_depth == 16)
6952 {
6953 that->sample_depth = that->bit_depth = 8;
6954 if (that->red_sBIT > 8) that->red_sBIT = 8;
6955 if (that->green_sBIT > 8) that->green_sBIT = 8;
6956 if (that->blue_sBIT > 8) that->blue_sBIT = 8;
6957 if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
6958 }
6959
6960 this->next->mod(this->next, that, pp, display);
6961}
6962
6963static int
6964image_transform_png_set_scale_16_add(image_transform *this,
Matt Sarett9ea75692016-01-08 13:00:42 -05006965 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07006966{
6967 UNUSED(colour_type)
6968
6969 this->next = *that;
6970 *that = this;
6971
6972 return bit_depth > 8;
6973}
6974
6975IT(scale_16);
6976#undef PT
6977#define PT ITSTRUCT(scale_16)
6978#endif /* PNG_READ_SCALE_16_TO_8_SUPPORTED (1.5.4 on) */
6979
6980#ifdef PNG_READ_16_TO_8_SUPPORTED /* the default before 1.5.4 */
6981/* png_set_strip_16 */
6982static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006983image_transform_png_set_strip_16_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006984 transform_display *that, png_structp pp, png_infop pi)
6985{
6986 png_set_strip_16(pp);
Matt Sarett9ea75692016-01-08 13:00:42 -05006987# if PNG_LIBPNG_VER < 10700
6988 /* libpng will limit the gamma table size: */
6989 that->max_gamma_8 = PNG_MAX_GAMMA_8;
6990# endif
Chris Craikb50c2172013-07-29 15:28:30 -07006991 this->next->set(this->next, that, pp, pi);
6992}
6993
6994static void
Matt Sarett9ea75692016-01-08 13:00:42 -05006995image_transform_png_set_strip_16_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006996 image_pixel *that, png_const_structp pp,
Matt Sarett9ea75692016-01-08 13:00:42 -05006997 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07006998{
6999 if (that->bit_depth == 16)
7000 {
7001 that->sample_depth = that->bit_depth = 8;
7002 if (that->red_sBIT > 8) that->red_sBIT = 8;
7003 if (that->green_sBIT > 8) that->green_sBIT = 8;
7004 if (that->blue_sBIT > 8) that->blue_sBIT = 8;
7005 if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
7006
7007 /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
7008 * configuration option is set. From 1.5.4 the flag is never set and the
7009 * 'scale' API (above) must be used.
7010 */
7011# ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
7012# if PNG_LIBPNG_VER >= 10504
7013# error PNG_READ_ACCURATE_SCALE should not be set
7014# endif
7015
7016 /* The strip 16 algorithm drops the low 8 bits rather than calculating
7017 * 1/257, so we need to adjust the permitted errors appropriately:
7018 * Notice that this is only relevant prior to the addition of the
7019 * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
7020 */
7021 {
Matt Sarett9ea75692016-01-08 13:00:42 -05007022 const double d = (255-128.5)/65535;
Chris Craikb50c2172013-07-29 15:28:30 -07007023 that->rede += d;
7024 that->greene += d;
7025 that->bluee += d;
7026 that->alphae += d;
7027 }
7028# endif
7029 }
7030
7031 this->next->mod(this->next, that, pp, display);
7032}
7033
7034static int
7035image_transform_png_set_strip_16_add(image_transform *this,
Matt Sarett9ea75692016-01-08 13:00:42 -05007036 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07007037{
7038 UNUSED(colour_type)
7039
7040 this->next = *that;
7041 *that = this;
7042
7043 return bit_depth > 8;
7044}
7045
7046IT(strip_16);
7047#undef PT
7048#define PT ITSTRUCT(strip_16)
7049#endif /* PNG_READ_16_TO_8_SUPPORTED */
7050
7051#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
7052/* png_set_strip_alpha */
7053static void
Matt Sarett9ea75692016-01-08 13:00:42 -05007054image_transform_png_set_strip_alpha_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007055 transform_display *that, png_structp pp, png_infop pi)
7056{
7057 png_set_strip_alpha(pp);
7058 this->next->set(this->next, that, pp, pi);
7059}
7060
7061static void
Matt Sarett9ea75692016-01-08 13:00:42 -05007062image_transform_png_set_strip_alpha_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007063 image_pixel *that, png_const_structp pp,
Matt Sarett9ea75692016-01-08 13:00:42 -05007064 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07007065{
7066 if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
7067 that->colour_type = PNG_COLOR_TYPE_GRAY;
7068 else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
7069 that->colour_type = PNG_COLOR_TYPE_RGB;
7070
7071 that->have_tRNS = 0;
7072 that->alphaf = 1;
7073
7074 this->next->mod(this->next, that, pp, display);
7075}
7076
7077static int
7078image_transform_png_set_strip_alpha_add(image_transform *this,
Matt Sarett9ea75692016-01-08 13:00:42 -05007079 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07007080{
7081 UNUSED(bit_depth)
7082
7083 this->next = *that;
7084 *that = this;
7085
7086 return (colour_type & PNG_COLOR_MASK_ALPHA) != 0;
7087}
7088
7089IT(strip_alpha);
7090#undef PT
7091#define PT ITSTRUCT(strip_alpha)
7092#endif /* PNG_READ_STRIP_ALPHA_SUPPORTED */
7093
7094#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
7095/* png_set_rgb_to_gray(png_structp, int err_action, double red, double green)
7096 * png_set_rgb_to_gray_fixed(png_structp, int err_action, png_fixed_point red,
7097 * png_fixed_point green)
7098 * png_get_rgb_to_gray_status
7099 *
Matt Sarett9ea75692016-01-08 13:00:42 -05007100 * The 'default' test here uses values known to be used inside libpng prior to
7101 * 1.7.0:
Chris Craikb50c2172013-07-29 15:28:30 -07007102 *
7103 * red: 6968
7104 * green: 23434
7105 * blue: 2366
7106 *
7107 * These values are being retained for compatibility, along with the somewhat
7108 * broken truncation calculation in the fast-and-inaccurate code path. Older
7109 * versions of libpng will fail the accuracy tests below because they use the
7110 * truncation algorithm everywhere.
7111 */
7112#define data ITDATA(rgb_to_gray)
7113static struct
7114{
7115 double gamma; /* File gamma to use in processing */
7116
7117 /* The following are the parameters for png_set_rgb_to_gray: */
7118# ifdef PNG_FLOATING_POINT_SUPPORTED
7119 double red_to_set;
7120 double green_to_set;
7121# else
7122 png_fixed_point red_to_set;
7123 png_fixed_point green_to_set;
7124# endif
7125
7126 /* The actual coefficients: */
7127 double red_coefficient;
7128 double green_coefficient;
7129 double blue_coefficient;
7130
7131 /* Set if the coeefficients have been overridden. */
7132 int coefficients_overridden;
7133} data;
7134
7135#undef image_transform_ini
7136#define image_transform_ini image_transform_png_set_rgb_to_gray_ini
7137static void
Matt Sarett9ea75692016-01-08 13:00:42 -05007138image_transform_png_set_rgb_to_gray_ini(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007139 transform_display *that)
7140{
7141 png_modifier *pm = that->pm;
Matt Sarett9ea75692016-01-08 13:00:42 -05007142 const color_encoding *e = pm->current_encoding;
Chris Craikb50c2172013-07-29 15:28:30 -07007143
7144 UNUSED(this)
7145
7146 /* Since we check the encoding this flag must be set: */
7147 pm->test_uses_encoding = 1;
7148
7149 /* If 'e' is not NULL chromaticity information is present and either a cHRM
7150 * or an sRGB chunk will be inserted.
7151 */
7152 if (e != 0)
7153 {
7154 /* Coefficients come from the encoding, but may need to be normalized to a
7155 * white point Y of 1.0
7156 */
Matt Sarett9ea75692016-01-08 13:00:42 -05007157 const double whiteY = e->red.Y + e->green.Y + e->blue.Y;
Chris Craikb50c2172013-07-29 15:28:30 -07007158
7159 data.red_coefficient = e->red.Y;
7160 data.green_coefficient = e->green.Y;
7161 data.blue_coefficient = e->blue.Y;
7162
7163 if (whiteY != 1)
7164 {
7165 data.red_coefficient /= whiteY;
7166 data.green_coefficient /= whiteY;
7167 data.blue_coefficient /= whiteY;
7168 }
7169 }
7170
7171 else
7172 {
7173 /* The default (built in) coeffcients, as above: */
Matt Sarett9ea75692016-01-08 13:00:42 -05007174# if PNG_LIBPNG_VER < 10700
7175 data.red_coefficient = 6968 / 32768.;
7176 data.green_coefficient = 23434 / 32768.;
7177 data.blue_coefficient = 2366 / 32768.;
7178# else
7179 data.red_coefficient = .2126;
7180 data.green_coefficient = .7152;
7181 data.blue_coefficient = .0722;
7182# endif
Chris Craikb50c2172013-07-29 15:28:30 -07007183 }
7184
7185 data.gamma = pm->current_gamma;
7186
7187 /* If not set then the calculations assume linear encoding (implicitly): */
7188 if (data.gamma == 0)
7189 data.gamma = 1;
7190
7191 /* The arguments to png_set_rgb_to_gray can override the coefficients implied
7192 * by the color space encoding. If doing exhaustive checks do the override
7193 * in each case, otherwise do it randomly.
7194 */
7195 if (pm->test_exhaustive)
7196 {
7197 /* First time in coefficients_overridden is 0, the following sets it to 1,
7198 * so repeat if it is set. If a test fails this may mean we subsequently
7199 * skip a non-override test, ignore that.
7200 */
7201 data.coefficients_overridden = !data.coefficients_overridden;
7202 pm->repeat = data.coefficients_overridden != 0;
7203 }
7204
7205 else
7206 data.coefficients_overridden = random_choice();
7207
7208 if (data.coefficients_overridden)
7209 {
7210 /* These values override the color encoding defaults, simply use random
7211 * numbers.
7212 */
7213 png_uint_32 ru;
7214 double total;
7215
7216 RANDOMIZE(ru);
7217 data.green_coefficient = total = (ru & 0xffff) / 65535.;
7218 ru >>= 16;
7219 data.red_coefficient = (1 - total) * (ru & 0xffff) / 65535.;
7220 total += data.red_coefficient;
7221 data.blue_coefficient = 1 - total;
7222
7223# ifdef PNG_FLOATING_POINT_SUPPORTED
7224 data.red_to_set = data.red_coefficient;
7225 data.green_to_set = data.green_coefficient;
7226# else
7227 data.red_to_set = fix(data.red_coefficient);
7228 data.green_to_set = fix(data.green_coefficient);
7229# endif
7230
7231 /* The following just changes the error messages: */
7232 pm->encoding_ignored = 1;
7233 }
7234
7235 else
7236 {
7237 data.red_to_set = -1;
7238 data.green_to_set = -1;
7239 }
7240
7241 /* Adjust the error limit in the png_modifier because of the larger errors
7242 * produced in the digitization during the gamma handling.
7243 */
7244 if (data.gamma != 1) /* Use gamma tables */
7245 {
7246 if (that->this.bit_depth == 16 || pm->assume_16_bit_calculations)
7247 {
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307248 /* The computations have the form:
7249 *
7250 * r * rc + g * gc + b * bc
7251 *
7252 * Each component of which is +/-1/65535 from the gamma_to_1 table
7253 * lookup, resulting in a base error of +/-6. The gamma_from_1
7254 * conversion adds another +/-2 in the 16-bit case and
7255 * +/-(1<<(15-PNG_MAX_GAMMA_8)) in the 8-bit case.
Chris Craikb50c2172013-07-29 15:28:30 -07007256 */
Matt Sarett9ea75692016-01-08 13:00:42 -05007257# if PNG_LIBPNG_VER < 10700
7258 if (that->this.bit_depth < 16)
7259 that->max_gamma_8 = PNG_MAX_GAMMA_8;
7260# endif
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307261 that->pm->limit += pow(
Matt Sarett9ea75692016-01-08 13:00:42 -05007262 (that->this.bit_depth == 16 || that->max_gamma_8 > 14 ?
7263 8. :
7264 6. + (1<<(15-that->max_gamma_8))
7265 )/65535, data.gamma);
Chris Craikb50c2172013-07-29 15:28:30 -07007266 }
7267
7268 else
7269 {
7270 /* Rounding to 8 bits in the linear space causes massive errors which
7271 * will trigger the error check in transform_range_check. Fix that
7272 * here by taking the gamma encoding into account.
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307273 *
7274 * When DIGITIZE is set because a pre-1.7 version of libpng is being
7275 * tested allow a bigger slack.
7276 *
Matt Sarett9ea75692016-01-08 13:00:42 -05007277 * NOTE: this magic number was determined by experiment to be about
7278 * 1.263. There's no great merit to the value below, however it only
7279 * affects the limit used for checking for internal calculation errors,
7280 * not the actual limit imposed by pngvalid on the output errors.
Chris Craikb50c2172013-07-29 15:28:30 -07007281 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307282 that->pm->limit += pow(
Matt Sarett9ea75692016-01-08 13:00:42 -05007283# if DIGITIZE
7284 1.3
7285# else
7286 1.0
7287# endif
7288 /255, data.gamma);
Chris Craikb50c2172013-07-29 15:28:30 -07007289 }
7290 }
7291
7292 else
7293 {
7294 /* With no gamma correction a large error comes from the truncation of the
7295 * calculation in the 8 bit case, allow for that here.
7296 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307297 if (that->this.bit_depth != 16 && !pm->assume_16_bit_calculations)
Chris Craikb50c2172013-07-29 15:28:30 -07007298 that->pm->limit += 4E-3;
7299 }
7300}
7301
7302static void
Matt Sarett9ea75692016-01-08 13:00:42 -05007303image_transform_png_set_rgb_to_gray_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007304 transform_display *that, png_structp pp, png_infop pi)
7305{
Matt Sarett9ea75692016-01-08 13:00:42 -05007306 const int error_action = 1; /* no error, no defines in png.h */
Chris Craikb50c2172013-07-29 15:28:30 -07007307
7308# ifdef PNG_FLOATING_POINT_SUPPORTED
7309 png_set_rgb_to_gray(pp, error_action, data.red_to_set, data.green_to_set);
7310# else
7311 png_set_rgb_to_gray_fixed(pp, error_action, data.red_to_set,
7312 data.green_to_set);
7313# endif
7314
7315# ifdef PNG_READ_cHRM_SUPPORTED
7316 if (that->pm->current_encoding != 0)
7317 {
7318 /* We have an encoding so a cHRM chunk may have been set; if so then
7319 * check that the libpng APIs give the correct (X,Y,Z) values within
7320 * some margin of error for the round trip through the chromaticity
7321 * form.
7322 */
7323# ifdef PNG_FLOATING_POINT_SUPPORTED
7324# define API_function png_get_cHRM_XYZ
7325# define API_form "FP"
7326# define API_type double
7327# define API_cvt(x) (x)
7328# else
7329# define API_function png_get_cHRM_XYZ_fixed
7330# define API_form "fixed"
7331# define API_type png_fixed_point
7332# define API_cvt(x) ((double)(x)/PNG_FP_1)
7333# endif
7334
7335 API_type rX, gX, bX;
7336 API_type rY, gY, bY;
7337 API_type rZ, gZ, bZ;
7338
7339 if ((API_function(pp, pi, &rX, &rY, &rZ, &gX, &gY, &gZ, &bX, &bY, &bZ)
7340 & PNG_INFO_cHRM) != 0)
7341 {
7342 double maxe;
Matt Sarett9ea75692016-01-08 13:00:42 -05007343 const char *el;
Chris Craikb50c2172013-07-29 15:28:30 -07007344 color_encoding e, o;
7345
7346 /* Expect libpng to return a normalized result, but the original
7347 * color space encoding may not be normalized.
7348 */
7349 modifier_current_encoding(that->pm, &o);
7350 normalize_color_encoding(&o);
7351
7352 /* Sanity check the pngvalid code - the coefficients should match
7353 * the normalized Y values of the encoding unless they were
7354 * overridden.
7355 */
7356 if (data.red_to_set == -1 && data.green_to_set == -1 &&
7357 (fabs(o.red.Y - data.red_coefficient) > DBL_EPSILON ||
7358 fabs(o.green.Y - data.green_coefficient) > DBL_EPSILON ||
7359 fabs(o.blue.Y - data.blue_coefficient) > DBL_EPSILON))
7360 png_error(pp, "internal pngvalid cHRM coefficient error");
7361
7362 /* Generate a colour space encoding. */
7363 e.gamma = o.gamma; /* not used */
7364 e.red.X = API_cvt(rX);
7365 e.red.Y = API_cvt(rY);
7366 e.red.Z = API_cvt(rZ);
7367 e.green.X = API_cvt(gX);
7368 e.green.Y = API_cvt(gY);
7369 e.green.Z = API_cvt(gZ);
7370 e.blue.X = API_cvt(bX);
7371 e.blue.Y = API_cvt(bY);
7372 e.blue.Z = API_cvt(bZ);
7373
7374 /* This should match the original one from the png_modifier, within
7375 * the range permitted by the libpng fixed point representation.
7376 */
7377 maxe = 0;
7378 el = "-"; /* Set to element name with error */
7379
7380# define CHECK(col,x)\
7381 {\
7382 double err = fabs(o.col.x - e.col.x);\
7383 if (err > maxe)\
7384 {\
7385 maxe = err;\
7386 el = #col "(" #x ")";\
7387 }\
7388 }
7389
7390 CHECK(red,X)
7391 CHECK(red,Y)
7392 CHECK(red,Z)
7393 CHECK(green,X)
7394 CHECK(green,Y)
7395 CHECK(green,Z)
7396 CHECK(blue,X)
7397 CHECK(blue,Y)
7398 CHECK(blue,Z)
7399
7400 /* Here in both fixed and floating cases to check the values read
7401 * from the cHRm chunk. PNG uses fixed point in the cHRM chunk, so
7402 * we can't expect better than +/-.5E-5 on the result, allow 1E-5.
7403 */
7404 if (maxe >= 1E-5)
7405 {
7406 size_t pos = 0;
7407 char buffer[256];
7408
7409 pos = safecat(buffer, sizeof buffer, pos, API_form);
7410 pos = safecat(buffer, sizeof buffer, pos, " cHRM ");
7411 pos = safecat(buffer, sizeof buffer, pos, el);
7412 pos = safecat(buffer, sizeof buffer, pos, " error: ");
7413 pos = safecatd(buffer, sizeof buffer, pos, maxe, 7);
7414 pos = safecat(buffer, sizeof buffer, pos, " ");
7415 /* Print the color space without the gamma value: */
7416 pos = safecat_color_encoding(buffer, sizeof buffer, pos, &o, 0);
7417 pos = safecat(buffer, sizeof buffer, pos, " -> ");
7418 pos = safecat_color_encoding(buffer, sizeof buffer, pos, &e, 0);
7419
7420 png_error(pp, buffer);
7421 }
7422 }
7423 }
7424# endif /* READ_cHRM */
7425
7426 this->next->set(this->next, that, pp, pi);
7427}
7428
7429static void
Matt Sarett9ea75692016-01-08 13:00:42 -05007430image_transform_png_set_rgb_to_gray_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007431 image_pixel *that, png_const_structp pp,
Matt Sarett9ea75692016-01-08 13:00:42 -05007432 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07007433{
7434 if ((that->colour_type & PNG_COLOR_MASK_COLOR) != 0)
7435 {
7436 double gray, err;
7437
Matt Sarett9ea75692016-01-08 13:00:42 -05007438# if PNG_LIBPNG_VER < 10700
7439 if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
7440 image_pixel_convert_PLTE(that);
7441# endif
Chris Craikb50c2172013-07-29 15:28:30 -07007442
7443 /* Image now has RGB channels... */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307444# if DIGITIZE
Chris Craikb50c2172013-07-29 15:28:30 -07007445 {
Matt Sarett9ea75692016-01-08 13:00:42 -05007446 const png_modifier *pm = display->pm;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307447 const unsigned int sample_depth = that->sample_depth;
7448 const unsigned int calc_depth = (pm->assume_16_bit_calculations ? 16 :
7449 sample_depth);
Matt Sarett9ea75692016-01-08 13:00:42 -05007450 const unsigned int gamma_depth =
7451 (sample_depth == 16 ?
7452 display->max_gamma_8 :
7453 (pm->assume_16_bit_calculations ?
7454 display->max_gamma_8 :
7455 sample_depth));
Chris Craikb50c2172013-07-29 15:28:30 -07007456 int isgray;
7457 double r, g, b;
7458 double rlo, rhi, glo, ghi, blo, bhi, graylo, grayhi;
7459
7460 /* Do this using interval arithmetic, otherwise it is too difficult to
7461 * handle the errors correctly.
7462 *
7463 * To handle the gamma correction work out the upper and lower bounds
7464 * of the digitized value. Assume rounding here - normally the values
7465 * will be identical after this operation if there is only one
7466 * transform, feel free to delete the png_error checks on this below in
7467 * the future (this is just me trying to ensure it works!)
Matt Sarett9ea75692016-01-08 13:00:42 -05007468 *
7469 * Interval arithmetic is exact, but to implement it it must be
7470 * possible to control the floating point implementation rounding mode.
7471 * This cannot be done in ANSI-C, so instead I reduce the 'lo' values
7472 * by DBL_EPSILON and increase the 'hi' values by the same.
Chris Craikb50c2172013-07-29 15:28:30 -07007473 */
Matt Sarett9ea75692016-01-08 13:00:42 -05007474# define DD(v,d,r) (digitize(v*(1-DBL_EPSILON), d, r) * (1-DBL_EPSILON))
7475# define DU(v,d,r) (digitize(v*(1+DBL_EPSILON), d, r) * (1+DBL_EPSILON))
7476
Chris Craikb50c2172013-07-29 15:28:30 -07007477 r = rlo = rhi = that->redf;
7478 rlo -= that->rede;
Matt Sarett9ea75692016-01-08 13:00:42 -05007479 rlo = DD(rlo, calc_depth, 1/*round*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007480 rhi += that->rede;
Matt Sarett9ea75692016-01-08 13:00:42 -05007481 rhi = DU(rhi, calc_depth, 1/*round*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007482
7483 g = glo = ghi = that->greenf;
7484 glo -= that->greene;
Matt Sarett9ea75692016-01-08 13:00:42 -05007485 glo = DD(glo, calc_depth, 1/*round*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007486 ghi += that->greene;
Matt Sarett9ea75692016-01-08 13:00:42 -05007487 ghi = DU(ghi, calc_depth, 1/*round*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007488
7489 b = blo = bhi = that->bluef;
7490 blo -= that->bluee;
Matt Sarett9ea75692016-01-08 13:00:42 -05007491 blo = DD(blo, calc_depth, 1/*round*/);
7492 bhi += that->bluee;
7493 bhi = DU(bhi, calc_depth, 1/*round*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007494
7495 isgray = r==g && g==b;
7496
7497 if (data.gamma != 1)
7498 {
Matt Sarett9ea75692016-01-08 13:00:42 -05007499 const double power = 1/data.gamma;
7500 const double abse = .5/(sample_depth == 16 ? 65535 : 255);
Chris Craikb50c2172013-07-29 15:28:30 -07007501
Matt Sarett9ea75692016-01-08 13:00:42 -05007502 /* If a gamma calculation is done it is done using lookup tables of
7503 * precision gamma_depth, so the already digitized value above may
7504 * need to be further digitized here.
Chris Craikb50c2172013-07-29 15:28:30 -07007505 */
Matt Sarett9ea75692016-01-08 13:00:42 -05007506 if (gamma_depth != calc_depth)
7507 {
7508 rlo = DD(rlo, gamma_depth, 0/*truncate*/);
7509 rhi = DU(rhi, gamma_depth, 0/*truncate*/);
7510 glo = DD(glo, gamma_depth, 0/*truncate*/);
7511 ghi = DU(ghi, gamma_depth, 0/*truncate*/);
7512 blo = DD(blo, gamma_depth, 0/*truncate*/);
7513 bhi = DU(bhi, gamma_depth, 0/*truncate*/);
7514 }
7515
7516 /* 'abse' is the error in the gamma table calculation itself. */
Chris Craikb50c2172013-07-29 15:28:30 -07007517 r = pow(r, power);
Matt Sarett9ea75692016-01-08 13:00:42 -05007518 rlo = DD(pow(rlo, power)-abse, calc_depth, 1);
7519 rhi = DU(pow(rhi, power)+abse, calc_depth, 1);
Chris Craikb50c2172013-07-29 15:28:30 -07007520
7521 g = pow(g, power);
Matt Sarett9ea75692016-01-08 13:00:42 -05007522 glo = DD(pow(glo, power)-abse, calc_depth, 1);
7523 ghi = DU(pow(ghi, power)+abse, calc_depth, 1);
Chris Craikb50c2172013-07-29 15:28:30 -07007524
7525 b = pow(b, power);
Matt Sarett9ea75692016-01-08 13:00:42 -05007526 blo = DD(pow(blo, power)-abse, calc_depth, 1);
7527 bhi = DU(pow(bhi, power)+abse, calc_depth, 1);
Chris Craikb50c2172013-07-29 15:28:30 -07007528 }
7529
7530 /* Now calculate the actual gray values. Although the error in the
7531 * coefficients depends on whether they were specified on the command
7532 * line (in which case truncation to 15 bits happened) or not (rounding
7533 * was used) the maxium error in an individual coefficient is always
Matt Sarett9ea75692016-01-08 13:00:42 -05007534 * 2/32768, because even in the rounding case the requirement that
Chris Craikb50c2172013-07-29 15:28:30 -07007535 * coefficients add up to 32768 can cause a larger rounding error.
7536 *
7537 * The only time when rounding doesn't occur in 1.5.5 and later is when
7538 * the non-gamma code path is used for less than 16 bit data.
7539 */
7540 gray = r * data.red_coefficient + g * data.green_coefficient +
7541 b * data.blue_coefficient;
7542
7543 {
Matt Sarett9ea75692016-01-08 13:00:42 -05007544 const int do_round = data.gamma != 1 || calc_depth == 16;
7545 const double ce = 2. / 32768;
Chris Craikb50c2172013-07-29 15:28:30 -07007546
Matt Sarett9ea75692016-01-08 13:00:42 -05007547 graylo = DD(rlo * (data.red_coefficient-ce) +
Chris Craikb50c2172013-07-29 15:28:30 -07007548 glo * (data.green_coefficient-ce) +
Matt Sarett9ea75692016-01-08 13:00:42 -05007549 blo * (data.blue_coefficient-ce), calc_depth, do_round);
7550 if (graylo > gray) /* always accept the right answer */
7551 graylo = gray;
Chris Craikb50c2172013-07-29 15:28:30 -07007552
Matt Sarett9ea75692016-01-08 13:00:42 -05007553 grayhi = DU(rhi * (data.red_coefficient+ce) +
Chris Craikb50c2172013-07-29 15:28:30 -07007554 ghi * (data.green_coefficient+ce) +
Matt Sarett9ea75692016-01-08 13:00:42 -05007555 bhi * (data.blue_coefficient+ce), calc_depth, do_round);
7556 if (grayhi < gray)
7557 grayhi = gray;
Chris Craikb50c2172013-07-29 15:28:30 -07007558 }
7559
7560 /* And invert the gamma. */
7561 if (data.gamma != 1)
7562 {
Matt Sarett9ea75692016-01-08 13:00:42 -05007563 const double power = data.gamma;
7564
7565 /* And this happens yet again, shifting the values once more. */
7566 if (gamma_depth != sample_depth)
7567 {
7568 rlo = DD(rlo, gamma_depth, 0/*truncate*/);
7569 rhi = DU(rhi, gamma_depth, 0/*truncate*/);
7570 glo = DD(glo, gamma_depth, 0/*truncate*/);
7571 ghi = DU(ghi, gamma_depth, 0/*truncate*/);
7572 blo = DD(blo, gamma_depth, 0/*truncate*/);
7573 bhi = DU(bhi, gamma_depth, 0/*truncate*/);
7574 }
Chris Craikb50c2172013-07-29 15:28:30 -07007575
7576 gray = pow(gray, power);
Matt Sarett9ea75692016-01-08 13:00:42 -05007577 graylo = DD(pow(graylo, power), sample_depth, 1);
7578 grayhi = DU(pow(grayhi, power), sample_depth, 1);
Chris Craikb50c2172013-07-29 15:28:30 -07007579 }
7580
Matt Sarett9ea75692016-01-08 13:00:42 -05007581# undef DD
7582# undef DU
7583
Chris Craikb50c2172013-07-29 15:28:30 -07007584 /* Now the error can be calculated.
7585 *
7586 * If r==g==b because there is no overall gamma correction libpng
7587 * currently preserves the original value.
7588 */
7589 if (isgray)
7590 err = (that->rede + that->greene + that->bluee)/3;
7591
7592 else
7593 {
7594 err = fabs(grayhi-gray);
7595 if (fabs(gray - graylo) > err)
7596 err = fabs(graylo-gray);
7597
7598 /* Check that this worked: */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307599 if (err > pm->limit)
Chris Craikb50c2172013-07-29 15:28:30 -07007600 {
7601 size_t pos = 0;
7602 char buffer[128];
7603
7604 pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
7605 pos = safecatd(buffer, sizeof buffer, pos, err, 6);
7606 pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307607 pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
Chris Craikb50c2172013-07-29 15:28:30 -07007608 png_error(pp, buffer);
7609 }
7610 }
7611 }
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307612# else /* DIGITIZE */
7613 {
7614 double r = that->redf;
7615 double re = that->rede;
7616 double g = that->greenf;
7617 double ge = that->greene;
7618 double b = that->bluef;
7619 double be = that->bluee;
7620
Matt Sarett9ea75692016-01-08 13:00:42 -05007621# if PNG_LIBPNG_VER < 10700
7622 /* The true gray case involves no math in earlier versions (not
7623 * true, there was some if gamma correction was happening too.)
7624 */
7625 if (r == g && r == b)
7626 {
7627 gray = r;
7628 err = re;
7629 if (err < ge) err = ge;
7630 if (err < be) err = be;
7631 }
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307632
Matt Sarett9ea75692016-01-08 13:00:42 -05007633 else
7634# endif /* before 1.7 */
7635 if (data.gamma == 1)
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307636 {
7637 /* There is no need to do the conversions to and from linear space,
7638 * so the calculation should be a lot more accurate. There is a
Matt Sarett9ea75692016-01-08 13:00:42 -05007639 * built in error in the coefficients because they only have 15 bits
7640 * and are adjusted to make sure they add up to 32768. This
7641 * involves a integer calculation with truncation of the form:
7642 *
7643 * ((int)(coefficient * 100000) * 32768)/100000
7644 *
7645 * This is done to the red and green coefficients (the ones
7646 * provided to the API) then blue is calculated from them so the
7647 * result adds up to 32768. In the worst case this can result in
7648 * a -1 error in red and green and a +2 error in blue. Consequently
7649 * the worst case in the calculation below is 2/32768 error.
7650 *
7651 * TODO: consider fixing this in libpng by rounding the calculation
7652 * limiting the error to 1/32768.
7653 *
7654 * Handling this by adding 2/32768 here avoids needing to increase
7655 * the global error limits to take this into account.)
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307656 */
7657 gray = r * data.red_coefficient + g * data.green_coefficient +
7658 b * data.blue_coefficient;
7659 err = re * data.red_coefficient + ge * data.green_coefficient +
Matt Sarett9ea75692016-01-08 13:00:42 -05007660 be * data.blue_coefficient + 2./32768 + gray * 5 * DBL_EPSILON;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307661 }
7662
7663 else
7664 {
7665 /* The calculation happens in linear space, and this produces much
7666 * wider errors in the encoded space. These are handled here by
7667 * factoring the errors in to the calculation. There are two table
7668 * lookups in the calculation and each introduces a quantization
7669 * error defined by the table size.
7670 */
Matt Sarett9ea75692016-01-08 13:00:42 -05007671 const png_modifier *pm = display->pm;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307672 double in_qe = (that->sample_depth > 8 ? .5/65535 : .5/255);
7673 double out_qe = (that->sample_depth > 8 ? .5/65535 :
Matt Sarett9ea75692016-01-08 13:00:42 -05007674 (pm->assume_16_bit_calculations ? .5/(1<<display->max_gamma_8) :
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307675 .5/255));
7676 double rhi, ghi, bhi, grayhi;
7677 double g1 = 1/data.gamma;
7678
7679 rhi = r + re + in_qe; if (rhi > 1) rhi = 1;
7680 r -= re + in_qe; if (r < 0) r = 0;
7681 ghi = g + ge + in_qe; if (ghi > 1) ghi = 1;
7682 g -= ge + in_qe; if (g < 0) g = 0;
7683 bhi = b + be + in_qe; if (bhi > 1) bhi = 1;
7684 b -= be + in_qe; if (b < 0) b = 0;
7685
7686 r = pow(r, g1)*(1-DBL_EPSILON); rhi = pow(rhi, g1)*(1+DBL_EPSILON);
7687 g = pow(g, g1)*(1-DBL_EPSILON); ghi = pow(ghi, g1)*(1+DBL_EPSILON);
7688 b = pow(b, g1)*(1-DBL_EPSILON); bhi = pow(bhi, g1)*(1+DBL_EPSILON);
7689
7690 /* Work out the lower and upper bounds for the gray value in the
7691 * encoded space, then work out an average and error. Remove the
7692 * previously added input quantization error at this point.
7693 */
7694 gray = r * data.red_coefficient + g * data.green_coefficient +
Matt Sarett9ea75692016-01-08 13:00:42 -05007695 b * data.blue_coefficient - 2./32768 - out_qe;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307696 if (gray <= 0)
7697 gray = 0;
7698 else
7699 {
7700 gray *= (1 - 6 * DBL_EPSILON);
7701 gray = pow(gray, data.gamma) * (1-DBL_EPSILON);
7702 }
7703
7704 grayhi = rhi * data.red_coefficient + ghi * data.green_coefficient +
Matt Sarett9ea75692016-01-08 13:00:42 -05007705 bhi * data.blue_coefficient + 2./32768 + out_qe;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307706 grayhi *= (1 + 6 * DBL_EPSILON);
7707 if (grayhi >= 1)
7708 grayhi = 1;
7709 else
7710 grayhi = pow(grayhi, data.gamma) * (1+DBL_EPSILON);
7711
7712 err = (grayhi - gray) / 2;
7713 gray = (grayhi + gray) / 2;
7714
7715 if (err <= in_qe)
7716 err = gray * DBL_EPSILON;
7717
7718 else
7719 err -= in_qe;
7720
7721 /* Validate that the error is within limits (this has caused
7722 * problems before, it's much easier to detect them here.)
7723 */
7724 if (err > pm->limit)
7725 {
7726 size_t pos = 0;
7727 char buffer[128];
7728
7729 pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
7730 pos = safecatd(buffer, sizeof buffer, pos, err, 6);
7731 pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
7732 pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
7733 png_error(pp, buffer);
7734 }
7735 }
7736 }
7737# endif /* !DIGITIZE */
Chris Craikb50c2172013-07-29 15:28:30 -07007738
7739 that->bluef = that->greenf = that->redf = gray;
7740 that->bluee = that->greene = that->rede = err;
7741
7742 /* The sBIT is the minium of the three colour channel sBITs. */
7743 if (that->red_sBIT > that->green_sBIT)
7744 that->red_sBIT = that->green_sBIT;
7745 if (that->red_sBIT > that->blue_sBIT)
7746 that->red_sBIT = that->blue_sBIT;
7747 that->blue_sBIT = that->green_sBIT = that->red_sBIT;
7748
7749 /* And remove the colour bit in the type: */
7750 if (that->colour_type == PNG_COLOR_TYPE_RGB)
7751 that->colour_type = PNG_COLOR_TYPE_GRAY;
7752 else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
7753 that->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
7754 }
7755
7756 this->next->mod(this->next, that, pp, display);
7757}
7758
7759static int
7760image_transform_png_set_rgb_to_gray_add(image_transform *this,
Matt Sarett9ea75692016-01-08 13:00:42 -05007761 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07007762{
7763 UNUSED(bit_depth)
7764
7765 this->next = *that;
7766 *that = this;
7767
7768 return (colour_type & PNG_COLOR_MASK_COLOR) != 0;
7769}
7770
7771#undef data
7772IT(rgb_to_gray);
7773#undef PT
7774#define PT ITSTRUCT(rgb_to_gray)
7775#undef image_transform_ini
7776#define image_transform_ini image_transform_default_ini
7777#endif /* PNG_READ_RGB_TO_GRAY_SUPPORTED */
7778
7779#ifdef PNG_READ_BACKGROUND_SUPPORTED
7780/* png_set_background(png_structp, png_const_color_16p background_color,
7781 * int background_gamma_code, int need_expand, double background_gamma)
7782 * png_set_background_fixed(png_structp, png_const_color_16p background_color,
7783 * int background_gamma_code, int need_expand,
7784 * png_fixed_point background_gamma)
7785 *
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307786 * This ignores the gamma (at present.)
Chris Craikb50c2172013-07-29 15:28:30 -07007787*/
7788#define data ITDATA(background)
7789static image_pixel data;
7790
7791static void
Matt Sarett9ea75692016-01-08 13:00:42 -05007792image_transform_png_set_background_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007793 transform_display *that, png_structp pp, png_infop pi)
7794{
7795 png_byte colour_type, bit_depth;
7796 png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307797 int expand;
Chris Craikb50c2172013-07-29 15:28:30 -07007798 png_color_16 back;
7799
7800 /* We need a background colour, because we don't know exactly what transforms
7801 * have been set we have to supply the colour in the original file format and
7802 * so we need to know what that is! The background colour is stored in the
7803 * transform_display.
7804 */
7805 RANDOMIZE(random_bytes);
7806
7807 /* Read the random value, for colour type 3 the background colour is actually
7808 * expressed as a 24bit rgb, not an index.
7809 */
7810 colour_type = that->this.colour_type;
7811 if (colour_type == 3)
7812 {
7813 colour_type = PNG_COLOR_TYPE_RGB;
7814 bit_depth = 8;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307815 expand = 0; /* passing in an RGB not a pixel index */
Chris Craikb50c2172013-07-29 15:28:30 -07007816 }
7817
7818 else
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307819 {
Matt Sarett9ea75692016-01-08 13:00:42 -05007820 if (that->this.has_tRNS)
7821 that->this.is_transparent = 1;
7822
Chris Craikb50c2172013-07-29 15:28:30 -07007823 bit_depth = that->this.bit_depth;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307824 expand = 1;
7825 }
Chris Craikb50c2172013-07-29 15:28:30 -07007826
7827 image_pixel_init(&data, random_bytes, colour_type,
Matt Sarett9ea75692016-01-08 13:00:42 -05007828 bit_depth, 0/*x*/, 0/*unused: palette*/, NULL/*format*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007829
7830 /* Extract the background colour from this image_pixel, but make sure the
7831 * unused fields of 'back' are garbage.
7832 */
7833 RANDOMIZE(back);
7834
7835 if (colour_type & PNG_COLOR_MASK_COLOR)
7836 {
7837 back.red = (png_uint_16)data.red;
7838 back.green = (png_uint_16)data.green;
7839 back.blue = (png_uint_16)data.blue;
7840 }
7841
7842 else
7843 back.gray = (png_uint_16)data.red;
7844
7845# ifdef PNG_FLOATING_POINT_SUPPORTED
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307846 png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
Chris Craikb50c2172013-07-29 15:28:30 -07007847# else
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307848 png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
Chris Craikb50c2172013-07-29 15:28:30 -07007849# endif
7850
7851 this->next->set(this->next, that, pp, pi);
7852}
7853
7854static void
Matt Sarett9ea75692016-01-08 13:00:42 -05007855image_transform_png_set_background_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007856 image_pixel *that, png_const_structp pp,
Matt Sarett9ea75692016-01-08 13:00:42 -05007857 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07007858{
7859 /* Check for tRNS first: */
7860 if (that->have_tRNS && that->colour_type != PNG_COLOR_TYPE_PALETTE)
Matt Sarett9ea75692016-01-08 13:00:42 -05007861 image_pixel_add_alpha(that, &display->this, 1/*for background*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007862
7863 /* This is only necessary if the alpha value is less than 1. */
7864 if (that->alphaf < 1)
7865 {
7866 /* Now we do the background calculation without any gamma correction. */
7867 if (that->alphaf <= 0)
7868 {
7869 that->redf = data.redf;
7870 that->greenf = data.greenf;
7871 that->bluef = data.bluef;
7872
7873 that->rede = data.rede;
7874 that->greene = data.greene;
7875 that->bluee = data.bluee;
7876
7877 that->red_sBIT= data.red_sBIT;
7878 that->green_sBIT= data.green_sBIT;
7879 that->blue_sBIT= data.blue_sBIT;
7880 }
7881
7882 else /* 0 < alpha < 1 */
7883 {
7884 double alf = 1 - that->alphaf;
7885
7886 that->redf = that->redf * that->alphaf + data.redf * alf;
7887 that->rede = that->rede * that->alphaf + data.rede * alf +
7888 DBL_EPSILON;
7889 that->greenf = that->greenf * that->alphaf + data.greenf * alf;
7890 that->greene = that->greene * that->alphaf + data.greene * alf +
7891 DBL_EPSILON;
7892 that->bluef = that->bluef * that->alphaf + data.bluef * alf;
7893 that->bluee = that->bluee * that->alphaf + data.bluee * alf +
7894 DBL_EPSILON;
7895 }
7896
7897 /* Remove the alpha type and set the alpha (not in that order.) */
7898 that->alphaf = 1;
7899 that->alphae = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07007900 }
7901
Matt Sarett9ea75692016-01-08 13:00:42 -05007902 if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
7903 that->colour_type = PNG_COLOR_TYPE_RGB;
7904 else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
7905 that->colour_type = PNG_COLOR_TYPE_GRAY;
7906 /* PNG_COLOR_TYPE_PALETTE is not changed */
7907
Chris Craikb50c2172013-07-29 15:28:30 -07007908 this->next->mod(this->next, that, pp, display);
7909}
7910
7911#define image_transform_png_set_background_add image_transform_default_add
7912
7913#undef data
7914IT(background);
7915#undef PT
7916#define PT ITSTRUCT(background)
7917#endif /* PNG_READ_BACKGROUND_SUPPORTED */
7918
Matt Sarett9ea75692016-01-08 13:00:42 -05007919/* png_set_quantize(png_structp, png_colorp palette, int num_palette,
7920 * int maximum_colors, png_const_uint_16p histogram, int full_quantize)
7921 *
7922 * Very difficult to validate this!
7923 */
7924/*NOTE: TBD NYI */
7925
7926/* The data layout transforms are handled by swapping our own channel data,
7927 * necessarily these need to happen at the end of the transform list because the
7928 * semantic of the channels changes after these are executed. Some of these,
7929 * like set_shift and set_packing, can't be done at present because they change
7930 * the layout of the data at the sub-sample level so sample() won't get the
7931 * right answer.
7932 */
7933/* png_set_invert_alpha */
7934#ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
7935/* Invert the alpha channel
7936 *
7937 * png_set_invert_alpha(png_structrp png_ptr)
7938 */
7939static void
7940image_transform_png_set_invert_alpha_set(const image_transform *this,
7941 transform_display *that, png_structp pp, png_infop pi)
7942{
7943 png_set_invert_alpha(pp);
7944 this->next->set(this->next, that, pp, pi);
7945}
Chris Craikb50c2172013-07-29 15:28:30 -07007946
7947static void
Matt Sarett9ea75692016-01-08 13:00:42 -05007948image_transform_png_set_invert_alpha_mod(const image_transform *this,
7949 image_pixel *that, png_const_structp pp,
7950 const transform_display *display)
7951{
7952 if (that->colour_type & 4)
7953 that->alpha_inverted = 1;
7954
7955 this->next->mod(this->next, that, pp, display);
7956}
7957
7958static int
7959image_transform_png_set_invert_alpha_add(image_transform *this,
7960 const image_transform **that, png_byte colour_type, png_byte bit_depth)
7961{
7962 UNUSED(bit_depth)
7963
7964 this->next = *that;
7965 *that = this;
7966
7967 /* Only has an effect on pixels with alpha: */
7968 return (colour_type & 4) != 0;
7969}
7970
7971IT(invert_alpha);
7972#undef PT
7973#define PT ITSTRUCT(invert_alpha)
7974
7975#endif /* PNG_READ_INVERT_ALPHA_SUPPORTED */
7976
7977/* png_set_bgr */
7978#ifdef PNG_READ_BGR_SUPPORTED
7979/* Swap R,G,B channels to order B,G,R.
7980 *
7981 * png_set_bgr(png_structrp png_ptr)
7982 *
7983 * This only has an effect on RGB and RGBA pixels.
7984 */
7985static void
7986image_transform_png_set_bgr_set(const image_transform *this,
7987 transform_display *that, png_structp pp, png_infop pi)
7988{
7989 png_set_bgr(pp);
7990 this->next->set(this->next, that, pp, pi);
7991}
7992
7993static void
7994image_transform_png_set_bgr_mod(const image_transform *this,
7995 image_pixel *that, png_const_structp pp,
7996 const transform_display *display)
7997{
7998 if (that->colour_type == PNG_COLOR_TYPE_RGB ||
7999 that->colour_type == PNG_COLOR_TYPE_RGBA)
8000 that->swap_rgb = 1;
8001
8002 this->next->mod(this->next, that, pp, display);
8003}
8004
8005static int
8006image_transform_png_set_bgr_add(image_transform *this,
8007 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8008{
8009 UNUSED(bit_depth)
8010
8011 this->next = *that;
8012 *that = this;
8013
8014 return colour_type == PNG_COLOR_TYPE_RGB ||
8015 colour_type == PNG_COLOR_TYPE_RGBA;
8016}
8017
8018IT(bgr);
8019#undef PT
8020#define PT ITSTRUCT(bgr)
8021
8022#endif /* PNG_READ_BGR_SUPPORTED */
8023
8024/* png_set_swap_alpha */
8025#ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
8026/* Put the alpha channel first.
8027 *
8028 * png_set_swap_alpha(png_structrp png_ptr)
8029 *
8030 * This only has an effect on GA and RGBA pixels.
8031 */
8032static void
8033image_transform_png_set_swap_alpha_set(const image_transform *this,
8034 transform_display *that, png_structp pp, png_infop pi)
8035{
8036 png_set_swap_alpha(pp);
8037 this->next->set(this->next, that, pp, pi);
8038}
8039
8040static void
8041image_transform_png_set_swap_alpha_mod(const image_transform *this,
8042 image_pixel *that, png_const_structp pp,
8043 const transform_display *display)
8044{
8045 if (that->colour_type == PNG_COLOR_TYPE_GA ||
8046 that->colour_type == PNG_COLOR_TYPE_RGBA)
8047 that->alpha_first = 1;
8048
8049 this->next->mod(this->next, that, pp, display);
8050}
8051
8052static int
8053image_transform_png_set_swap_alpha_add(image_transform *this,
8054 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8055{
8056 UNUSED(bit_depth)
8057
8058 this->next = *that;
8059 *that = this;
8060
8061 return colour_type == PNG_COLOR_TYPE_GA ||
8062 colour_type == PNG_COLOR_TYPE_RGBA;
8063}
8064
8065IT(swap_alpha);
8066#undef PT
8067#define PT ITSTRUCT(swap_alpha)
8068
8069#endif /* PNG_READ_SWAP_ALPHA_SUPPORTED */
8070
8071/* png_set_swap */
8072#ifdef PNG_READ_SWAP_SUPPORTED
8073/* Byte swap 16-bit components.
8074 *
8075 * png_set_swap(png_structrp png_ptr)
8076 */
8077static void
8078image_transform_png_set_swap_set(const image_transform *this,
8079 transform_display *that, png_structp pp, png_infop pi)
8080{
8081 png_set_swap(pp);
8082 this->next->set(this->next, that, pp, pi);
8083}
8084
8085static void
8086image_transform_png_set_swap_mod(const image_transform *this,
8087 image_pixel *that, png_const_structp pp,
8088 const transform_display *display)
8089{
8090 if (that->bit_depth == 16)
8091 that->swap16 = 1;
8092
8093 this->next->mod(this->next, that, pp, display);
8094}
8095
8096static int
8097image_transform_png_set_swap_add(image_transform *this,
8098 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8099{
8100 UNUSED(colour_type)
8101
8102 this->next = *that;
8103 *that = this;
8104
8105 return bit_depth == 16;
8106}
8107
8108IT(swap);
8109#undef PT
8110#define PT ITSTRUCT(swap)
8111
8112#endif /* PNG_READ_SWAP_SUPPORTED */
8113
8114#ifdef PNG_READ_FILLER_SUPPORTED
8115/* Add a filler byte to 8-bit Gray or 24-bit RGB images.
8116 *
8117 * png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags));
8118 *
8119 * Flags:
8120 *
8121 * PNG_FILLER_BEFORE
8122 * PNG_FILLER_AFTER
8123 */
8124#define data ITDATA(filler)
8125static struct
8126{
8127 png_uint_32 filler;
8128 int flags;
8129} data;
8130
8131static void
8132image_transform_png_set_filler_set(const image_transform *this,
8133 transform_display *that, png_structp pp, png_infop pi)
8134{
8135 /* Need a random choice for 'before' and 'after' as well as for the
8136 * filler. The 'filler' value has all 32 bits set, but only bit_depth
8137 * will be used. At this point we don't know bit_depth.
8138 */
8139 RANDOMIZE(data.filler);
8140 data.flags = random_choice();
8141
8142 png_set_filler(pp, data.filler, data.flags);
8143
8144 /* The standard display handling stuff also needs to know that
8145 * there is a filler, so set that here.
8146 */
8147 that->this.filler = 1;
8148
8149 this->next->set(this->next, that, pp, pi);
8150}
8151
8152static void
8153image_transform_png_set_filler_mod(const image_transform *this,
8154 image_pixel *that, png_const_structp pp,
8155 const transform_display *display)
8156{
8157 if (that->bit_depth >= 8 &&
8158 (that->colour_type == PNG_COLOR_TYPE_RGB ||
8159 that->colour_type == PNG_COLOR_TYPE_GRAY))
8160 {
8161 const unsigned int max = (1U << that->bit_depth)-1;
8162 that->alpha = data.filler & max;
8163 that->alphaf = ((double)that->alpha) / max;
8164 that->alphae = 0;
8165
8166 /* The filler has been stored in the alpha channel, we must record
8167 * that this has been done for the checking later on, the color
8168 * type is faked to have an alpha channel, but libpng won't report
8169 * this; the app has to know the extra channel is there and this
8170 * was recording in standard_display::filler above.
8171 */
8172 that->colour_type |= 4; /* alpha added */
8173 that->alpha_first = data.flags == PNG_FILLER_BEFORE;
8174 }
8175
8176 this->next->mod(this->next, that, pp, display);
8177}
8178
8179static int
8180image_transform_png_set_filler_add(image_transform *this,
8181 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8182{
8183 this->next = *that;
8184 *that = this;
8185
8186 return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
8187 colour_type == PNG_COLOR_TYPE_GRAY);
8188}
8189
8190#undef data
8191IT(filler);
8192#undef PT
8193#define PT ITSTRUCT(filler)
8194
8195/* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */
8196/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
8197#define data ITDATA(add_alpha)
8198static struct
8199{
8200 png_uint_32 filler;
8201 int flags;
8202} data;
8203
8204static void
8205image_transform_png_set_add_alpha_set(const image_transform *this,
8206 transform_display *that, png_structp pp, png_infop pi)
8207{
8208 /* Need a random choice for 'before' and 'after' as well as for the
8209 * filler. The 'filler' value has all 32 bits set, but only bit_depth
8210 * will be used. At this point we don't know bit_depth.
8211 */
8212 RANDOMIZE(data.filler);
8213 data.flags = random_choice();
8214
8215 png_set_add_alpha(pp, data.filler, data.flags);
8216 this->next->set(this->next, that, pp, pi);
8217}
8218
8219static void
8220image_transform_png_set_add_alpha_mod(const image_transform *this,
8221 image_pixel *that, png_const_structp pp,
8222 const transform_display *display)
8223{
8224 if (that->bit_depth >= 8 &&
8225 (that->colour_type == PNG_COLOR_TYPE_RGB ||
8226 that->colour_type == PNG_COLOR_TYPE_GRAY))
8227 {
8228 const unsigned int max = (1U << that->bit_depth)-1;
8229 that->alpha = data.filler & max;
8230 that->alphaf = ((double)that->alpha) / max;
8231 that->alphae = 0;
8232
8233 that->colour_type |= 4; /* alpha added */
8234 that->alpha_first = data.flags == PNG_FILLER_BEFORE;
8235 }
8236
8237 this->next->mod(this->next, that, pp, display);
8238}
8239
8240static int
8241image_transform_png_set_add_alpha_add(image_transform *this,
8242 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8243{
8244 this->next = *that;
8245 *that = this;
8246
8247 return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
8248 colour_type == PNG_COLOR_TYPE_GRAY);
8249}
8250
8251#undef data
8252IT(add_alpha);
8253#undef PT
8254#define PT ITSTRUCT(add_alpha)
8255
8256#endif /* PNG_READ_FILLER_SUPPORTED */
8257
8258/* png_set_packing */
8259#ifdef PNG_READ_PACK_SUPPORTED
8260/* Use 1 byte per pixel in 1, 2, or 4-bit depth files.
8261 *
8262 * png_set_packing(png_structrp png_ptr)
8263 *
8264 * This should only affect grayscale and palette images with less than 8 bits
8265 * per pixel.
8266 */
8267static void
8268image_transform_png_set_packing_set(const image_transform *this,
8269 transform_display *that, png_structp pp, png_infop pi)
8270{
8271 png_set_packing(pp);
8272 that->unpacked = 1;
8273 this->next->set(this->next, that, pp, pi);
8274}
8275
8276static void
8277image_transform_png_set_packing_mod(const image_transform *this,
8278 image_pixel *that, png_const_structp pp,
8279 const transform_display *display)
8280{
8281 /* The general expand case depends on what the colour type is,
8282 * low bit-depth pixel values are unpacked into bytes without
8283 * scaling, so sample_depth is not changed.
8284 */
8285 if (that->bit_depth < 8) /* grayscale or palette */
8286 that->bit_depth = 8;
8287
8288 this->next->mod(this->next, that, pp, display);
8289}
8290
8291static int
8292image_transform_png_set_packing_add(image_transform *this,
8293 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8294{
8295 UNUSED(colour_type)
8296
8297 this->next = *that;
8298 *that = this;
8299
8300 /* Nothing should happen unless the bit depth is less than 8: */
8301 return bit_depth < 8;
8302}
8303
8304IT(packing);
8305#undef PT
8306#define PT ITSTRUCT(packing)
8307
8308#endif /* PNG_READ_PACK_SUPPORTED */
8309
8310/* png_set_packswap */
8311#ifdef PNG_READ_PACKSWAP_SUPPORTED
8312/* Swap pixels packed into bytes; reverses the order on screen so that
8313 * the high order bits correspond to the rightmost pixels.
8314 *
8315 * png_set_packswap(png_structrp png_ptr)
8316 */
8317static void
8318image_transform_png_set_packswap_set(const image_transform *this,
8319 transform_display *that, png_structp pp, png_infop pi)
8320{
8321 png_set_packswap(pp);
8322 that->this.littleendian = 1;
8323 this->next->set(this->next, that, pp, pi);
8324}
8325
8326static void
8327image_transform_png_set_packswap_mod(const image_transform *this,
8328 image_pixel *that, png_const_structp pp,
8329 const transform_display *display)
8330{
8331 if (that->bit_depth < 8)
8332 that->littleendian = 1;
8333
8334 this->next->mod(this->next, that, pp, display);
8335}
8336
8337static int
8338image_transform_png_set_packswap_add(image_transform *this,
8339 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8340{
8341 UNUSED(colour_type)
8342
8343 this->next = *that;
8344 *that = this;
8345
8346 return bit_depth < 8;
8347}
8348
8349IT(packswap);
8350#undef PT
8351#define PT ITSTRUCT(packswap)
8352
8353#endif /* PNG_READ_PACKSWAP_SUPPORTED */
8354
8355
8356/* png_set_invert_mono */
8357#ifdef PNG_READ_INVERT_MONO_SUPPORTED
8358/* Invert the gray channel
8359 *
8360 * png_set_invert_mono(png_structrp png_ptr)
8361 */
8362static void
8363image_transform_png_set_invert_mono_set(const image_transform *this,
8364 transform_display *that, png_structp pp, png_infop pi)
8365{
8366 png_set_invert_mono(pp);
8367 this->next->set(this->next, that, pp, pi);
8368}
8369
8370static void
8371image_transform_png_set_invert_mono_mod(const image_transform *this,
8372 image_pixel *that, png_const_structp pp,
8373 const transform_display *display)
8374{
8375 if (that->colour_type & 4)
8376 that->mono_inverted = 1;
8377
8378 this->next->mod(this->next, that, pp, display);
8379}
8380
8381static int
8382image_transform_png_set_invert_mono_add(image_transform *this,
8383 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8384{
8385 UNUSED(bit_depth)
8386
8387 this->next = *that;
8388 *that = this;
8389
8390 /* Only has an effect on pixels with no colour: */
8391 return (colour_type & 2) == 0;
8392}
8393
8394IT(invert_mono);
8395#undef PT
8396#define PT ITSTRUCT(invert_mono)
8397
8398#endif /* PNG_READ_INVERT_MONO_SUPPORTED */
8399
8400#ifdef PNG_READ_SHIFT_SUPPORTED
8401/* png_set_shift(png_structp, png_const_color_8p true_bits)
8402 *
8403 * The output pixels will be shifted by the given true_bits
8404 * values.
8405 */
8406#define data ITDATA(shift)
8407static png_color_8 data;
8408
8409static void
8410image_transform_png_set_shift_set(const image_transform *this,
8411 transform_display *that, png_structp pp, png_infop pi)
8412{
8413 /* Get a random set of shifts. The shifts need to do something
8414 * to test the transform, so they are limited to the bit depth
8415 * of the input image. Notice that in the following the 'gray'
8416 * field is randomized independently. This acts as a check that
8417 * libpng does use the correct field.
8418 */
8419 const unsigned int depth = that->this.bit_depth;
8420
8421 data.red = (png_byte)/*SAFE*/(random_mod(depth)+1);
8422 data.green = (png_byte)/*SAFE*/(random_mod(depth)+1);
8423 data.blue = (png_byte)/*SAFE*/(random_mod(depth)+1);
8424 data.gray = (png_byte)/*SAFE*/(random_mod(depth)+1);
8425 data.alpha = (png_byte)/*SAFE*/(random_mod(depth)+1);
8426
8427 png_set_shift(pp, &data);
8428 this->next->set(this->next, that, pp, pi);
8429}
8430
8431static void
8432image_transform_png_set_shift_mod(const image_transform *this,
8433 image_pixel *that, png_const_structp pp,
8434 const transform_display *display)
8435{
8436 /* Copy the correct values into the sBIT fields, libpng does not do
8437 * anything to palette data:
8438 */
8439 if (that->colour_type != PNG_COLOR_TYPE_PALETTE)
8440 {
8441 that->sig_bits = 1;
8442
8443 /* The sBIT fields are reset to the values previously sent to
8444 * png_set_shift according to the colour type.
8445 * does.
8446 */
8447 if (that->colour_type & 2) /* RGB channels */
8448 {
8449 that->red_sBIT = data.red;
8450 that->green_sBIT = data.green;
8451 that->blue_sBIT = data.blue;
8452 }
8453
8454 else /* One grey channel */
8455 that->red_sBIT = that->green_sBIT = that->blue_sBIT = data.gray;
8456
8457 that->alpha_sBIT = data.alpha;
8458 }
8459
8460 this->next->mod(this->next, that, pp, display);
8461}
8462
8463static int
8464image_transform_png_set_shift_add(image_transform *this,
8465 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8466{
8467 UNUSED(bit_depth)
8468
8469 this->next = *that;
8470 *that = this;
8471
8472 return colour_type != PNG_COLOR_TYPE_PALETTE;
8473}
8474
8475IT(shift);
8476#undef PT
8477#define PT ITSTRUCT(shift)
8478
8479#endif /* PNG_READ_SHIFT_SUPPORTED */
8480
8481#ifdef THIS_IS_THE_PROFORMA
8482static void
8483image_transform_png_set_@_set(const image_transform *this,
8484 transform_display *that, png_structp pp, png_infop pi)
8485{
8486 png_set_@(pp);
8487 this->next->set(this->next, that, pp, pi);
8488}
8489
8490static void
8491image_transform_png_set_@_mod(const image_transform *this,
8492 image_pixel *that, png_const_structp pp,
8493 const transform_display *display)
8494{
8495 this->next->mod(this->next, that, pp, display);
8496}
8497
8498static int
8499image_transform_png_set_@_add(image_transform *this,
8500 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8501{
8502 this->next = *that;
8503 *that = this;
8504
8505 return 1;
8506}
8507
8508IT(@);
8509#endif
8510
8511
8512/* This may just be 'end' if all the transforms are disabled! */
8513static image_transform *const image_transform_first = &PT;
8514
8515static void
8516transform_enable(const char *name)
Chris Craikb50c2172013-07-29 15:28:30 -07008517{
8518 /* Everything starts out enabled, so if we see an 'enable' disabled
8519 * everything else the first time round.
8520 */
8521 static int all_disabled = 0;
8522 int found_it = 0;
8523 image_transform *list = image_transform_first;
8524
8525 while (list != &image_transform_end)
8526 {
8527 if (strcmp(list->name, name) == 0)
8528 {
8529 list->enable = 1;
8530 found_it = 1;
8531 }
8532 else if (!all_disabled)
8533 list->enable = 0;
8534
8535 list = list->list;
8536 }
8537
8538 all_disabled = 1;
8539
8540 if (!found_it)
8541 {
8542 fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n",
8543 name);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308544 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -07008545 }
8546}
8547
8548static void
Matt Sarett9ea75692016-01-08 13:00:42 -05008549transform_disable(const char *name)
Chris Craikb50c2172013-07-29 15:28:30 -07008550{
8551 image_transform *list = image_transform_first;
8552
8553 while (list != &image_transform_end)
8554 {
8555 if (strcmp(list->name, name) == 0)
8556 {
8557 list->enable = 0;
8558 return;
8559 }
8560
8561 list = list->list;
8562 }
8563
8564 fprintf(stderr, "pngvalid: --transform-disable=%s: unknown transform\n",
8565 name);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308566 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -07008567}
8568
8569static void
8570image_transform_reset_count(void)
8571{
8572 image_transform *next = image_transform_first;
8573 int count = 0;
8574
8575 while (next != &image_transform_end)
8576 {
8577 next->local_use = 0;
8578 next->next = 0;
8579 next = next->list;
8580 ++count;
8581 }
8582
8583 /* This can only happen if we every have more than 32 transforms (excluding
8584 * the end) in the list.
8585 */
8586 if (count > 32) abort();
8587}
8588
8589static int
8590image_transform_test_counter(png_uint_32 counter, unsigned int max)
8591{
8592 /* Test the list to see if there is any point contining, given a current
8593 * counter and a 'max' value.
8594 */
8595 image_transform *next = image_transform_first;
8596
8597 while (next != &image_transform_end)
8598 {
8599 /* For max 0 or 1 continue until the counter overflows: */
8600 counter >>= 1;
8601
8602 /* Continue if any entry hasn't reacked the max. */
8603 if (max > 1 && next->local_use < max)
8604 return 1;
8605 next = next->list;
8606 }
8607
8608 return max <= 1 && counter == 0;
8609}
8610
8611static png_uint_32
Matt Sarett9ea75692016-01-08 13:00:42 -05008612image_transform_add(const image_transform **this, unsigned int max,
Chris Craikb50c2172013-07-29 15:28:30 -07008613 png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos,
8614 png_byte colour_type, png_byte bit_depth)
8615{
8616 for (;;) /* until we manage to add something */
8617 {
8618 png_uint_32 mask;
8619 image_transform *list;
8620
8621 /* Find the next counter value, if the counter is zero this is the start
8622 * of the list. This routine always returns the current counter (not the
8623 * next) so it returns 0 at the end and expects 0 at the beginning.
8624 */
8625 if (counter == 0) /* first time */
8626 {
8627 image_transform_reset_count();
8628 if (max <= 1)
8629 counter = 1;
8630 else
8631 counter = random_32();
8632 }
8633 else /* advance the counter */
8634 {
8635 switch (max)
8636 {
8637 case 0: ++counter; break;
8638 case 1: counter <<= 1; break;
8639 default: counter = random_32(); break;
8640 }
8641 }
8642
8643 /* Now add all these items, if possible */
8644 *this = &image_transform_end;
8645 list = image_transform_first;
8646 mask = 1;
8647
8648 /* Go through the whole list adding anything that the counter selects: */
8649 while (list != &image_transform_end)
8650 {
8651 if ((counter & mask) != 0 && list->enable &&
8652 (max == 0 || list->local_use < max))
8653 {
8654 /* Candidate to add: */
8655 if (list->add(list, this, colour_type, bit_depth) || max == 0)
8656 {
8657 /* Added, so add to the name too. */
8658 *pos = safecat(name, sizeof_name, *pos, " +");
8659 *pos = safecat(name, sizeof_name, *pos, list->name);
8660 }
8661
8662 else
8663 {
8664 /* Not useful and max>0, so remove it from *this: */
8665 *this = list->next;
8666 list->next = 0;
8667
8668 /* And, since we know it isn't useful, stop it being added again
8669 * in this run:
8670 */
8671 list->local_use = max;
8672 }
8673 }
8674
8675 mask <<= 1;
8676 list = list->list;
8677 }
8678
8679 /* Now if anything was added we have something to do. */
8680 if (*this != &image_transform_end)
8681 return counter;
8682
8683 /* Nothing added, but was there anything in there to add? */
8684 if (!image_transform_test_counter(counter, max))
8685 return 0;
8686 }
8687}
8688
Chris Craikb50c2172013-07-29 15:28:30 -07008689static void
8690perform_transform_test(png_modifier *pm)
8691{
8692 png_byte colour_type = 0;
8693 png_byte bit_depth = 0;
8694 unsigned int palette_number = 0;
8695
Matt Sarett9ea75692016-01-08 13:00:42 -05008696 while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg,
8697 pm->test_tRNS))
Chris Craikb50c2172013-07-29 15:28:30 -07008698 {
8699 png_uint_32 counter = 0;
8700 size_t base_pos;
8701 char name[64];
8702
8703 base_pos = safecat(name, sizeof name, 0, "transform:");
8704
8705 for (;;)
8706 {
8707 size_t pos = base_pos;
Matt Sarett9ea75692016-01-08 13:00:42 -05008708 const image_transform *list = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07008709
8710 /* 'max' is currently hardwired to '1'; this should be settable on the
8711 * command line.
8712 */
8713 counter = image_transform_add(&list, 1/*max*/, counter,
8714 name, sizeof name, &pos, colour_type, bit_depth);
8715
8716 if (counter == 0)
8717 break;
8718
8719 /* The command line can change this to checking interlaced images. */
8720 do
8721 {
8722 pm->repeat = 0;
8723 transform_test(pm, FILEID(colour_type, bit_depth, palette_number,
8724 pm->interlace_type, 0, 0, 0), list, name);
8725
8726 if (fail(pm))
8727 return;
8728 }
8729 while (pm->repeat);
8730 }
8731 }
8732}
8733#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
8734
8735/********************************* GAMMA TESTS ********************************/
8736#ifdef PNG_READ_GAMMA_SUPPORTED
8737/* Reader callbacks and implementations, where they differ from the standard
8738 * ones.
8739 */
8740typedef struct gamma_display
8741{
8742 standard_display this;
8743
8744 /* Parameters */
8745 png_modifier* pm;
8746 double file_gamma;
8747 double screen_gamma;
8748 double background_gamma;
8749 png_byte sbit;
8750 int threshold_test;
8751 int use_input_precision;
8752 int scale16;
8753 int expand16;
8754 int do_background;
8755 png_color_16 background_color;
8756
8757 /* Local variables */
8758 double maxerrout;
8759 double maxerrpc;
8760 double maxerrabs;
8761} gamma_display;
8762
8763#define ALPHA_MODE_OFFSET 4
8764
8765static void
8766gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
8767 double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
8768 int use_input_precision, int scale16, int expand16,
Matt Sarett9ea75692016-01-08 13:00:42 -05008769 int do_background, const png_color_16 *pointer_to_the_background_color,
Chris Craikb50c2172013-07-29 15:28:30 -07008770 double background_gamma)
8771{
8772 /* Standard fields */
Matt Sarett9ea75692016-01-08 13:00:42 -05008773 standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
Chris Craikb50c2172013-07-29 15:28:30 -07008774 pm->use_update_info);
8775
8776 /* Parameter fields */
8777 dp->pm = pm;
8778 dp->file_gamma = file_gamma;
8779 dp->screen_gamma = screen_gamma;
8780 dp->background_gamma = background_gamma;
8781 dp->sbit = sbit;
8782 dp->threshold_test = threshold_test;
8783 dp->use_input_precision = use_input_precision;
8784 dp->scale16 = scale16;
8785 dp->expand16 = expand16;
8786 dp->do_background = do_background;
8787 if (do_background && pointer_to_the_background_color != 0)
8788 dp->background_color = *pointer_to_the_background_color;
8789 else
8790 memset(&dp->background_color, 0, sizeof dp->background_color);
8791
8792 /* Local variable fields */
8793 dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
8794}
8795
8796static void
8797gamma_info_imp(gamma_display *dp, png_structp pp, png_infop pi)
8798{
8799 /* Reuse the standard stuff as appropriate. */
8800 standard_info_part1(&dp->this, pp, pi);
8801
8802 /* If requested strip 16 to 8 bits - this is handled automagically below
8803 * because the output bit depth is read from the library. Note that there
8804 * are interactions with sBIT but, internally, libpng makes sbit at most
Matt Sarett9ea75692016-01-08 13:00:42 -05008805 * PNG_MAX_GAMMA_8 prior to 1.7 when doing the following.
Chris Craikb50c2172013-07-29 15:28:30 -07008806 */
8807 if (dp->scale16)
8808# ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
8809 png_set_scale_16(pp);
8810# else
8811 /* The following works both in 1.5.4 and earlier versions: */
8812# ifdef PNG_READ_16_TO_8_SUPPORTED
8813 png_set_strip_16(pp);
8814# else
8815 png_error(pp, "scale16 (16 to 8 bit conversion) not supported");
8816# endif
8817# endif
8818
8819 if (dp->expand16)
8820# ifdef PNG_READ_EXPAND_16_SUPPORTED
8821 png_set_expand_16(pp);
8822# else
8823 png_error(pp, "expand16 (8 to 16 bit conversion) not supported");
8824# endif
8825
8826 if (dp->do_background >= ALPHA_MODE_OFFSET)
8827 {
8828# ifdef PNG_READ_ALPHA_MODE_SUPPORTED
8829 {
8830 /* This tests the alpha mode handling, if supported. */
8831 int mode = dp->do_background - ALPHA_MODE_OFFSET;
8832
8833 /* The gamma value is the output gamma, and is in the standard,
8834 * non-inverted, represenation. It provides a default for the PNG file
8835 * gamma, but since the file has a gAMA chunk this does not matter.
8836 */
Matt Sarett9ea75692016-01-08 13:00:42 -05008837 const double sg = dp->screen_gamma;
Chris Craikb50c2172013-07-29 15:28:30 -07008838# ifndef PNG_FLOATING_POINT_SUPPORTED
Matt Sarett9ea75692016-01-08 13:00:42 -05008839 const png_fixed_point g = fix(sg);
Chris Craikb50c2172013-07-29 15:28:30 -07008840# endif
8841
8842# ifdef PNG_FLOATING_POINT_SUPPORTED
8843 png_set_alpha_mode(pp, mode, sg);
8844# else
8845 png_set_alpha_mode_fixed(pp, mode, g);
8846# endif
8847
8848 /* However, for the standard Porter-Duff algorithm the output defaults
8849 * to be linear, so if the test requires non-linear output it must be
8850 * corrected here.
8851 */
8852 if (mode == PNG_ALPHA_STANDARD && sg != 1)
8853 {
8854# ifdef PNG_FLOATING_POINT_SUPPORTED
8855 png_set_gamma(pp, sg, dp->file_gamma);
8856# else
8857 png_fixed_point f = fix(dp->file_gamma);
8858 png_set_gamma_fixed(pp, g, f);
8859# endif
8860 }
8861 }
8862# else
8863 png_error(pp, "alpha mode handling not supported");
8864# endif
8865 }
8866
8867 else
8868 {
8869 /* Set up gamma processing. */
8870# ifdef PNG_FLOATING_POINT_SUPPORTED
8871 png_set_gamma(pp, dp->screen_gamma, dp->file_gamma);
8872# else
8873 {
8874 png_fixed_point s = fix(dp->screen_gamma);
8875 png_fixed_point f = fix(dp->file_gamma);
8876 png_set_gamma_fixed(pp, s, f);
8877 }
8878# endif
8879
8880 if (dp->do_background)
8881 {
8882# ifdef PNG_READ_BACKGROUND_SUPPORTED
8883 /* NOTE: this assumes the caller provided the correct background gamma!
8884 */
Matt Sarett9ea75692016-01-08 13:00:42 -05008885 const double bg = dp->background_gamma;
Chris Craikb50c2172013-07-29 15:28:30 -07008886# ifndef PNG_FLOATING_POINT_SUPPORTED
Matt Sarett9ea75692016-01-08 13:00:42 -05008887 const png_fixed_point g = fix(bg);
Chris Craikb50c2172013-07-29 15:28:30 -07008888# endif
8889
8890# ifdef PNG_FLOATING_POINT_SUPPORTED
8891 png_set_background(pp, &dp->background_color, dp->do_background,
8892 0/*need_expand*/, bg);
8893# else
8894 png_set_background_fixed(pp, &dp->background_color,
8895 dp->do_background, 0/*need_expand*/, g);
8896# endif
8897# else
8898 png_error(pp, "png_set_background not supported");
8899# endif
8900 }
8901 }
8902
8903 {
8904 int i = dp->this.use_update_info;
8905 /* Always do one call, even if use_update_info is 0. */
8906 do
8907 png_read_update_info(pp, pi);
8908 while (--i > 0);
8909 }
8910
8911 /* Now we may get a different cbRow: */
8912 standard_info_part2(&dp->this, pp, pi, 1 /*images*/);
8913}
8914
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308915static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07008916gamma_info(png_structp pp, png_infop pi)
8917{
8918 gamma_info_imp(voidcast(gamma_display*, png_get_progressive_ptr(pp)), pp,
8919 pi);
8920}
8921
8922/* Validate a single component value - the routine gets the input and output
8923 * sample values as unscaled PNG component values along with a cache of all the
8924 * information required to validate the values.
8925 */
8926typedef struct validate_info
8927{
8928 png_const_structp pp;
8929 gamma_display *dp;
8930 png_byte sbit;
8931 int use_input_precision;
8932 int do_background;
8933 int scale16;
8934 unsigned int sbit_max;
8935 unsigned int isbit_shift;
8936 unsigned int outmax;
8937
8938 double gamma_correction; /* Overall correction required. */
8939 double file_inverse; /* Inverse of file gamma. */
8940 double screen_gamma;
8941 double screen_inverse; /* Inverse of screen gamma. */
8942
8943 double background_red; /* Linear background value, red or gray. */
8944 double background_green;
8945 double background_blue;
8946
8947 double maxabs;
8948 double maxpc;
8949 double maxcalc;
8950 double maxout;
8951 double maxout_total; /* Total including quantization error */
8952 double outlog;
8953 int outquant;
8954}
8955validate_info;
8956
8957static void
8958init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp,
8959 int in_depth, int out_depth)
8960{
Matt Sarett9ea75692016-01-08 13:00:42 -05008961 const unsigned int outmax = (1U<<out_depth)-1;
Chris Craikb50c2172013-07-29 15:28:30 -07008962
8963 vi->pp = pp;
8964 vi->dp = dp;
8965
8966 if (dp->sbit > 0 && dp->sbit < in_depth)
8967 {
8968 vi->sbit = dp->sbit;
8969 vi->isbit_shift = in_depth - dp->sbit;
8970 }
8971
8972 else
8973 {
8974 vi->sbit = (png_byte)in_depth;
8975 vi->isbit_shift = 0;
8976 }
8977
8978 vi->sbit_max = (1U << vi->sbit)-1;
8979
8980 /* This mimics the libpng threshold test, '0' is used to prevent gamma
8981 * correction in the validation test.
8982 */
8983 vi->screen_gamma = dp->screen_gamma;
8984 if (fabs(vi->screen_gamma-1) < PNG_GAMMA_THRESHOLD)
8985 vi->screen_gamma = vi->screen_inverse = 0;
8986 else
8987 vi->screen_inverse = 1/vi->screen_gamma;
8988
8989 vi->use_input_precision = dp->use_input_precision;
8990 vi->outmax = outmax;
8991 vi->maxabs = abserr(dp->pm, in_depth, out_depth);
8992 vi->maxpc = pcerr(dp->pm, in_depth, out_depth);
8993 vi->maxcalc = calcerr(dp->pm, in_depth, out_depth);
8994 vi->maxout = outerr(dp->pm, in_depth, out_depth);
8995 vi->outquant = output_quantization_factor(dp->pm, in_depth, out_depth);
8996 vi->maxout_total = vi->maxout + vi->outquant * .5;
8997 vi->outlog = outlog(dp->pm, in_depth, out_depth);
8998
8999 if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 ||
Matt Sarett9ea75692016-01-08 13:00:42 -05009000 (dp->this.colour_type == 3 && dp->this.is_transparent) ||
9001 ((dp->this.colour_type == 0 || dp->this.colour_type == 2) &&
9002 dp->this.has_tRNS))
Chris Craikb50c2172013-07-29 15:28:30 -07009003 {
9004 vi->do_background = dp->do_background;
9005
9006 if (vi->do_background != 0)
9007 {
Matt Sarett9ea75692016-01-08 13:00:42 -05009008 const double bg_inverse = 1/dp->background_gamma;
Chris Craikb50c2172013-07-29 15:28:30 -07009009 double r, g, b;
9010
9011 /* Caller must at least put the gray value into the red channel */
9012 r = dp->background_color.red; r /= outmax;
9013 g = dp->background_color.green; g /= outmax;
9014 b = dp->background_color.blue; b /= outmax;
9015
9016# if 0
9017 /* libpng doesn't do this optimization, if we do pngvalid will fail.
9018 */
9019 if (fabs(bg_inverse-1) >= PNG_GAMMA_THRESHOLD)
9020# endif
9021 {
9022 r = pow(r, bg_inverse);
9023 g = pow(g, bg_inverse);
9024 b = pow(b, bg_inverse);
9025 }
9026
9027 vi->background_red = r;
9028 vi->background_green = g;
9029 vi->background_blue = b;
9030 }
9031 }
Matt Sarett9ea75692016-01-08 13:00:42 -05009032 else /* Do not expect any background processing */
Chris Craikb50c2172013-07-29 15:28:30 -07009033 vi->do_background = 0;
9034
9035 if (vi->do_background == 0)
9036 vi->background_red = vi->background_green = vi->background_blue = 0;
9037
9038 vi->gamma_correction = 1/(dp->file_gamma*dp->screen_gamma);
9039 if (fabs(vi->gamma_correction-1) < PNG_GAMMA_THRESHOLD)
9040 vi->gamma_correction = 0;
9041
9042 vi->file_inverse = 1/dp->file_gamma;
9043 if (fabs(vi->file_inverse-1) < PNG_GAMMA_THRESHOLD)
9044 vi->file_inverse = 0;
9045
9046 vi->scale16 = dp->scale16;
9047}
9048
9049/* This function handles composition of a single non-alpha component. The
9050 * argument is the input sample value, in the range 0..1, and the alpha value.
9051 * The result is the composed, linear, input sample. If alpha is less than zero
9052 * this is the alpha component and the function should not be called!
9053 */
9054static double
9055gamma_component_compose(int do_background, double input_sample, double alpha,
9056 double background, int *compose)
9057{
9058 switch (do_background)
9059 {
9060#ifdef PNG_READ_BACKGROUND_SUPPORTED
9061 case PNG_BACKGROUND_GAMMA_SCREEN:
9062 case PNG_BACKGROUND_GAMMA_FILE:
9063 case PNG_BACKGROUND_GAMMA_UNIQUE:
9064 /* Standard PNG background processing. */
9065 if (alpha < 1)
9066 {
9067 if (alpha > 0)
9068 {
9069 input_sample = input_sample * alpha + background * (1-alpha);
9070 if (compose != NULL)
9071 *compose = 1;
9072 }
9073
9074 else
9075 input_sample = background;
9076 }
9077 break;
9078#endif
9079
9080#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9081 case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
9082 case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
9083 /* The components are premultiplied in either case and the output is
9084 * gamma encoded (to get standard Porter-Duff we expect the output
9085 * gamma to be set to 1.0!)
9086 */
9087 case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
9088 /* The optimization is that the partial-alpha entries are linear
9089 * while the opaque pixels are gamma encoded, but this only affects the
9090 * output encoding.
9091 */
9092 if (alpha < 1)
9093 {
9094 if (alpha > 0)
9095 {
9096 input_sample *= alpha;
9097 if (compose != NULL)
9098 *compose = 1;
9099 }
9100
9101 else
9102 input_sample = 0;
9103 }
9104 break;
9105#endif
9106
9107 default:
9108 /* Standard cases where no compositing is done (so the component
9109 * value is already correct.)
9110 */
9111 UNUSED(alpha)
9112 UNUSED(background)
9113 UNUSED(compose)
9114 break;
9115 }
9116
9117 return input_sample;
9118}
9119
9120/* This API returns the encoded *input* component, in the range 0..1 */
9121static double
Matt Sarett9ea75692016-01-08 13:00:42 -05009122gamma_component_validate(const char *name, const validate_info *vi,
9123 const unsigned int id, const unsigned int od,
9124 const double alpha /* <0 for the alpha channel itself */,
9125 const double background /* component background value */)
Chris Craikb50c2172013-07-29 15:28:30 -07009126{
Matt Sarett9ea75692016-01-08 13:00:42 -05009127 const unsigned int isbit = id >> vi->isbit_shift;
9128 const unsigned int sbit_max = vi->sbit_max;
9129 const unsigned int outmax = vi->outmax;
9130 const int do_background = vi->do_background;
Chris Craikb50c2172013-07-29 15:28:30 -07009131
9132 double i;
9133
9134 /* First check on the 'perfect' result obtained from the digitized input
9135 * value, id, and compare this against the actual digitized result, 'od'.
9136 * 'i' is the input result in the range 0..1:
9137 */
9138 i = isbit; i /= sbit_max;
9139
9140 /* Check for the fast route: if we don't do any background composition or if
9141 * this is the alpha channel ('alpha' < 0) or if the pixel is opaque then
9142 * just use the gamma_correction field to correct to the final output gamma.
9143 */
9144 if (alpha == 1 /* opaque pixel component */ || !do_background
9145#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9146 || do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_PNG
9147#endif
9148 || (alpha < 0 /* alpha channel */
9149#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9150 && do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN
9151#endif
9152 ))
9153 {
9154 /* Then get the gamma corrected version of 'i' and compare to 'od', any
9155 * error less than .5 is insignificant - just quantization of the output
9156 * value to the nearest digital value (nevertheless the error is still
9157 * recorded - it's interesting ;-)
9158 */
9159 double encoded_sample = i;
9160 double encoded_error;
9161
9162 /* alpha less than 0 indicates the alpha channel, which is always linear
9163 */
9164 if (alpha >= 0 && vi->gamma_correction > 0)
9165 encoded_sample = pow(encoded_sample, vi->gamma_correction);
9166 encoded_sample *= outmax;
9167
9168 encoded_error = fabs(od-encoded_sample);
9169
9170 if (encoded_error > vi->dp->maxerrout)
9171 vi->dp->maxerrout = encoded_error;
9172
9173 if (encoded_error < vi->maxout_total && encoded_error < vi->outlog)
9174 return i;
9175 }
9176
9177 /* The slow route - attempt to do linear calculations. */
9178 /* There may be an error, or background processing is required, so calculate
9179 * the actual sample values - unencoded light intensity values. Note that in
9180 * practice these are not completely unencoded because they include a
9181 * 'viewing correction' to decrease or (normally) increase the perceptual
9182 * contrast of the image. There's nothing we can do about this - we don't
9183 * know what it is - so assume the unencoded value is perceptually linear.
9184 */
9185 {
9186 double input_sample = i; /* In range 0..1 */
9187 double output, error, encoded_sample, encoded_error;
9188 double es_lo, es_hi;
9189 int compose = 0; /* Set to one if composition done */
9190 int output_is_encoded; /* Set if encoded to screen gamma */
9191 int log_max_error = 1; /* Check maximum error values */
9192 png_const_charp pass = 0; /* Reason test passes (or 0 for fail) */
9193
9194 /* Convert to linear light (with the above caveat.) The alpha channel is
9195 * already linear.
9196 */
9197 if (alpha >= 0)
9198 {
9199 int tcompose;
9200
9201 if (vi->file_inverse > 0)
9202 input_sample = pow(input_sample, vi->file_inverse);
9203
9204 /* Handle the compose processing: */
9205 tcompose = 0;
9206 input_sample = gamma_component_compose(do_background, input_sample,
9207 alpha, background, &tcompose);
9208
9209 if (tcompose)
9210 compose = 1;
9211 }
9212
9213 /* And similarly for the output value, but we need to check the background
9214 * handling to linearize it correctly.
9215 */
9216 output = od;
9217 output /= outmax;
9218
9219 output_is_encoded = vi->screen_gamma > 0;
9220
9221 if (alpha < 0) /* The alpha channel */
9222 {
9223#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9224 if (do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN)
9225#endif
9226 {
9227 /* In all other cases the output alpha channel is linear already,
9228 * don't log errors here, they are much larger in linear data.
9229 */
9230 output_is_encoded = 0;
9231 log_max_error = 0;
9232 }
9233 }
9234
9235#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9236 else /* A component */
9237 {
9238 if (do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED &&
9239 alpha < 1) /* the optimized case - linear output */
9240 {
9241 if (alpha > 0) log_max_error = 0;
9242 output_is_encoded = 0;
9243 }
9244 }
9245#endif
9246
9247 if (output_is_encoded)
9248 output = pow(output, vi->screen_gamma);
9249
9250 /* Calculate (or recalculate) the encoded_sample value and repeat the
9251 * check above (unnecessary if we took the fast route, but harmless.)
9252 */
9253 encoded_sample = input_sample;
9254 if (output_is_encoded)
9255 encoded_sample = pow(encoded_sample, vi->screen_inverse);
9256 encoded_sample *= outmax;
9257
9258 encoded_error = fabs(od-encoded_sample);
9259
9260 /* Don't log errors in the alpha channel, or the 'optimized' case,
9261 * neither are significant to the overall perception.
9262 */
9263 if (log_max_error && encoded_error > vi->dp->maxerrout)
9264 vi->dp->maxerrout = encoded_error;
9265
9266 if (encoded_error < vi->maxout_total)
9267 {
9268 if (encoded_error < vi->outlog)
9269 return i;
9270
9271 /* Test passed but error is bigger than the log limit, record why the
9272 * test passed:
9273 */
9274 pass = "less than maxout:\n";
9275 }
9276
9277 /* i: the original input value in the range 0..1
9278 *
9279 * pngvalid calculations:
9280 * input_sample: linear result; i linearized and composed, range 0..1
9281 * encoded_sample: encoded result; input_sample scaled to ouput bit depth
9282 *
9283 * libpng calculations:
9284 * output: linear result; od scaled to 0..1 and linearized
9285 * od: encoded result from libpng
9286 */
9287
9288 /* Now we have the numbers for real errors, both absolute values as as a
9289 * percentage of the correct value (output):
9290 */
9291 error = fabs(input_sample-output);
9292
9293 if (log_max_error && error > vi->dp->maxerrabs)
9294 vi->dp->maxerrabs = error;
9295
9296 /* The following is an attempt to ignore the tendency of quantization to
9297 * dominate the percentage errors for lower result values:
9298 */
9299 if (log_max_error && input_sample > .5)
9300 {
9301 double percentage_error = error/input_sample;
9302 if (percentage_error > vi->dp->maxerrpc)
9303 vi->dp->maxerrpc = percentage_error;
9304 }
9305
9306 /* Now calculate the digitization limits for 'encoded_sample' using the
9307 * 'max' values. Note that maxout is in the encoded space but maxpc and
9308 * maxabs are in linear light space.
9309 *
9310 * First find the maximum error in linear light space, range 0..1:
9311 */
9312 {
9313 double tmp = input_sample * vi->maxpc;
9314 if (tmp < vi->maxabs) tmp = vi->maxabs;
9315 /* If 'compose' is true the composition was done in linear space using
9316 * integer arithmetic. This introduces an extra error of +/- 0.5 (at
9317 * least) in the integer space used. 'maxcalc' records this, taking
9318 * into account the possibility that even for 16 bit output 8 bit space
9319 * may have been used.
9320 */
9321 if (compose && tmp < vi->maxcalc) tmp = vi->maxcalc;
9322
9323 /* The 'maxout' value refers to the encoded result, to compare with
9324 * this encode input_sample adjusted by the maximum error (tmp) above.
9325 */
9326 es_lo = encoded_sample - vi->maxout;
9327
9328 if (es_lo > 0 && input_sample-tmp > 0)
9329 {
9330 double low_value = input_sample-tmp;
9331 if (output_is_encoded)
9332 low_value = pow(low_value, vi->screen_inverse);
9333 low_value *= outmax;
9334 if (low_value < es_lo) es_lo = low_value;
9335
9336 /* Quantize this appropriately: */
9337 es_lo = ceil(es_lo / vi->outquant - .5) * vi->outquant;
9338 }
9339
9340 else
9341 es_lo = 0;
9342
9343 es_hi = encoded_sample + vi->maxout;
9344
9345 if (es_hi < outmax && input_sample+tmp < 1)
9346 {
9347 double high_value = input_sample+tmp;
9348 if (output_is_encoded)
9349 high_value = pow(high_value, vi->screen_inverse);
9350 high_value *= outmax;
9351 if (high_value > es_hi) es_hi = high_value;
9352
9353 es_hi = floor(es_hi / vi->outquant + .5) * vi->outquant;
9354 }
9355
9356 else
9357 es_hi = outmax;
9358 }
9359
9360 /* The primary test is that the final encoded value returned by the
9361 * library should be between the two limits (inclusive) that were
9362 * calculated above.
9363 */
9364 if (od >= es_lo && od <= es_hi)
9365 {
9366 /* The value passes, but we may need to log the information anyway. */
9367 if (encoded_error < vi->outlog)
9368 return i;
9369
9370 if (pass == 0)
9371 pass = "within digitization limits:\n";
9372 }
9373
9374 {
9375 /* There has been an error in processing, or we need to log this
9376 * value.
9377 */
9378 double is_lo, is_hi;
9379
9380 /* pass is set at this point if either of the tests above would have
9381 * passed. Don't do these additional tests here - just log the
9382 * original [es_lo..es_hi] values.
9383 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309384 if (pass == 0 && vi->use_input_precision && vi->dp->sbit)
Chris Craikb50c2172013-07-29 15:28:30 -07009385 {
9386 /* Ok, something is wrong - this actually happens in current libpng
9387 * 16-to-8 processing. Assume that the input value (id, adjusted
9388 * for sbit) can be anywhere between value-.5 and value+.5 - quite a
9389 * large range if sbit is low.
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309390 *
9391 * NOTE: at present because the libpng gamma table stuff has been
9392 * changed to use a rounding algorithm to correct errors in 8-bit
9393 * calculations the precise sbit calculation (a shift) has been
9394 * lost. This can result in up to a +/-1 error in the presence of
9395 * an sbit less than the bit depth.
Chris Craikb50c2172013-07-29 15:28:30 -07009396 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309397# if PNG_LIBPNG_VER < 10700
9398# define SBIT_ERROR .5
9399# else
9400# define SBIT_ERROR 1.
9401# endif
9402 double tmp = (isbit - SBIT_ERROR)/sbit_max;
Chris Craikb50c2172013-07-29 15:28:30 -07009403
9404 if (tmp <= 0)
9405 tmp = 0;
9406
9407 else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
9408 tmp = pow(tmp, vi->file_inverse);
9409
9410 tmp = gamma_component_compose(do_background, tmp, alpha, background,
9411 NULL);
9412
9413 if (output_is_encoded && tmp > 0 && tmp < 1)
9414 tmp = pow(tmp, vi->screen_inverse);
9415
9416 is_lo = ceil(outmax * tmp - vi->maxout_total);
9417
9418 if (is_lo < 0)
9419 is_lo = 0;
9420
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309421 tmp = (isbit + SBIT_ERROR)/sbit_max;
Chris Craikb50c2172013-07-29 15:28:30 -07009422
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309423 if (tmp >= 1)
9424 tmp = 1;
Chris Craikb50c2172013-07-29 15:28:30 -07009425
9426 else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
9427 tmp = pow(tmp, vi->file_inverse);
9428
9429 tmp = gamma_component_compose(do_background, tmp, alpha, background,
9430 NULL);
9431
9432 if (output_is_encoded && tmp > 0 && tmp < 1)
9433 tmp = pow(tmp, vi->screen_inverse);
9434
9435 is_hi = floor(outmax * tmp + vi->maxout_total);
9436
9437 if (is_hi > outmax)
9438 is_hi = outmax;
9439
9440 if (!(od < is_lo || od > is_hi))
9441 {
9442 if (encoded_error < vi->outlog)
9443 return i;
9444
9445 pass = "within input precision limits:\n";
9446 }
9447
9448 /* One last chance. If this is an alpha channel and the 16to8
9449 * option has been used and 'inaccurate' scaling is used then the
9450 * bit reduction is obtained by simply using the top 8 bits of the
9451 * value.
9452 *
9453 * This is only done for older libpng versions when the 'inaccurate'
9454 * (chop) method of scaling was used.
9455 */
9456# ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
9457# if PNG_LIBPNG_VER < 10504
9458 /* This may be required for other components in the future,
9459 * but at present the presence of gamma correction effectively
9460 * prevents the errors in the component scaling (I don't quite
9461 * understand why, but since it's better this way I care not
9462 * to ask, JB 20110419.)
9463 */
9464 if (pass == 0 && alpha < 0 && vi->scale16 && vi->sbit > 8 &&
9465 vi->sbit + vi->isbit_shift == 16)
9466 {
9467 tmp = ((id >> 8) - .5)/255;
9468
9469 if (tmp > 0)
9470 {
9471 is_lo = ceil(outmax * tmp - vi->maxout_total);
9472 if (is_lo < 0) is_lo = 0;
9473 }
9474
9475 else
9476 is_lo = 0;
9477
9478 tmp = ((id >> 8) + .5)/255;
9479
9480 if (tmp < 1)
9481 {
9482 is_hi = floor(outmax * tmp + vi->maxout_total);
9483 if (is_hi > outmax) is_hi = outmax;
9484 }
9485
9486 else
9487 is_hi = outmax;
9488
9489 if (!(od < is_lo || od > is_hi))
9490 {
9491 if (encoded_error < vi->outlog)
9492 return i;
9493
9494 pass = "within 8 bit limits:\n";
9495 }
9496 }
9497# endif
9498# endif
9499 }
9500 else /* !use_input_precision */
9501 is_lo = es_lo, is_hi = es_hi;
9502
9503 /* Attempt to output a meaningful error/warning message: the message
9504 * output depends on the background/composite operation being performed
9505 * because this changes what parameters were actually used above.
9506 */
9507 {
9508 size_t pos = 0;
9509 /* Need either 1/255 or 1/65535 precision here; 3 or 6 decimal
9510 * places. Just use outmax to work out which.
9511 */
9512 int precision = (outmax >= 1000 ? 6 : 3);
9513 int use_input=1, use_background=0, do_compose=0;
9514 char msg[256];
9515
9516 if (pass != 0)
9517 pos = safecat(msg, sizeof msg, pos, "\n\t");
9518
9519 /* Set up the various flags, the output_is_encoded flag above
9520 * is also used below. do_compose is just a double check.
9521 */
9522 switch (do_background)
9523 {
9524# ifdef PNG_READ_BACKGROUND_SUPPORTED
9525 case PNG_BACKGROUND_GAMMA_SCREEN:
9526 case PNG_BACKGROUND_GAMMA_FILE:
9527 case PNG_BACKGROUND_GAMMA_UNIQUE:
9528 use_background = (alpha >= 0 && alpha < 1);
9529 /*FALL THROUGH*/
9530# endif
9531# ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9532 case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
9533 case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
9534 case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
9535# endif /* ALPHA_MODE_SUPPORTED */
9536 do_compose = (alpha > 0 && alpha < 1);
9537 use_input = (alpha != 0);
9538 break;
9539
9540 default:
9541 break;
9542 }
9543
9544 /* Check the 'compose' flag */
9545 if (compose != do_compose)
9546 png_error(vi->pp, "internal error (compose)");
9547
9548 /* 'name' is the component name */
9549 pos = safecat(msg, sizeof msg, pos, name);
9550 pos = safecat(msg, sizeof msg, pos, "(");
9551 pos = safecatn(msg, sizeof msg, pos, id);
9552 if (use_input || pass != 0/*logging*/)
9553 {
9554 if (isbit != id)
9555 {
9556 /* sBIT has reduced the precision of the input: */
9557 pos = safecat(msg, sizeof msg, pos, ", sbit(");
9558 pos = safecatn(msg, sizeof msg, pos, vi->sbit);
9559 pos = safecat(msg, sizeof msg, pos, "): ");
9560 pos = safecatn(msg, sizeof msg, pos, isbit);
9561 }
9562 pos = safecat(msg, sizeof msg, pos, "/");
9563 /* The output is either "id/max" or "id sbit(sbit): isbit/max" */
9564 pos = safecatn(msg, sizeof msg, pos, vi->sbit_max);
9565 }
9566 pos = safecat(msg, sizeof msg, pos, ")");
9567
9568 /* A component may have been multiplied (in linear space) by the
9569 * alpha value, 'compose' says whether this is relevant.
9570 */
9571 if (compose || pass != 0)
9572 {
9573 /* If any form of composition is being done report our
9574 * calculated linear value here (the code above doesn't record
9575 * the input value before composition is performed, so what
9576 * gets reported is the value after composition.)
9577 */
9578 if (use_input || pass != 0)
9579 {
9580 if (vi->file_inverse > 0)
9581 {
9582 pos = safecat(msg, sizeof msg, pos, "^");
9583 pos = safecatd(msg, sizeof msg, pos, vi->file_inverse, 2);
9584 }
9585
9586 else
9587 pos = safecat(msg, sizeof msg, pos, "[linear]");
9588
9589 pos = safecat(msg, sizeof msg, pos, "*(alpha)");
9590 pos = safecatd(msg, sizeof msg, pos, alpha, precision);
9591 }
9592
9593 /* Now record the *linear* background value if it was used
9594 * (this function is not passed the original, non-linear,
9595 * value but it is contained in the test name.)
9596 */
9597 if (use_background)
9598 {
9599 pos = safecat(msg, sizeof msg, pos, use_input ? "+" : " ");
9600 pos = safecat(msg, sizeof msg, pos, "(background)");
9601 pos = safecatd(msg, sizeof msg, pos, background, precision);
9602 pos = safecat(msg, sizeof msg, pos, "*");
9603 pos = safecatd(msg, sizeof msg, pos, 1-alpha, precision);
9604 }
9605 }
9606
9607 /* Report the calculated value (input_sample) and the linearized
9608 * libpng value (output) unless this is just a component gamma
9609 * correction.
9610 */
9611 if (compose || alpha < 0 || pass != 0)
9612 {
9613 pos = safecat(msg, sizeof msg, pos,
9614 pass != 0 ? " =\n\t" : " = ");
9615 pos = safecatd(msg, sizeof msg, pos, input_sample, precision);
9616 pos = safecat(msg, sizeof msg, pos, " (libpng: ");
9617 pos = safecatd(msg, sizeof msg, pos, output, precision);
9618 pos = safecat(msg, sizeof msg, pos, ")");
9619
9620 /* Finally report the output gamma encoding, if any. */
9621 if (output_is_encoded)
9622 {
9623 pos = safecat(msg, sizeof msg, pos, " ^");
9624 pos = safecatd(msg, sizeof msg, pos, vi->screen_inverse, 2);
9625 pos = safecat(msg, sizeof msg, pos, "(to screen) =");
9626 }
9627
9628 else
9629 pos = safecat(msg, sizeof msg, pos, " [screen is linear] =");
9630 }
9631
9632 if ((!compose && alpha >= 0) || pass != 0)
9633 {
9634 if (pass != 0) /* logging */
9635 pos = safecat(msg, sizeof msg, pos, "\n\t[overall:");
9636
9637 /* This is the non-composition case, the internal linear
9638 * values are irrelevant (though the log below will reveal
9639 * them.) Output a much shorter warning/error message and report
9640 * the overall gamma correction.
9641 */
9642 if (vi->gamma_correction > 0)
9643 {
9644 pos = safecat(msg, sizeof msg, pos, " ^");
9645 pos = safecatd(msg, sizeof msg, pos, vi->gamma_correction, 2);
9646 pos = safecat(msg, sizeof msg, pos, "(gamma correction) =");
9647 }
9648
9649 else
9650 pos = safecat(msg, sizeof msg, pos,
9651 " [no gamma correction] =");
9652
9653 if (pass != 0)
9654 pos = safecat(msg, sizeof msg, pos, "]");
9655 }
9656
9657 /* This is our calculated encoded_sample which should (but does
9658 * not) match od:
9659 */
9660 pos = safecat(msg, sizeof msg, pos, pass != 0 ? "\n\t" : " ");
9661 pos = safecatd(msg, sizeof msg, pos, is_lo, 1);
9662 pos = safecat(msg, sizeof msg, pos, " < ");
9663 pos = safecatd(msg, sizeof msg, pos, encoded_sample, 1);
9664 pos = safecat(msg, sizeof msg, pos, " (libpng: ");
9665 pos = safecatn(msg, sizeof msg, pos, od);
9666 pos = safecat(msg, sizeof msg, pos, ")");
9667 pos = safecat(msg, sizeof msg, pos, "/");
9668 pos = safecatn(msg, sizeof msg, pos, outmax);
9669 pos = safecat(msg, sizeof msg, pos, " < ");
9670 pos = safecatd(msg, sizeof msg, pos, is_hi, 1);
9671
9672 if (pass == 0) /* The error condition */
9673 {
9674# ifdef PNG_WARNINGS_SUPPORTED
9675 png_warning(vi->pp, msg);
9676# else
9677 store_warning(vi->pp, msg);
9678# endif
9679 }
9680
9681 else /* logging this value */
9682 store_verbose(&vi->dp->pm->this, vi->pp, pass, msg);
9683 }
9684 }
9685 }
9686
9687 return i;
9688}
9689
9690static void
9691gamma_image_validate(gamma_display *dp, png_const_structp pp,
9692 png_infop pi)
9693{
9694 /* Get some constants derived from the input and output file formats: */
Matt Sarett9ea75692016-01-08 13:00:42 -05009695 const png_store* const ps = dp->this.ps;
9696 const png_byte in_ct = dp->this.colour_type;
9697 const png_byte in_bd = dp->this.bit_depth;
9698 const png_uint_32 w = dp->this.w;
9699 const png_uint_32 h = dp->this.h;
9700 const size_t cbRow = dp->this.cbRow;
9701 const png_byte out_ct = png_get_color_type(pp, pi);
9702 const png_byte out_bd = png_get_bit_depth(pp, pi);
Chris Craikb50c2172013-07-29 15:28:30 -07009703
9704 /* There are three sources of error, firstly the quantization in the
9705 * file encoding, determined by sbit and/or the file depth, secondly
9706 * the output (screen) gamma and thirdly the output file encoding.
9707 *
9708 * Since this API receives the screen and file gamma in double
9709 * precision it is possible to calculate an exact answer given an input
9710 * pixel value. Therefore we assume that the *input* value is exact -
9711 * sample/maxsample - calculate the corresponding gamma corrected
9712 * output to the limits of double precision arithmetic and compare with
9713 * what libpng returns.
9714 *
9715 * Since the library must quantize the output to 8 or 16 bits there is
9716 * a fundamental limit on the accuracy of the output of +/-.5 - this
9717 * quantization limit is included in addition to the other limits
9718 * specified by the paramaters to the API. (Effectively, add .5
9719 * everywhere.)
9720 *
9721 * The behavior of the 'sbit' paramter is defined by section 12.5
9722 * (sample depth scaling) of the PNG spec. That section forces the
9723 * decoder to assume that the PNG values have been scaled if sBIT is
9724 * present:
9725 *
9726 * png-sample = floor( input-sample * (max-out/max-in) + .5);
9727 *
9728 * This means that only a subset of the possible PNG values should
9729 * appear in the input. However, the spec allows the encoder to use a
9730 * variety of approximations to the above and doesn't require any
9731 * restriction of the values produced.
9732 *
9733 * Nevertheless the spec requires that the upper 'sBIT' bits of the
9734 * value stored in a PNG file be the original sample bits.
9735 * Consequently the code below simply scales the top sbit bits by
9736 * (1<<sbit)-1 to obtain an original sample value.
9737 *
9738 * Because there is limited precision in the input it is arguable that
9739 * an acceptable result is any valid result from input-.5 to input+.5.
9740 * The basic tests below do not do this, however if 'use_input_precision'
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309741 * is set a subsequent test is performed above.
Chris Craikb50c2172013-07-29 15:28:30 -07009742 */
Matt Sarett9ea75692016-01-08 13:00:42 -05009743 const unsigned int samples_per_pixel = (out_ct & 2U) ? 3U : 1U;
Chris Craikb50c2172013-07-29 15:28:30 -07009744 int processing;
9745 png_uint_32 y;
Matt Sarett9ea75692016-01-08 13:00:42 -05009746 const store_palette_entry *in_palette = dp->this.palette;
9747 const int in_is_transparent = dp->this.is_transparent;
9748 int process_tRNS;
Chris Craikb50c2172013-07-29 15:28:30 -07009749 int out_npalette = -1;
9750 int out_is_transparent = 0; /* Just refers to the palette case */
9751 store_palette out_palette;
9752 validate_info vi;
9753
9754 /* Check for row overwrite errors */
9755 store_image_check(dp->this.ps, pp, 0);
9756
9757 /* Supply the input and output sample depths here - 8 for an indexed image,
9758 * otherwise the bit depth.
9759 */
9760 init_validate_info(&vi, dp, pp, in_ct==3?8:in_bd, out_ct==3?8:out_bd);
9761
9762 processing = (vi.gamma_correction > 0 && !dp->threshold_test)
9763 || in_bd != out_bd || in_ct != out_ct || vi.do_background;
Matt Sarett9ea75692016-01-08 13:00:42 -05009764 process_tRNS = dp->this.has_tRNS && vi.do_background;
Chris Craikb50c2172013-07-29 15:28:30 -07009765
9766 /* TODO: FIX THIS: MAJOR BUG! If the transformations all happen inside
9767 * the palette there is no way of finding out, because libpng fails to
9768 * update the palette on png_read_update_info. Indeed, libpng doesn't
9769 * even do the required work until much later, when it doesn't have any
9770 * info pointer. Oops. For the moment 'processing' is turned off if
9771 * out_ct is palette.
9772 */
9773 if (in_ct == 3 && out_ct == 3)
9774 processing = 0;
9775
9776 if (processing && out_ct == 3)
9777 out_is_transparent = read_palette(out_palette, &out_npalette, pp, pi);
9778
9779 for (y=0; y<h; ++y)
9780 {
9781 png_const_bytep pRow = store_image_row(ps, pp, 0, y);
9782 png_byte std[STANDARD_ROWMAX];
9783
9784 transform_row(pp, std, in_ct, in_bd, y);
9785
9786 if (processing)
9787 {
9788 unsigned int x;
9789
9790 for (x=0; x<w; ++x)
9791 {
9792 double alpha = 1; /* serves as a flag value */
9793
9794 /* Record the palette index for index images. */
Matt Sarett9ea75692016-01-08 13:00:42 -05009795 const unsigned int in_index =
9796 in_ct == 3 ? sample(std, 3, in_bd, x, 0, 0, 0) : 256;
9797 const unsigned int out_index =
9798 out_ct == 3 ? sample(std, 3, out_bd, x, 0, 0, 0) : 256;
Chris Craikb50c2172013-07-29 15:28:30 -07009799
9800 /* Handle input alpha - png_set_background will cause the output
9801 * alpha to disappear so there is nothing to check.
9802 */
Matt Sarett9ea75692016-01-08 13:00:42 -05009803 if ((in_ct & PNG_COLOR_MASK_ALPHA) != 0 ||
9804 (in_ct == 3 && in_is_transparent))
Chris Craikb50c2172013-07-29 15:28:30 -07009805 {
Matt Sarett9ea75692016-01-08 13:00:42 -05009806 const unsigned int input_alpha = in_ct == 3 ?
Chris Craikb50c2172013-07-29 15:28:30 -07009807 dp->this.palette[in_index].alpha :
Matt Sarett9ea75692016-01-08 13:00:42 -05009808 sample(std, in_ct, in_bd, x, samples_per_pixel, 0, 0);
Chris Craikb50c2172013-07-29 15:28:30 -07009809
9810 unsigned int output_alpha = 65536 /* as a flag value */;
9811
9812 if (out_ct == 3)
9813 {
9814 if (out_is_transparent)
9815 output_alpha = out_palette[out_index].alpha;
9816 }
9817
9818 else if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0)
9819 output_alpha = sample(pRow, out_ct, out_bd, x,
Matt Sarett9ea75692016-01-08 13:00:42 -05009820 samples_per_pixel, 0, 0);
Chris Craikb50c2172013-07-29 15:28:30 -07009821
9822 if (output_alpha != 65536)
9823 alpha = gamma_component_validate("alpha", &vi, input_alpha,
9824 output_alpha, -1/*alpha*/, 0/*background*/);
9825
9826 else /* no alpha in output */
9827 {
9828 /* This is a copy of the calculation of 'i' above in order to
9829 * have the alpha value to use in the background calculation.
9830 */
9831 alpha = input_alpha >> vi.isbit_shift;
9832 alpha /= vi.sbit_max;
9833 }
9834 }
9835
Matt Sarett9ea75692016-01-08 13:00:42 -05009836 else if (process_tRNS)
9837 {
9838 /* alpha needs to be set appropriately for this pixel, it is
9839 * currently 1 and needs to be 0 for an input pixel which matches
9840 * the values in tRNS.
9841 */
9842 switch (in_ct)
9843 {
9844 case 0: /* gray */
9845 if (sample(std, in_ct, in_bd, x, 0, 0, 0) ==
9846 dp->this.transparent.red)
9847 alpha = 0;
9848 break;
9849
9850 case 2: /* RGB */
9851 if (sample(std, in_ct, in_bd, x, 0, 0, 0) ==
9852 dp->this.transparent.red &&
9853 sample(std, in_ct, in_bd, x, 1, 0, 0) ==
9854 dp->this.transparent.green &&
9855 sample(std, in_ct, in_bd, x, 2, 0, 0) ==
9856 dp->this.transparent.blue)
9857 alpha = 0;
9858 break;
9859
9860 default:
9861 break;
9862 }
9863 }
9864
Chris Craikb50c2172013-07-29 15:28:30 -07009865 /* Handle grayscale or RGB components. */
9866 if ((in_ct & PNG_COLOR_MASK_COLOR) == 0) /* grayscale */
9867 (void)gamma_component_validate("gray", &vi,
Matt Sarett9ea75692016-01-08 13:00:42 -05009868 sample(std, in_ct, in_bd, x, 0, 0, 0),
9869 sample(pRow, out_ct, out_bd, x, 0, 0, 0),
9870 alpha/*component*/, vi.background_red);
Chris Craikb50c2172013-07-29 15:28:30 -07009871 else /* RGB or palette */
9872 {
9873 (void)gamma_component_validate("red", &vi,
9874 in_ct == 3 ? in_palette[in_index].red :
Matt Sarett9ea75692016-01-08 13:00:42 -05009875 sample(std, in_ct, in_bd, x, 0, 0, 0),
Chris Craikb50c2172013-07-29 15:28:30 -07009876 out_ct == 3 ? out_palette[out_index].red :
Matt Sarett9ea75692016-01-08 13:00:42 -05009877 sample(pRow, out_ct, out_bd, x, 0, 0, 0),
Chris Craikb50c2172013-07-29 15:28:30 -07009878 alpha/*component*/, vi.background_red);
9879
9880 (void)gamma_component_validate("green", &vi,
9881 in_ct == 3 ? in_palette[in_index].green :
Matt Sarett9ea75692016-01-08 13:00:42 -05009882 sample(std, in_ct, in_bd, x, 1, 0, 0),
Chris Craikb50c2172013-07-29 15:28:30 -07009883 out_ct == 3 ? out_palette[out_index].green :
Matt Sarett9ea75692016-01-08 13:00:42 -05009884 sample(pRow, out_ct, out_bd, x, 1, 0, 0),
Chris Craikb50c2172013-07-29 15:28:30 -07009885 alpha/*component*/, vi.background_green);
9886
9887 (void)gamma_component_validate("blue", &vi,
9888 in_ct == 3 ? in_palette[in_index].blue :
Matt Sarett9ea75692016-01-08 13:00:42 -05009889 sample(std, in_ct, in_bd, x, 2, 0, 0),
Chris Craikb50c2172013-07-29 15:28:30 -07009890 out_ct == 3 ? out_palette[out_index].blue :
Matt Sarett9ea75692016-01-08 13:00:42 -05009891 sample(pRow, out_ct, out_bd, x, 2, 0, 0),
Chris Craikb50c2172013-07-29 15:28:30 -07009892 alpha/*component*/, vi.background_blue);
9893 }
9894 }
9895 }
9896
9897 else if (memcmp(std, pRow, cbRow) != 0)
9898 {
9899 char msg[64];
9900
9901 /* No transform is expected on the threshold tests. */
9902 sprintf(msg, "gamma: below threshold row %lu changed",
9903 (unsigned long)y);
9904
9905 png_error(pp, msg);
9906 }
9907 } /* row (y) loop */
9908
9909 dp->this.ps->validated = 1;
9910}
9911
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309912static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07009913gamma_end(png_structp ppIn, png_infop pi)
9914{
9915 png_const_structp pp = ppIn;
9916 gamma_display *dp = voidcast(gamma_display*, png_get_progressive_ptr(pp));
9917
9918 if (!dp->this.speed)
9919 gamma_image_validate(dp, pp, pi);
9920 else
9921 dp->this.ps->validated = 1;
9922}
9923
9924/* A single test run checking a gamma transformation.
9925 *
9926 * maxabs: maximum absolute error as a fraction
9927 * maxout: maximum output error in the output units
9928 * maxpc: maximum percentage error (as a percentage)
9929 */
9930static void
Matt Sarett9ea75692016-01-08 13:00:42 -05009931gamma_test(png_modifier *pmIn, const png_byte colour_typeIn,
9932 const png_byte bit_depthIn, const int palette_numberIn,
9933 const int interlace_typeIn,
9934 const double file_gammaIn, const double screen_gammaIn,
9935 const png_byte sbitIn, const int threshold_testIn,
9936 const char *name,
9937 const int use_input_precisionIn, const int scale16In,
9938 const int expand16In, const int do_backgroundIn,
9939 const png_color_16 *bkgd_colorIn, double bkgd_gammaIn)
Chris Craikb50c2172013-07-29 15:28:30 -07009940{
9941 gamma_display d;
9942 context(&pmIn->this, fault);
9943
9944 gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn,
9945 palette_numberIn, interlace_typeIn, 0, 0, 0),
9946 file_gammaIn, screen_gammaIn, sbitIn,
9947 threshold_testIn, use_input_precisionIn, scale16In,
9948 expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn);
9949
9950 Try
9951 {
9952 png_structp pp;
9953 png_infop pi;
9954 gama_modification gama_mod;
9955 srgb_modification srgb_mod;
9956 sbit_modification sbit_mod;
9957
9958 /* For the moment don't use the png_modifier support here. */
9959 d.pm->encoding_counter = 0;
9960 modifier_set_encoding(d.pm); /* Just resets everything */
9961 d.pm->current_gamma = d.file_gamma;
9962
9963 /* Make an appropriate modifier to set the PNG file gamma to the
9964 * given gamma value and the sBIT chunk to the given precision.
9965 */
9966 d.pm->modifications = NULL;
9967 gama_modification_init(&gama_mod, d.pm, d.file_gamma);
9968 srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/);
9969 if (d.sbit > 0)
9970 sbit_modification_init(&sbit_mod, d.pm, d.sbit);
9971
9972 modification_reset(d.pm->modifications);
9973
Matt Sarett9ea75692016-01-08 13:00:42 -05009974 /* Get a png_struct for reading the image. */
Chris Craikb50c2172013-07-29 15:28:30 -07009975 pp = set_modifier_for_read(d.pm, &pi, d.this.id, name);
9976 standard_palette_init(&d.this);
9977
9978 /* Introduce the correct read function. */
9979 if (d.pm->this.progressive)
9980 {
9981 /* Share the row function with the standard implementation. */
9982 png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row,
9983 gamma_end);
9984
9985 /* Now feed data into the reader until we reach the end: */
9986 modifier_progressive_read(d.pm, pp, pi);
9987 }
9988 else
9989 {
9990 /* modifier_read expects a png_modifier* */
9991 png_set_read_fn(pp, d.pm, modifier_read);
9992
9993 /* Check the header values: */
9994 png_read_info(pp, pi);
9995
9996 /* Process the 'info' requirements. Only one image is generated */
9997 gamma_info_imp(&d, pp, pi);
9998
9999 sequential_row(&d.this, pp, pi, -1, 0);
10000
10001 if (!d.this.speed)
10002 gamma_image_validate(&d, pp, pi);
10003 else
10004 d.this.ps->validated = 1;
10005 }
10006
10007 modifier_reset(d.pm);
10008
10009 if (d.pm->log && !d.threshold_test && !d.this.speed)
10010 fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n",
10011 d.this.bit_depth, colour_types[d.this.colour_type], name,
10012 d.maxerrout, d.maxerrabs, 100*d.maxerrpc);
10013
10014 /* Log the summary values too. */
10015 if (d.this.colour_type == 0 || d.this.colour_type == 4)
10016 {
10017 switch (d.this.bit_depth)
10018 {
10019 case 1:
10020 break;
10021
10022 case 2:
10023 if (d.maxerrout > d.pm->error_gray_2)
10024 d.pm->error_gray_2 = d.maxerrout;
10025
10026 break;
10027
10028 case 4:
10029 if (d.maxerrout > d.pm->error_gray_4)
10030 d.pm->error_gray_4 = d.maxerrout;
10031
10032 break;
10033
10034 case 8:
10035 if (d.maxerrout > d.pm->error_gray_8)
10036 d.pm->error_gray_8 = d.maxerrout;
10037
10038 break;
10039
10040 case 16:
10041 if (d.maxerrout > d.pm->error_gray_16)
10042 d.pm->error_gray_16 = d.maxerrout;
10043
10044 break;
10045
10046 default:
10047 png_error(pp, "bad bit depth (internal: 1)");
10048 }
10049 }
10050
10051 else if (d.this.colour_type == 2 || d.this.colour_type == 6)
10052 {
10053 switch (d.this.bit_depth)
10054 {
10055 case 8:
10056
10057 if (d.maxerrout > d.pm->error_color_8)
10058 d.pm->error_color_8 = d.maxerrout;
10059
10060 break;
10061
10062 case 16:
10063
10064 if (d.maxerrout > d.pm->error_color_16)
10065 d.pm->error_color_16 = d.maxerrout;
10066
10067 break;
10068
10069 default:
10070 png_error(pp, "bad bit depth (internal: 2)");
10071 }
10072 }
10073
10074 else if (d.this.colour_type == 3)
10075 {
10076 if (d.maxerrout > d.pm->error_indexed)
10077 d.pm->error_indexed = d.maxerrout;
10078 }
10079 }
10080
10081 Catch(fault)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010082 modifier_reset(voidcast(png_modifier*,(void*)fault));
Chris Craikb50c2172013-07-29 15:28:30 -070010083}
10084
10085static void gamma_threshold_test(png_modifier *pm, png_byte colour_type,
10086 png_byte bit_depth, int interlace_type, double file_gamma,
10087 double screen_gamma)
10088{
10089 size_t pos = 0;
10090 char name[64];
10091 pos = safecat(name, sizeof name, pos, "threshold ");
10092 pos = safecatd(name, sizeof name, pos, file_gamma, 3);
10093 pos = safecat(name, sizeof name, pos, "/");
10094 pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
10095
10096 (void)gamma_test(pm, colour_type, bit_depth, 0/*palette*/, interlace_type,
10097 file_gamma, screen_gamma, 0/*sBIT*/, 1/*threshold test*/, name,
10098 0 /*no input precision*/,
10099 0 /*no scale16*/, 0 /*no expand16*/, 0 /*no background*/, 0 /*hence*/,
10100 0 /*no background gamma*/);
10101}
10102
10103static void
10104perform_gamma_threshold_tests(png_modifier *pm)
10105{
10106 png_byte colour_type = 0;
10107 png_byte bit_depth = 0;
10108 unsigned int palette_number = 0;
10109
10110 /* Don't test more than one instance of each palette - it's pointless, in
10111 * fact this test is somewhat excessive since libpng doesn't make this
10112 * decision based on colour type or bit depth!
Matt Sarett9ea75692016-01-08 13:00:42 -050010113 *
10114 * CHANGED: now test two palettes and, as a side effect, images with and
10115 * without tRNS.
Chris Craikb50c2172013-07-29 15:28:30 -070010116 */
Matt Sarett9ea75692016-01-08 13:00:42 -050010117 while (next_format(&colour_type, &bit_depth, &palette_number,
10118 pm->test_lbg_gamma_threshold, pm->test_tRNS))
10119 if (palette_number < 2)
Chris Craikb50c2172013-07-29 15:28:30 -070010120 {
10121 double test_gamma = 1.0;
10122 while (test_gamma >= .4)
10123 {
10124 /* There's little point testing the interlacing vs non-interlacing,
10125 * but this can be set from the command line.
10126 */
10127 gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
10128 test_gamma, 1/test_gamma);
10129 test_gamma *= .95;
10130 }
10131
10132 /* And a special test for sRGB */
10133 gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
10134 .45455, 2.2);
10135
10136 if (fail(pm))
10137 return;
10138 }
10139}
10140
10141static void gamma_transform_test(png_modifier *pm,
Matt Sarett9ea75692016-01-08 13:00:42 -050010142 const png_byte colour_type, const png_byte bit_depth,
10143 const int palette_number,
10144 const int interlace_type, const double file_gamma,
10145 const double screen_gamma, const png_byte sbit,
10146 const int use_input_precision, const int scale16)
Chris Craikb50c2172013-07-29 15:28:30 -070010147{
10148 size_t pos = 0;
10149 char name[64];
10150
10151 if (sbit != bit_depth && sbit != 0)
10152 {
10153 pos = safecat(name, sizeof name, pos, "sbit(");
10154 pos = safecatn(name, sizeof name, pos, sbit);
10155 pos = safecat(name, sizeof name, pos, ") ");
10156 }
10157
10158 else
10159 pos = safecat(name, sizeof name, pos, "gamma ");
10160
10161 if (scale16)
10162 pos = safecat(name, sizeof name, pos, "16to8 ");
10163
10164 pos = safecatd(name, sizeof name, pos, file_gamma, 3);
10165 pos = safecat(name, sizeof name, pos, "->");
10166 pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
10167
10168 gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
10169 file_gamma, screen_gamma, sbit, 0, name, use_input_precision,
10170 scale16, pm->test_gamma_expand16, 0 , 0, 0);
10171}
10172
10173static void perform_gamma_transform_tests(png_modifier *pm)
10174{
10175 png_byte colour_type = 0;
10176 png_byte bit_depth = 0;
10177 unsigned int palette_number = 0;
10178
Matt Sarett9ea75692016-01-08 13:00:42 -050010179 while (next_format(&colour_type, &bit_depth, &palette_number,
10180 pm->test_lbg_gamma_transform, pm->test_tRNS))
Chris Craikb50c2172013-07-29 15:28:30 -070010181 {
10182 unsigned int i, j;
10183
10184 for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
10185 if (i != j)
10186 {
10187 gamma_transform_test(pm, colour_type, bit_depth, palette_number,
10188 pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], 0/*sBIT*/,
10189 pm->use_input_precision, 0 /*do not scale16*/);
10190
10191 if (fail(pm))
10192 return;
10193 }
10194 }
10195}
10196
10197static void perform_gamma_sbit_tests(png_modifier *pm)
10198{
10199 png_byte sbit;
10200
10201 /* The only interesting cases are colour and grayscale, alpha is ignored here
10202 * for overall speed. Only bit depths where sbit is less than the bit depth
10203 * are tested.
10204 */
10205 for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit)
10206 {
10207 png_byte colour_type = 0, bit_depth = 0;
10208 unsigned int npalette = 0;
10209
Matt Sarett9ea75692016-01-08 13:00:42 -050010210 while (next_format(&colour_type, &bit_depth, &npalette,
10211 pm->test_lbg_gamma_sbit, pm->test_tRNS))
Chris Craikb50c2172013-07-29 15:28:30 -070010212 if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 &&
10213 ((colour_type == 3 && sbit < 8) ||
10214 (colour_type != 3 && sbit < bit_depth)))
10215 {
10216 unsigned int i;
10217
10218 for (i=0; i<pm->ngamma_tests; ++i)
10219 {
10220 unsigned int j;
10221
10222 for (j=0; j<pm->ngamma_tests; ++j) if (i != j)
10223 {
10224 gamma_transform_test(pm, colour_type, bit_depth, npalette,
10225 pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
10226 sbit, pm->use_input_precision_sbit, 0 /*scale16*/);
10227
10228 if (fail(pm))
10229 return;
10230 }
10231 }
10232 }
10233 }
10234}
10235
10236/* Note that this requires a 16 bit source image but produces 8 bit output, so
10237 * we only need the 16bit write support, but the 16 bit images are only
10238 * generated if DO_16BIT is defined.
10239 */
10240#ifdef DO_16BIT
10241static void perform_gamma_scale16_tests(png_modifier *pm)
10242{
10243# ifndef PNG_MAX_GAMMA_8
10244# define PNG_MAX_GAMMA_8 11
10245# endif
Matt Sarett9ea75692016-01-08 13:00:42 -050010246# if defined PNG_MAX_GAMMA_8 || PNG_LIBPNG_VER < 10700
10247# define SBIT_16_TO_8 PNG_MAX_GAMMA_8
10248# else
10249# define SBIT_16_TO_8 16
10250# endif
Chris Craikb50c2172013-07-29 15:28:30 -070010251 /* Include the alpha cases here. Note that sbit matches the internal value
10252 * used by the library - otherwise we will get spurious errors from the
10253 * internal sbit style approximation.
10254 *
10255 * The threshold test is here because otherwise the 16 to 8 conversion will
10256 * proceed *without* gamma correction, and the tests above will fail (but not
10257 * by much) - this could be fixed, it only appears with the -g option.
10258 */
10259 unsigned int i, j;
10260 for (i=0; i<pm->ngamma_tests; ++i)
10261 {
10262 for (j=0; j<pm->ngamma_tests; ++j)
10263 {
10264 if (i != j &&
10265 fabs(pm->gammas[j]/pm->gammas[i]-1) >= PNG_GAMMA_THRESHOLD)
10266 {
10267 gamma_transform_test(pm, 0, 16, 0, pm->interlace_type,
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010268 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
Chris Craikb50c2172013-07-29 15:28:30 -070010269 pm->use_input_precision_16to8, 1 /*scale16*/);
10270
10271 if (fail(pm))
10272 return;
10273
10274 gamma_transform_test(pm, 2, 16, 0, pm->interlace_type,
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010275 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
Chris Craikb50c2172013-07-29 15:28:30 -070010276 pm->use_input_precision_16to8, 1 /*scale16*/);
10277
10278 if (fail(pm))
10279 return;
10280
10281 gamma_transform_test(pm, 4, 16, 0, pm->interlace_type,
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010282 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
Chris Craikb50c2172013-07-29 15:28:30 -070010283 pm->use_input_precision_16to8, 1 /*scale16*/);
10284
10285 if (fail(pm))
10286 return;
10287
10288 gamma_transform_test(pm, 6, 16, 0, pm->interlace_type,
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010289 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
Chris Craikb50c2172013-07-29 15:28:30 -070010290 pm->use_input_precision_16to8, 1 /*scale16*/);
10291
10292 if (fail(pm))
10293 return;
10294 }
10295 }
10296 }
10297}
10298#endif /* 16 to 8 bit conversion */
10299
10300#if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\
10301 defined(PNG_READ_ALPHA_MODE_SUPPORTED)
10302static void gamma_composition_test(png_modifier *pm,
Matt Sarett9ea75692016-01-08 13:00:42 -050010303 const png_byte colour_type, const png_byte bit_depth,
10304 const int palette_number,
10305 const int interlace_type, const double file_gamma,
10306 const double screen_gamma,
10307 const int use_input_precision, const int do_background,
10308 const int expand_16)
Chris Craikb50c2172013-07-29 15:28:30 -070010309{
10310 size_t pos = 0;
10311 png_const_charp base;
10312 double bg;
10313 char name[128];
10314 png_color_16 background;
10315
10316 /* Make up a name and get an appropriate background gamma value. */
10317 switch (do_background)
10318 {
10319 default:
10320 base = "";
10321 bg = 4; /* should not be used */
10322 break;
10323 case PNG_BACKGROUND_GAMMA_SCREEN:
10324 base = " bckg(Screen):";
10325 bg = 1/screen_gamma;
10326 break;
10327 case PNG_BACKGROUND_GAMMA_FILE:
10328 base = " bckg(File):";
10329 bg = file_gamma;
10330 break;
10331 case PNG_BACKGROUND_GAMMA_UNIQUE:
10332 base = " bckg(Unique):";
10333 /* This tests the handling of a unique value, the math is such that the
10334 * value tends to be <1, but is neither screen nor file (even if they
10335 * match!)
10336 */
10337 bg = (file_gamma + screen_gamma) / 3;
10338 break;
10339#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
10340 case ALPHA_MODE_OFFSET + PNG_ALPHA_PNG:
10341 base = " alpha(PNG)";
10342 bg = 4; /* should not be used */
10343 break;
10344 case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
10345 base = " alpha(Porter-Duff)";
10346 bg = 4; /* should not be used */
10347 break;
10348 case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
10349 base = " alpha(Optimized)";
10350 bg = 4; /* should not be used */
10351 break;
10352 case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
10353 base = " alpha(Broken)";
10354 bg = 4; /* should not be used */
10355 break;
10356#endif
10357 }
10358
10359 /* Use random background values - the background is always presented in the
10360 * output space (8 or 16 bit components).
10361 */
10362 if (expand_16 || bit_depth == 16)
10363 {
10364 png_uint_32 r = random_32();
10365
10366 background.red = (png_uint_16)r;
10367 background.green = (png_uint_16)(r >> 16);
10368 r = random_32();
10369 background.blue = (png_uint_16)r;
10370 background.gray = (png_uint_16)(r >> 16);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010371
10372 /* In earlier libpng versions, those where DIGITIZE is set, any background
10373 * gamma correction in the expand16 case was done using 8-bit gamma
10374 * correction tables, resulting in larger errors. To cope with those
10375 * cases use a 16-bit background value which will handle this gamma
10376 * correction.
10377 */
10378# if DIGITIZE
10379 if (expand_16 && (do_background == PNG_BACKGROUND_GAMMA_UNIQUE ||
10380 do_background == PNG_BACKGROUND_GAMMA_FILE) &&
10381 fabs(bg*screen_gamma-1) > PNG_GAMMA_THRESHOLD)
10382 {
10383 /* The background values will be looked up in an 8-bit table to do
10384 * the gamma correction, so only select values which are an exact
10385 * match for the 8-bit table entries:
10386 */
10387 background.red = (png_uint_16)((background.red >> 8) * 257);
10388 background.green = (png_uint_16)((background.green >> 8) * 257);
10389 background.blue = (png_uint_16)((background.blue >> 8) * 257);
10390 background.gray = (png_uint_16)((background.gray >> 8) * 257);
10391 }
10392# endif
Chris Craikb50c2172013-07-29 15:28:30 -070010393 }
10394
10395 else /* 8 bit colors */
10396 {
10397 png_uint_32 r = random_32();
10398
10399 background.red = (png_byte)r;
10400 background.green = (png_byte)(r >> 8);
10401 background.blue = (png_byte)(r >> 16);
10402 background.gray = (png_byte)(r >> 24);
10403 }
10404
10405 background.index = 193; /* rgb(193,193,193) to detect errors */
Matt Sarett9ea75692016-01-08 13:00:42 -050010406
Chris Craikb50c2172013-07-29 15:28:30 -070010407 if (!(colour_type & PNG_COLOR_MASK_COLOR))
10408 {
Matt Sarett9ea75692016-01-08 13:00:42 -050010409 /* Because, currently, png_set_background is always called with
10410 * 'need_expand' false in this case and because the gamma test itself
10411 * doesn't cause an expand to 8-bit for lower bit depths the colour must
10412 * be reduced to the correct range.
10413 */
10414 if (bit_depth < 8)
10415 background.gray &= (png_uint_16)((1U << bit_depth)-1);
10416
Chris Craikb50c2172013-07-29 15:28:30 -070010417 /* Grayscale input, we do not convert to RGB (TBD), so we must set the
10418 * background to gray - else libpng seems to fail.
10419 */
10420 background.red = background.green = background.blue = background.gray;
10421 }
10422
10423 pos = safecat(name, sizeof name, pos, "gamma ");
10424 pos = safecatd(name, sizeof name, pos, file_gamma, 3);
10425 pos = safecat(name, sizeof name, pos, "->");
10426 pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
10427
10428 pos = safecat(name, sizeof name, pos, base);
10429 if (do_background < ALPHA_MODE_OFFSET)
10430 {
10431 /* Include the background color and gamma in the name: */
10432 pos = safecat(name, sizeof name, pos, "(");
10433 /* This assumes no expand gray->rgb - the current code won't handle that!
10434 */
10435 if (colour_type & PNG_COLOR_MASK_COLOR)
10436 {
10437 pos = safecatn(name, sizeof name, pos, background.red);
10438 pos = safecat(name, sizeof name, pos, ",");
10439 pos = safecatn(name, sizeof name, pos, background.green);
10440 pos = safecat(name, sizeof name, pos, ",");
10441 pos = safecatn(name, sizeof name, pos, background.blue);
10442 }
10443 else
10444 pos = safecatn(name, sizeof name, pos, background.gray);
10445 pos = safecat(name, sizeof name, pos, ")^");
10446 pos = safecatd(name, sizeof name, pos, bg, 3);
10447 }
10448
10449 gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
10450 file_gamma, screen_gamma, 0/*sBIT*/, 0, name, use_input_precision,
10451 0/*strip 16*/, expand_16, do_background, &background, bg);
10452}
10453
10454
10455static void
10456perform_gamma_composition_tests(png_modifier *pm, int do_background,
10457 int expand_16)
10458{
10459 png_byte colour_type = 0;
10460 png_byte bit_depth = 0;
10461 unsigned int palette_number = 0;
10462
10463 /* Skip the non-alpha cases - there is no setting of a transparency colour at
10464 * present.
Matt Sarett9ea75692016-01-08 13:00:42 -050010465 *
10466 * TODO: incorrect; the palette case sets tRNS and, now RGB and gray do,
10467 * however the palette case fails miserably so is commented out below.
Chris Craikb50c2172013-07-29 15:28:30 -070010468 */
Matt Sarett9ea75692016-01-08 13:00:42 -050010469 while (next_format(&colour_type, &bit_depth, &palette_number,
10470 pm->test_lbg_gamma_composition, pm->test_tRNS))
10471 if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0
10472#if 0 /* TODO: FIXME */
10473 /*TODO: FIXME: this should work */
10474 || colour_type == 3
10475#endif
10476 || (colour_type != 3 && palette_number != 0))
Chris Craikb50c2172013-07-29 15:28:30 -070010477 {
10478 unsigned int i, j;
10479
10480 /* Don't skip the i==j case here - it's relevant. */
10481 for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
10482 {
10483 gamma_composition_test(pm, colour_type, bit_depth, palette_number,
10484 pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
10485 pm->use_input_precision, do_background, expand_16);
10486
10487 if (fail(pm))
10488 return;
10489 }
10490 }
10491}
10492#endif /* READ_BACKGROUND || READ_ALPHA_MODE */
10493
10494static void
10495init_gamma_errors(png_modifier *pm)
10496{
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010497 /* Use -1 to catch tests that were not actually run */
10498 pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = -1.;
10499 pm->error_color_8 = -1.;
10500 pm->error_indexed = -1.;
10501 pm->error_gray_16 = pm->error_color_16 = -1.;
Chris Craikb50c2172013-07-29 15:28:30 -070010502}
10503
10504static void
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010505print_one(const char *leader, double err)
Chris Craikb50c2172013-07-29 15:28:30 -070010506{
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010507 if (err != -1.)
10508 printf(" %s %.5f\n", leader, err);
10509}
10510
10511static void
10512summarize_gamma_errors(png_modifier *pm, png_const_charp who, int low_bit_depth,
10513 int indexed)
10514{
10515 fflush(stderr);
10516
Chris Craikb50c2172013-07-29 15:28:30 -070010517 if (who)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010518 printf("\nGamma correction with %s:\n", who);
10519
10520 else
10521 printf("\nBasic gamma correction:\n");
Chris Craikb50c2172013-07-29 15:28:30 -070010522
10523 if (low_bit_depth)
10524 {
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010525 print_one(" 2 bit gray: ", pm->error_gray_2);
10526 print_one(" 4 bit gray: ", pm->error_gray_4);
10527 print_one(" 8 bit gray: ", pm->error_gray_8);
10528 print_one(" 8 bit color:", pm->error_color_8);
10529 if (indexed)
10530 print_one(" indexed: ", pm->error_indexed);
Chris Craikb50c2172013-07-29 15:28:30 -070010531 }
10532
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010533 print_one("16 bit gray: ", pm->error_gray_16);
10534 print_one("16 bit color:", pm->error_color_16);
10535
10536 fflush(stdout);
Chris Craikb50c2172013-07-29 15:28:30 -070010537}
10538
10539static void
10540perform_gamma_test(png_modifier *pm, int summary)
10541{
10542 /*TODO: remove this*/
10543 /* Save certain values for the temporary overrides below. */
10544 unsigned int calculations_use_input_precision =
10545 pm->calculations_use_input_precision;
10546# ifdef PNG_READ_BACKGROUND_SUPPORTED
10547 double maxout8 = pm->maxout8;
10548# endif
10549
10550 /* First some arbitrary no-transform tests: */
10551 if (!pm->this.speed && pm->test_gamma_threshold)
10552 {
10553 perform_gamma_threshold_tests(pm);
10554
10555 if (fail(pm))
10556 return;
10557 }
10558
10559 /* Now some real transforms. */
10560 if (pm->test_gamma_transform)
10561 {
Chris Craikb50c2172013-07-29 15:28:30 -070010562 if (summary)
10563 {
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010564 fflush(stderr);
Chris Craikb50c2172013-07-29 15:28:30 -070010565 printf("Gamma correction error summary\n\n");
10566 printf("The printed value is the maximum error in the pixel values\n");
10567 printf("calculated by the libpng gamma correction code. The error\n");
10568 printf("is calculated as the difference between the output pixel\n");
10569 printf("value (always an integer) and the ideal value from the\n");
10570 printf("libpng specification (typically not an integer).\n\n");
10571
10572 printf("Expect this value to be less than .5 for 8 bit formats,\n");
10573 printf("less than 1 for formats with fewer than 8 bits and a small\n");
10574 printf("number (typically less than 5) for the 16 bit formats.\n");
10575 printf("For performance reasons the value for 16 bit formats\n");
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010576 printf("increases when the image file includes an sBIT chunk.\n");
10577 fflush(stdout);
Chris Craikb50c2172013-07-29 15:28:30 -070010578 }
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010579
10580 init_gamma_errors(pm);
10581 /*TODO: remove this. Necessary because the current libpng
10582 * implementation works in 8 bits:
10583 */
10584 if (pm->test_gamma_expand16)
10585 pm->calculations_use_input_precision = 1;
10586 perform_gamma_transform_tests(pm);
10587 if (!calculations_use_input_precision)
10588 pm->calculations_use_input_precision = 0;
10589
10590 if (summary)
10591 summarize_gamma_errors(pm, 0/*who*/, 1/*low bit depth*/, 1/*indexed*/);
10592
10593 if (fail(pm))
10594 return;
Chris Craikb50c2172013-07-29 15:28:30 -070010595 }
10596
10597 /* The sbit tests produce much larger errors: */
10598 if (pm->test_gamma_sbit)
10599 {
10600 init_gamma_errors(pm);
10601 perform_gamma_sbit_tests(pm);
10602
10603 if (summary)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010604 summarize_gamma_errors(pm, "sBIT", pm->sbitlow < 8U, 1/*indexed*/);
10605
10606 if (fail(pm))
10607 return;
Chris Craikb50c2172013-07-29 15:28:30 -070010608 }
10609
10610#ifdef DO_16BIT /* Should be READ_16BIT_SUPPORTED */
10611 if (pm->test_gamma_scale16)
10612 {
10613 /* The 16 to 8 bit strip operations: */
10614 init_gamma_errors(pm);
10615 perform_gamma_scale16_tests(pm);
10616
10617 if (summary)
10618 {
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010619 fflush(stderr);
10620 printf("\nGamma correction with 16 to 8 bit reduction:\n");
Chris Craikb50c2172013-07-29 15:28:30 -070010621 printf(" 16 bit gray: %.5f\n", pm->error_gray_16);
10622 printf(" 16 bit color: %.5f\n", pm->error_color_16);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010623 fflush(stdout);
Chris Craikb50c2172013-07-29 15:28:30 -070010624 }
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010625
10626 if (fail(pm))
10627 return;
Chris Craikb50c2172013-07-29 15:28:30 -070010628 }
10629#endif
10630
10631#ifdef PNG_READ_BACKGROUND_SUPPORTED
10632 if (pm->test_gamma_background)
10633 {
10634 init_gamma_errors(pm);
10635
10636 /*TODO: remove this. Necessary because the current libpng
10637 * implementation works in 8 bits:
10638 */
10639 if (pm->test_gamma_expand16)
10640 {
10641 pm->calculations_use_input_precision = 1;
10642 pm->maxout8 = .499; /* because the 16 bit background is smashed */
10643 }
10644 perform_gamma_composition_tests(pm, PNG_BACKGROUND_GAMMA_UNIQUE,
10645 pm->test_gamma_expand16);
10646 if (!calculations_use_input_precision)
10647 pm->calculations_use_input_precision = 0;
10648 pm->maxout8 = maxout8;
10649
10650 if (summary)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010651 summarize_gamma_errors(pm, "background", 1, 0/*indexed*/);
10652
10653 if (fail(pm))
10654 return;
Chris Craikb50c2172013-07-29 15:28:30 -070010655 }
10656#endif
10657
10658#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
10659 if (pm->test_gamma_alpha_mode)
10660 {
10661 int do_background;
10662
10663 init_gamma_errors(pm);
10664
10665 /*TODO: remove this. Necessary because the current libpng
10666 * implementation works in 8 bits:
10667 */
10668 if (pm->test_gamma_expand16)
10669 pm->calculations_use_input_precision = 1;
10670 for (do_background = ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD;
10671 do_background <= ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN && !fail(pm);
10672 ++do_background)
10673 perform_gamma_composition_tests(pm, do_background,
10674 pm->test_gamma_expand16);
10675 if (!calculations_use_input_precision)
10676 pm->calculations_use_input_precision = 0;
10677
10678 if (summary)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010679 summarize_gamma_errors(pm, "alpha mode", 1, 0/*indexed*/);
10680
10681 if (fail(pm))
10682 return;
Chris Craikb50c2172013-07-29 15:28:30 -070010683 }
10684#endif
10685}
10686#endif /* PNG_READ_GAMMA_SUPPORTED */
10687#endif /* PNG_READ_SUPPORTED */
10688
10689/* INTERLACE MACRO VALIDATION */
10690/* This is copied verbatim from the specification, it is simply the pass
10691 * number in which each pixel in each 8x8 tile appears. The array must
10692 * be indexed adam7[y][x] and notice that the pass numbers are based at
10693 * 1, not 0 - the base libpng uses.
10694 */
Matt Sarett9ea75692016-01-08 13:00:42 -050010695static const
Chris Craikb50c2172013-07-29 15:28:30 -070010696png_byte adam7[8][8] =
10697{
10698 { 1,6,4,6,2,6,4,6 },
10699 { 7,7,7,7,7,7,7,7 },
10700 { 5,6,5,6,5,6,5,6 },
10701 { 7,7,7,7,7,7,7,7 },
10702 { 3,6,4,6,3,6,4,6 },
10703 { 7,7,7,7,7,7,7,7 },
10704 { 5,6,5,6,5,6,5,6 },
10705 { 7,7,7,7,7,7,7,7 }
10706};
10707
10708/* This routine validates all the interlace support macros in png.h for
10709 * a variety of valid PNG widths and heights. It uses a number of similarly
10710 * named internal routines that feed off the above array.
10711 */
10712static png_uint_32
10713png_pass_start_row(int pass)
10714{
10715 int x, y;
10716 ++pass;
10717 for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
10718 return y;
10719 return 0xf;
10720}
10721
10722static png_uint_32
10723png_pass_start_col(int pass)
10724{
10725 int x, y;
10726 ++pass;
10727 for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
10728 return x;
10729 return 0xf;
10730}
10731
10732static int
10733png_pass_row_shift(int pass)
10734{
10735 int x, y, base=(-1), inc=8;
10736 ++pass;
10737 for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
10738 {
10739 if (base == (-1))
10740 base = y;
10741 else if (base == y)
10742 {}
10743 else if (inc == y-base)
10744 base=y;
10745 else if (inc == 8)
10746 inc = y-base, base=y;
10747 else if (inc != y-base)
10748 return 0xff; /* error - more than one 'inc' value! */
10749 }
10750
10751 if (base == (-1)) return 0xfe; /* error - no row in pass! */
10752
10753 /* The shift is always 1, 2 or 3 - no pass has all the rows! */
10754 switch (inc)
10755 {
10756case 2: return 1;
10757case 4: return 2;
10758case 8: return 3;
10759default: break;
10760 }
10761
10762 /* error - unrecognized 'inc' */
10763 return (inc << 8) + 0xfd;
10764}
10765
10766static int
10767png_pass_col_shift(int pass)
10768{
10769 int x, y, base=(-1), inc=8;
10770 ++pass;
10771 for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
10772 {
10773 if (base == (-1))
10774 base = x;
10775 else if (base == x)
10776 {}
10777 else if (inc == x-base)
10778 base=x;
10779 else if (inc == 8)
10780 inc = x-base, base=x;
10781 else if (inc != x-base)
10782 return 0xff; /* error - more than one 'inc' value! */
10783 }
10784
10785 if (base == (-1)) return 0xfe; /* error - no row in pass! */
10786
10787 /* The shift is always 1, 2 or 3 - no pass has all the rows! */
10788 switch (inc)
10789 {
10790case 1: return 0; /* pass 7 has all the columns */
10791case 2: return 1;
10792case 4: return 2;
10793case 8: return 3;
10794default: break;
10795 }
10796
10797 /* error - unrecognized 'inc' */
10798 return (inc << 8) + 0xfd;
10799}
10800
10801static png_uint_32
10802png_row_from_pass_row(png_uint_32 yIn, int pass)
10803{
10804 /* By examination of the array: */
10805 switch (pass)
10806 {
10807case 0: return yIn * 8;
10808case 1: return yIn * 8;
10809case 2: return yIn * 8 + 4;
10810case 3: return yIn * 4;
10811case 4: return yIn * 4 + 2;
10812case 5: return yIn * 2;
10813case 6: return yIn * 2 + 1;
10814default: break;
10815 }
10816
10817 return 0xff; /* bad pass number */
10818}
10819
10820static png_uint_32
10821png_col_from_pass_col(png_uint_32 xIn, int pass)
10822{
10823 /* By examination of the array: */
10824 switch (pass)
10825 {
10826case 0: return xIn * 8;
10827case 1: return xIn * 8 + 4;
10828case 2: return xIn * 4;
10829case 3: return xIn * 4 + 2;
10830case 4: return xIn * 2;
10831case 5: return xIn * 2 + 1;
10832case 6: return xIn;
10833default: break;
10834 }
10835
10836 return 0xff; /* bad pass number */
10837}
10838
10839static int
10840png_row_in_interlace_pass(png_uint_32 y, int pass)
10841{
10842 /* Is row 'y' in pass 'pass'? */
10843 int x;
10844 y &= 7;
10845 ++pass;
10846 for (x=0; x<8; ++x) if (adam7[y][x] == pass)
10847 return 1;
10848
10849 return 0;
10850}
10851
10852static int
10853png_col_in_interlace_pass(png_uint_32 x, int pass)
10854{
10855 /* Is column 'x' in pass 'pass'? */
10856 int y;
10857 x &= 7;
10858 ++pass;
10859 for (y=0; y<8; ++y) if (adam7[y][x] == pass)
10860 return 1;
10861
10862 return 0;
10863}
10864
10865static png_uint_32
10866png_pass_rows(png_uint_32 height, int pass)
10867{
10868 png_uint_32 tiles = height>>3;
10869 png_uint_32 rows = 0;
10870 unsigned int x, y;
10871
10872 height &= 7;
10873 ++pass;
10874 for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
10875 {
10876 rows += tiles;
10877 if (y < height) ++rows;
10878 break; /* i.e. break the 'x', column, loop. */
10879 }
10880
10881 return rows;
10882}
10883
10884static png_uint_32
10885png_pass_cols(png_uint_32 width, int pass)
10886{
10887 png_uint_32 tiles = width>>3;
10888 png_uint_32 cols = 0;
10889 unsigned int x, y;
10890
10891 width &= 7;
10892 ++pass;
10893 for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
10894 {
10895 cols += tiles;
10896 if (x < width) ++cols;
10897 break; /* i.e. break the 'y', row, loop. */
10898 }
10899
10900 return cols;
10901}
10902
10903static void
10904perform_interlace_macro_validation(void)
10905{
10906 /* The macros to validate, first those that depend only on pass:
10907 *
10908 * PNG_PASS_START_ROW(pass)
10909 * PNG_PASS_START_COL(pass)
10910 * PNG_PASS_ROW_SHIFT(pass)
10911 * PNG_PASS_COL_SHIFT(pass)
10912 */
10913 int pass;
10914
10915 for (pass=0; pass<7; ++pass)
10916 {
10917 png_uint_32 m, f, v;
10918
10919 m = PNG_PASS_START_ROW(pass);
10920 f = png_pass_start_row(pass);
10921 if (m != f)
10922 {
10923 fprintf(stderr, "PNG_PASS_START_ROW(%d) = %u != %x\n", pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010924 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070010925 }
10926
10927 m = PNG_PASS_START_COL(pass);
10928 f = png_pass_start_col(pass);
10929 if (m != f)
10930 {
10931 fprintf(stderr, "PNG_PASS_START_COL(%d) = %u != %x\n", pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010932 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070010933 }
10934
10935 m = PNG_PASS_ROW_SHIFT(pass);
10936 f = png_pass_row_shift(pass);
10937 if (m != f)
10938 {
10939 fprintf(stderr, "PNG_PASS_ROW_SHIFT(%d) = %u != %x\n", pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010940 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070010941 }
10942
10943 m = PNG_PASS_COL_SHIFT(pass);
10944 f = png_pass_col_shift(pass);
10945 if (m != f)
10946 {
10947 fprintf(stderr, "PNG_PASS_COL_SHIFT(%d) = %u != %x\n", pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010948 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070010949 }
10950
10951 /* Macros that depend on the image or sub-image height too:
10952 *
10953 * PNG_PASS_ROWS(height, pass)
10954 * PNG_PASS_COLS(width, pass)
10955 * PNG_ROW_FROM_PASS_ROW(yIn, pass)
10956 * PNG_COL_FROM_PASS_COL(xIn, pass)
10957 * PNG_ROW_IN_INTERLACE_PASS(y, pass)
10958 * PNG_COL_IN_INTERLACE_PASS(x, pass)
10959 */
10960 for (v=0;;)
10961 {
10962 /* First the base 0 stuff: */
10963 m = PNG_ROW_FROM_PASS_ROW(v, pass);
10964 f = png_row_from_pass_row(v, pass);
10965 if (m != f)
10966 {
10967 fprintf(stderr, "PNG_ROW_FROM_PASS_ROW(%u, %d) = %u != %x\n",
10968 v, pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010969 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070010970 }
10971
10972 m = PNG_COL_FROM_PASS_COL(v, pass);
10973 f = png_col_from_pass_col(v, pass);
10974 if (m != f)
10975 {
10976 fprintf(stderr, "PNG_COL_FROM_PASS_COL(%u, %d) = %u != %x\n",
10977 v, pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010978 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070010979 }
10980
10981 m = PNG_ROW_IN_INTERLACE_PASS(v, pass);
10982 f = png_row_in_interlace_pass(v, pass);
10983 if (m != f)
10984 {
10985 fprintf(stderr, "PNG_ROW_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
10986 v, pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010987 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070010988 }
10989
10990 m = PNG_COL_IN_INTERLACE_PASS(v, pass);
10991 f = png_col_in_interlace_pass(v, pass);
10992 if (m != f)
10993 {
10994 fprintf(stderr, "PNG_COL_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
10995 v, pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010996 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070010997 }
10998
10999 /* Then the base 1 stuff: */
11000 ++v;
11001 m = PNG_PASS_ROWS(v, pass);
11002 f = png_pass_rows(v, pass);
11003 if (m != f)
11004 {
11005 fprintf(stderr, "PNG_PASS_ROWS(%u, %d) = %u != %x\n",
11006 v, pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011007 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070011008 }
11009
11010 m = PNG_PASS_COLS(v, pass);
11011 f = png_pass_cols(v, pass);
11012 if (m != f)
11013 {
11014 fprintf(stderr, "PNG_PASS_COLS(%u, %d) = %u != %x\n",
11015 v, pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011016 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070011017 }
11018
11019 /* Move to the next v - the stepping algorithm starts skipping
11020 * values above 1024.
11021 */
11022 if (v > 1024)
11023 {
11024 if (v == PNG_UINT_31_MAX)
11025 break;
11026
11027 v = (v << 1) ^ v;
11028 if (v >= PNG_UINT_31_MAX)
11029 v = PNG_UINT_31_MAX-1;
11030 }
11031 }
11032 }
11033}
11034
11035/* Test color encodings. These values are back-calculated from the published
11036 * chromaticities. The values are accurate to about 14 decimal places; 15 are
11037 * given. These values are much more accurate than the ones given in the spec,
11038 * which typically don't exceed 4 decimal places. This allows testing of the
11039 * libpng code to its theoretical accuracy of 4 decimal places. (If pngvalid
11040 * used the published errors the 'slack' permitted would have to be +/-.5E-4 or
11041 * more.)
11042 *
11043 * The png_modifier code assumes that encodings[0] is sRGB and treats it
11044 * specially: do not change the first entry in this list!
11045 */
Matt Sarett9ea75692016-01-08 13:00:42 -050011046static const color_encoding test_encodings[] =
Chris Craikb50c2172013-07-29 15:28:30 -070011047{
11048/* sRGB: must be first in this list! */
11049/*gamma:*/ { 1/2.2,
11050/*red: */ { 0.412390799265959, 0.212639005871510, 0.019330818715592 },
11051/*green:*/ { 0.357584339383878, 0.715168678767756, 0.119194779794626 },
11052/*blue: */ { 0.180480788401834, 0.072192315360734, 0.950532152249660} },
11053/* Kodak ProPhoto (wide gamut) */
11054/*gamma:*/ { 1/1.6 /*approximate: uses 1.8 power law compared to sRGB 2.4*/,
11055/*red: */ { 0.797760489672303, 0.288071128229293, 0.000000000000000 },
11056/*green:*/ { 0.135185837175740, 0.711843217810102, 0.000000000000000 },
11057/*blue: */ { 0.031349349581525, 0.000085653960605, 0.825104602510460} },
11058/* Adobe RGB (1998) */
11059/*gamma:*/ { 1/(2+51./256),
11060/*red: */ { 0.576669042910131, 0.297344975250536, 0.027031361386412 },
11061/*green:*/ { 0.185558237906546, 0.627363566255466, 0.070688852535827 },
11062/*blue: */ { 0.188228646234995, 0.075291458493998, 0.991337536837639} },
11063/* Adobe Wide Gamut RGB */
11064/*gamma:*/ { 1/(2+51./256),
11065/*red: */ { 0.716500716779386, 0.258728243040113, 0.000000000000000 },
11066/*green:*/ { 0.101020574397477, 0.724682314948566, 0.051211818965388 },
11067/*blue: */ { 0.146774385252705, 0.016589442011321, 0.773892783545073} },
Matt Sarett9ea75692016-01-08 13:00:42 -050011068/* Fake encoding which selects just the green channel */
11069/*gamma:*/ { 1.45/2.2, /* the 'Mac' gamma */
11070/*red: */ { 0.716500716779386, 0.000000000000000, 0.000000000000000 },
11071/*green:*/ { 0.101020574397477, 1.000000000000000, 0.051211818965388 },
11072/*blue: */ { 0.146774385252705, 0.000000000000000, 0.773892783545073} },
Chris Craikb50c2172013-07-29 15:28:30 -070011073};
11074
11075/* signal handler
11076 *
11077 * This attempts to trap signals and escape without crashing. It needs a
11078 * context pointer so that it can throw an exception (call longjmp) to recover
11079 * from the condition; this is handled by making the png_modifier used by 'main'
11080 * into a global variable.
11081 */
11082static png_modifier pm;
11083
11084static void signal_handler(int signum)
11085{
11086
11087 size_t pos = 0;
11088 char msg[64];
11089
11090 pos = safecat(msg, sizeof msg, pos, "caught signal: ");
11091
11092 switch (signum)
11093 {
11094 case SIGABRT:
11095 pos = safecat(msg, sizeof msg, pos, "abort");
11096 break;
11097
11098 case SIGFPE:
11099 pos = safecat(msg, sizeof msg, pos, "floating point exception");
11100 break;
11101
11102 case SIGILL:
11103 pos = safecat(msg, sizeof msg, pos, "illegal instruction");
11104 break;
11105
11106 case SIGINT:
11107 pos = safecat(msg, sizeof msg, pos, "interrupt");
11108 break;
11109
11110 case SIGSEGV:
11111 pos = safecat(msg, sizeof msg, pos, "invalid memory access");
11112 break;
11113
11114 case SIGTERM:
11115 pos = safecat(msg, sizeof msg, pos, "termination request");
11116 break;
11117
11118 default:
11119 pos = safecat(msg, sizeof msg, pos, "unknown ");
11120 pos = safecatn(msg, sizeof msg, pos, signum);
11121 break;
11122 }
11123
11124 store_log(&pm.this, NULL/*png_structp*/, msg, 1/*error*/);
11125
11126 /* And finally throw an exception so we can keep going, unless this is
11127 * SIGTERM in which case stop now.
11128 */
11129 if (signum != SIGTERM)
11130 {
11131 struct exception_context *the_exception_context =
11132 &pm.this.exception_context;
11133
11134 Throw &pm.this;
11135 }
11136
11137 else
11138 exit(1);
11139}
11140
11141/* main program */
11142int main(int argc, char **argv)
11143{
Matt Sarett9ea75692016-01-08 13:00:42 -050011144 int summary = 1; /* Print the error summary at the end */
11145 int memstats = 0; /* Print memory statistics at the end */
Chris Craikb50c2172013-07-29 15:28:30 -070011146
11147 /* Create the given output file on success: */
Matt Sarett9ea75692016-01-08 13:00:42 -050011148 const char *touch = NULL;
Chris Craikb50c2172013-07-29 15:28:30 -070011149
11150 /* This is an array of standard gamma values (believe it or not I've seen
11151 * every one of these mentioned somewhere.)
11152 *
11153 * In the following list the most useful values are first!
11154 */
11155 static double
11156 gammas[]={2.2, 1.0, 2.2/1.45, 1.8, 1.5, 2.4, 2.5, 2.62, 2.9};
11157
11158 /* This records the command and arguments: */
11159 size_t cp = 0;
11160 char command[1024];
11161
11162 anon_context(&pm.this);
11163
Matt Sarett9ea75692016-01-08 13:00:42 -050011164 gnu_volatile(summary)
11165 gnu_volatile(memstats)
11166 gnu_volatile(touch)
11167
Chris Craikb50c2172013-07-29 15:28:30 -070011168 /* Add appropriate signal handlers, just the ANSI specified ones: */
11169 signal(SIGABRT, signal_handler);
11170 signal(SIGFPE, signal_handler);
11171 signal(SIGILL, signal_handler);
11172 signal(SIGINT, signal_handler);
11173 signal(SIGSEGV, signal_handler);
11174 signal(SIGTERM, signal_handler);
11175
11176#ifdef HAVE_FEENABLEEXCEPT
11177 /* Only required to enable FP exceptions on platforms where they start off
11178 * disabled; this is not necessary but if it is not done pngvalid will likely
11179 * end up ignoring FP conditions that other platforms fault.
11180 */
11181 feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
11182#endif
11183
11184 modifier_init(&pm);
11185
11186 /* Preallocate the image buffer, because we know how big it needs to be,
11187 * note that, for testing purposes, it is deliberately mis-aligned by tag
11188 * bytes either side. All rows have an additional five bytes of padding for
11189 * overwrite checking.
11190 */
11191 store_ensure_image(&pm.this, NULL, 2, TRANSFORM_ROWMAX, TRANSFORM_HEIGHTMAX);
11192
11193 /* Don't give argv[0], it's normally some horrible libtool string: */
11194 cp = safecat(command, sizeof command, cp, "pngvalid");
11195
11196 /* Default to error on warning: */
11197 pm.this.treat_warnings_as_errors = 1;
11198
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011199 /* Default assume_16_bit_calculations appropriately; this tells the checking
11200 * code that 16-bit arithmetic is used for 8-bit samples when it would make a
11201 * difference.
11202 */
11203 pm.assume_16_bit_calculations = PNG_LIBPNG_VER >= 10700;
11204
11205 /* Currently 16 bit expansion happens at the end of the pipeline, so the
11206 * calculations are done in the input bit depth not the output.
11207 *
11208 * TODO: fix this
11209 */
11210 pm.calculations_use_input_precision = 1U;
11211
Chris Craikb50c2172013-07-29 15:28:30 -070011212 /* Store the test gammas */
11213 pm.gammas = gammas;
Matt Sarett9ea75692016-01-08 13:00:42 -050011214 pm.ngammas = ARRAY_SIZE(gammas);
Chris Craikb50c2172013-07-29 15:28:30 -070011215 pm.ngamma_tests = 0; /* default to off */
11216
Matt Sarett9ea75692016-01-08 13:00:42 -050011217 /* Low bit depth gray images don't do well in the gamma tests, until
11218 * this is fixed turn them off for some gamma cases:
11219 */
11220# ifdef PNG_WRITE_tRNS_SUPPORTED
11221 pm.test_tRNS = 1;
11222# endif
11223 pm.test_lbg = PNG_LIBPNG_VER >= 10600;
11224 pm.test_lbg_gamma_threshold = 1;
11225 pm.test_lbg_gamma_transform = PNG_LIBPNG_VER >= 10600;
11226 pm.test_lbg_gamma_sbit = 1;
11227 pm.test_lbg_gamma_composition = PNG_LIBPNG_VER >= 10700;
11228
Chris Craikb50c2172013-07-29 15:28:30 -070011229 /* And the test encodings */
11230 pm.encodings = test_encodings;
Matt Sarett9ea75692016-01-08 13:00:42 -050011231 pm.nencodings = ARRAY_SIZE(test_encodings);
Chris Craikb50c2172013-07-29 15:28:30 -070011232
Matt Sarett9ea75692016-01-08 13:00:42 -050011233# if PNG_LIBPNG_VER < 10700
11234 pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */
11235# else
11236 pm.sbitlow = 1U;
11237# endif
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011238
Chris Craikb50c2172013-07-29 15:28:30 -070011239 /* The following allows results to pass if they correspond to anything in the
11240 * transformed range [input-.5,input+.5]; this is is required because of the
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011241 * way libpng treates the 16_TO_8 flag when building the gamma tables in
11242 * releases up to 1.6.0.
Chris Craikb50c2172013-07-29 15:28:30 -070011243 *
11244 * TODO: review this
11245 */
11246 pm.use_input_precision_16to8 = 1U;
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011247 pm.use_input_precision_sbit = 1U; /* because libpng now rounds sBIT */
Chris Craikb50c2172013-07-29 15:28:30 -070011248
11249 /* Some default values (set the behavior for 'make check' here).
11250 * These values simply control the maximum error permitted in the gamma
11251 * transformations. The practial limits for human perception are described
11252 * below (the setting for maxpc16), however for 8 bit encodings it isn't
11253 * possible to meet the accepted capabilities of human vision - i.e. 8 bit
11254 * images can never be good enough, regardless of encoding.
11255 */
11256 pm.maxout8 = .1; /* Arithmetic error in *encoded* value */
11257 pm.maxabs8 = .00005; /* 1/20000 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011258 pm.maxcalc8 = 1./255; /* +/-1 in 8 bits for compose errors */
Chris Craikb50c2172013-07-29 15:28:30 -070011259 pm.maxpc8 = .499; /* I.e., .499% fractional error */
11260 pm.maxout16 = .499; /* Error in *encoded* value */
11261 pm.maxabs16 = .00005;/* 1/20000 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011262 pm.maxcalc16 =1./65535;/* +/-1 in 16 bits for compose errors */
Matt Sarett9ea75692016-01-08 13:00:42 -050011263# if PNG_LIBPNG_VER < 10700
11264 pm.maxcalcG = 1./((1<<PNG_MAX_GAMMA_8)-1);
11265# else
11266 pm.maxcalcG = 1./((1<<16)-1);
11267# endif
Chris Craikb50c2172013-07-29 15:28:30 -070011268
11269 /* NOTE: this is a reasonable perceptual limit. We assume that humans can
11270 * perceive light level differences of 1% over a 100:1 range, so we need to
11271 * maintain 1 in 10000 accuracy (in linear light space), which is what the
11272 * following guarantees. It also allows significantly higher errors at
11273 * higher 16 bit values, which is important for performance. The actual
11274 * maximum 16 bit error is about +/-1.9 in the fixed point implementation but
11275 * this is only allowed for values >38149 by the following:
11276 */
11277 pm.maxpc16 = .005; /* I.e., 1/200% - 1/20000 */
11278
11279 /* Now parse the command line options. */
11280 while (--argc >= 1)
11281 {
11282 int catmore = 0; /* Set if the argument has an argument. */
11283
11284 /* Record each argument for posterity: */
11285 cp = safecat(command, sizeof command, cp, " ");
11286 cp = safecat(command, sizeof command, cp, *++argv);
11287
11288 if (strcmp(*argv, "-v") == 0)
11289 pm.this.verbose = 1;
11290
11291 else if (strcmp(*argv, "-l") == 0)
11292 pm.log = 1;
11293
11294 else if (strcmp(*argv, "-q") == 0)
11295 summary = pm.this.verbose = pm.log = 0;
11296
Matt Sarett9ea75692016-01-08 13:00:42 -050011297 else if (strcmp(*argv, "-w") == 0 ||
11298 strcmp(*argv, "--strict") == 0)
Chris Craikb50c2172013-07-29 15:28:30 -070011299 pm.this.treat_warnings_as_errors = 0;
11300
11301 else if (strcmp(*argv, "--speed") == 0)
11302 pm.this.speed = 1, pm.ngamma_tests = pm.ngammas, pm.test_standard = 0,
11303 summary = 0;
11304
11305 else if (strcmp(*argv, "--memory") == 0)
11306 memstats = 1;
11307
11308 else if (strcmp(*argv, "--size") == 0)
11309 pm.test_size = 1;
11310
11311 else if (strcmp(*argv, "--nosize") == 0)
11312 pm.test_size = 0;
11313
11314 else if (strcmp(*argv, "--standard") == 0)
11315 pm.test_standard = 1;
11316
11317 else if (strcmp(*argv, "--nostandard") == 0)
11318 pm.test_standard = 0;
11319
11320 else if (strcmp(*argv, "--transform") == 0)
11321 pm.test_transform = 1;
11322
11323 else if (strcmp(*argv, "--notransform") == 0)
11324 pm.test_transform = 0;
11325
11326#ifdef PNG_READ_TRANSFORMS_SUPPORTED
11327 else if (strncmp(*argv, "--transform-disable=",
11328 sizeof "--transform-disable") == 0)
11329 {
11330 pm.test_transform = 1;
11331 transform_disable(*argv + sizeof "--transform-disable");
11332 }
11333
11334 else if (strncmp(*argv, "--transform-enable=",
11335 sizeof "--transform-enable") == 0)
11336 {
11337 pm.test_transform = 1;
11338 transform_enable(*argv + sizeof "--transform-enable");
11339 }
11340#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
11341
11342 else if (strcmp(*argv, "--gamma") == 0)
11343 {
11344 /* Just do two gamma tests here (2.2 and linear) for speed: */
11345 pm.ngamma_tests = 2U;
11346 pm.test_gamma_threshold = 1;
11347 pm.test_gamma_transform = 1;
11348 pm.test_gamma_sbit = 1;
11349 pm.test_gamma_scale16 = 1;
Matt Sarett9ea75692016-01-08 13:00:42 -050011350 pm.test_gamma_background = 1; /* composition */
Chris Craikb50c2172013-07-29 15:28:30 -070011351 pm.test_gamma_alpha_mode = 1;
11352 }
11353
11354 else if (strcmp(*argv, "--nogamma") == 0)
11355 pm.ngamma_tests = 0;
11356
11357 else if (strcmp(*argv, "--gamma-threshold") == 0)
11358 pm.ngamma_tests = 2U, pm.test_gamma_threshold = 1;
11359
11360 else if (strcmp(*argv, "--nogamma-threshold") == 0)
11361 pm.test_gamma_threshold = 0;
11362
11363 else if (strcmp(*argv, "--gamma-transform") == 0)
11364 pm.ngamma_tests = 2U, pm.test_gamma_transform = 1;
11365
11366 else if (strcmp(*argv, "--nogamma-transform") == 0)
11367 pm.test_gamma_transform = 0;
11368
11369 else if (strcmp(*argv, "--gamma-sbit") == 0)
11370 pm.ngamma_tests = 2U, pm.test_gamma_sbit = 1;
11371
11372 else if (strcmp(*argv, "--nogamma-sbit") == 0)
11373 pm.test_gamma_sbit = 0;
11374
11375 else if (strcmp(*argv, "--gamma-16-to-8") == 0)
11376 pm.ngamma_tests = 2U, pm.test_gamma_scale16 = 1;
11377
11378 else if (strcmp(*argv, "--nogamma-16-to-8") == 0)
11379 pm.test_gamma_scale16 = 0;
11380
11381 else if (strcmp(*argv, "--gamma-background") == 0)
11382 pm.ngamma_tests = 2U, pm.test_gamma_background = 1;
11383
11384 else if (strcmp(*argv, "--nogamma-background") == 0)
11385 pm.test_gamma_background = 0;
11386
11387 else if (strcmp(*argv, "--gamma-alpha-mode") == 0)
11388 pm.ngamma_tests = 2U, pm.test_gamma_alpha_mode = 1;
11389
11390 else if (strcmp(*argv, "--nogamma-alpha-mode") == 0)
11391 pm.test_gamma_alpha_mode = 0;
11392
11393 else if (strcmp(*argv, "--expand16") == 0)
11394 pm.test_gamma_expand16 = 1;
11395
11396 else if (strcmp(*argv, "--noexpand16") == 0)
11397 pm.test_gamma_expand16 = 0;
11398
Matt Sarett9ea75692016-01-08 13:00:42 -050011399 else if (strcmp(*argv, "--low-depth-gray") == 0)
11400 pm.test_lbg = pm.test_lbg_gamma_threshold =
11401 pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
11402 pm.test_lbg_gamma_composition = 1;
11403
11404 else if (strcmp(*argv, "--nolow-depth-gray") == 0)
11405 pm.test_lbg = pm.test_lbg_gamma_threshold =
11406 pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
11407 pm.test_lbg_gamma_composition = 0;
11408
11409# ifdef PNG_WRITE_tRNS_SUPPORTED
11410 else if (strcmp(*argv, "--tRNS") == 0)
11411 pm.test_tRNS = 1;
11412# endif
11413
11414 else if (strcmp(*argv, "--notRNS") == 0)
11415 pm.test_tRNS = 0;
11416
Chris Craikb50c2172013-07-29 15:28:30 -070011417 else if (strcmp(*argv, "--more-gammas") == 0)
11418 pm.ngamma_tests = 3U;
11419
11420 else if (strcmp(*argv, "--all-gammas") == 0)
11421 pm.ngamma_tests = pm.ngammas;
11422
11423 else if (strcmp(*argv, "--progressive-read") == 0)
11424 pm.this.progressive = 1;
11425
11426 else if (strcmp(*argv, "--use-update-info") == 0)
11427 ++pm.use_update_info; /* Can call multiple times */
11428
11429 else if (strcmp(*argv, "--interlace") == 0)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011430 {
Matt Sarett9ea75692016-01-08 13:00:42 -050011431# if CAN_WRITE_INTERLACE
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011432 pm.interlace_type = PNG_INTERLACE_ADAM7;
Matt Sarett9ea75692016-01-08 13:00:42 -050011433# else /* !CAN_WRITE_INTERLACE */
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011434 fprintf(stderr, "pngvalid: no write interlace support\n");
11435 return SKIP;
Matt Sarett9ea75692016-01-08 13:00:42 -050011436# endif /* !CAN_WRITE_INTERLACE */
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011437 }
Chris Craikb50c2172013-07-29 15:28:30 -070011438
11439 else if (strcmp(*argv, "--use-input-precision") == 0)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011440 pm.use_input_precision = 1U;
11441
11442 else if (strcmp(*argv, "--use-calculation-precision") == 0)
11443 pm.use_input_precision = 0;
Chris Craikb50c2172013-07-29 15:28:30 -070011444
11445 else if (strcmp(*argv, "--calculations-use-input-precision") == 0)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011446 pm.calculations_use_input_precision = 1U;
Chris Craikb50c2172013-07-29 15:28:30 -070011447
11448 else if (strcmp(*argv, "--assume-16-bit-calculations") == 0)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011449 pm.assume_16_bit_calculations = 1U;
Chris Craikb50c2172013-07-29 15:28:30 -070011450
11451 else if (strcmp(*argv, "--calculations-follow-bit-depth") == 0)
11452 pm.calculations_use_input_precision =
11453 pm.assume_16_bit_calculations = 0;
11454
11455 else if (strcmp(*argv, "--exhaustive") == 0)
11456 pm.test_exhaustive = 1;
11457
11458 else if (argc > 1 && strcmp(*argv, "--sbitlow") == 0)
11459 --argc, pm.sbitlow = (png_byte)atoi(*++argv), catmore = 1;
11460
11461 else if (argc > 1 && strcmp(*argv, "--touch") == 0)
11462 --argc, touch = *++argv, catmore = 1;
11463
11464 else if (argc > 1 && strncmp(*argv, "--max", 5) == 0)
11465 {
11466 --argc;
11467
11468 if (strcmp(5+*argv, "abs8") == 0)
11469 pm.maxabs8 = atof(*++argv);
11470
11471 else if (strcmp(5+*argv, "abs16") == 0)
11472 pm.maxabs16 = atof(*++argv);
11473
11474 else if (strcmp(5+*argv, "calc8") == 0)
11475 pm.maxcalc8 = atof(*++argv);
11476
11477 else if (strcmp(5+*argv, "calc16") == 0)
11478 pm.maxcalc16 = atof(*++argv);
11479
11480 else if (strcmp(5+*argv, "out8") == 0)
11481 pm.maxout8 = atof(*++argv);
11482
11483 else if (strcmp(5+*argv, "out16") == 0)
11484 pm.maxout16 = atof(*++argv);
11485
11486 else if (strcmp(5+*argv, "pc8") == 0)
11487 pm.maxpc8 = atof(*++argv);
11488
11489 else if (strcmp(5+*argv, "pc16") == 0)
11490 pm.maxpc16 = atof(*++argv);
11491
11492 else
11493 {
11494 fprintf(stderr, "pngvalid: %s: unknown 'max' option\n", *argv);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011495 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070011496 }
11497
11498 catmore = 1;
11499 }
11500
11501 else if (strcmp(*argv, "--log8") == 0)
11502 --argc, pm.log8 = atof(*++argv), catmore = 1;
11503
11504 else if (strcmp(*argv, "--log16") == 0)
11505 --argc, pm.log16 = atof(*++argv), catmore = 1;
11506
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011507#ifdef PNG_SET_OPTION_SUPPORTED
11508 else if (strncmp(*argv, "--option=", 9) == 0)
11509 {
11510 /* Syntax of the argument is <option>:{on|off} */
11511 const char *arg = 9+*argv;
11512 unsigned char option=0, setting=0;
11513
Matt Sarett9ea75692016-01-08 13:00:42 -050011514#ifdef PNG_ARM_NEON
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011515 if (strncmp(arg, "arm-neon:", 9) == 0)
11516 option = PNG_ARM_NEON, arg += 9;
11517
11518 else
11519#endif
Matt Sarett9ea75692016-01-08 13:00:42 -050011520#ifdef PNG_EXTENSIONS
11521 if (strncmp(arg, "extensions:", 11) == 0)
11522 option = PNG_EXTENSIONS, arg += 11;
11523
11524 else
11525#endif
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011526#ifdef PNG_MAXIMUM_INFLATE_WINDOW
11527 if (strncmp(arg, "max-inflate-window:", 19) == 0)
11528 option = PNG_MAXIMUM_INFLATE_WINDOW, arg += 19;
11529
11530 else
11531#endif
11532 {
11533 fprintf(stderr, "pngvalid: %s: %s: unknown option\n", *argv, arg);
11534 exit(99);
11535 }
11536
11537 if (strcmp(arg, "off") == 0)
11538 setting = PNG_OPTION_OFF;
11539
11540 else if (strcmp(arg, "on") == 0)
11541 setting = PNG_OPTION_ON;
11542
11543 else
11544 {
11545 fprintf(stderr,
11546 "pngvalid: %s: %s: unknown setting (use 'on' or 'off')\n",
11547 *argv, arg);
11548 exit(99);
11549 }
11550
11551 pm.this.options[pm.this.noptions].option = option;
11552 pm.this.options[pm.this.noptions++].setting = setting;
11553 }
11554#endif /* PNG_SET_OPTION_SUPPORTED */
11555
Chris Craikb50c2172013-07-29 15:28:30 -070011556 else
11557 {
11558 fprintf(stderr, "pngvalid: %s: unknown argument\n", *argv);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011559 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070011560 }
11561
11562 if (catmore) /* consumed an extra *argv */
11563 {
11564 cp = safecat(command, sizeof command, cp, " ");
11565 cp = safecat(command, sizeof command, cp, *argv);
11566 }
11567 }
11568
11569 /* If pngvalid is run with no arguments default to a reasonable set of the
11570 * tests.
11571 */
11572 if (pm.test_standard == 0 && pm.test_size == 0 && pm.test_transform == 0 &&
11573 pm.ngamma_tests == 0)
11574 {
11575 /* Make this do all the tests done in the test shell scripts with the same
11576 * parameters, where possible. The limitation is that all the progressive
11577 * read and interlace stuff has to be done in separate runs, so only the
11578 * basic 'standard' and 'size' tests are done.
11579 */
11580 pm.test_standard = 1;
11581 pm.test_size = 1;
11582 pm.test_transform = 1;
11583 pm.ngamma_tests = 2U;
11584 }
11585
11586 if (pm.ngamma_tests > 0 &&
11587 pm.test_gamma_threshold == 0 && pm.test_gamma_transform == 0 &&
11588 pm.test_gamma_sbit == 0 && pm.test_gamma_scale16 == 0 &&
11589 pm.test_gamma_background == 0 && pm.test_gamma_alpha_mode == 0)
11590 {
11591 pm.test_gamma_threshold = 1;
11592 pm.test_gamma_transform = 1;
11593 pm.test_gamma_sbit = 1;
11594 pm.test_gamma_scale16 = 1;
11595 pm.test_gamma_background = 1;
11596 pm.test_gamma_alpha_mode = 1;
11597 }
11598
11599 else if (pm.ngamma_tests == 0)
11600 {
11601 /* Nothing to test so turn everything off: */
11602 pm.test_gamma_threshold = 0;
11603 pm.test_gamma_transform = 0;
11604 pm.test_gamma_sbit = 0;
11605 pm.test_gamma_scale16 = 0;
11606 pm.test_gamma_background = 0;
11607 pm.test_gamma_alpha_mode = 0;
11608 }
11609
11610 Try
11611 {
11612 /* Make useful base images */
Matt Sarett9ea75692016-01-08 13:00:42 -050011613 make_transform_images(&pm);
Chris Craikb50c2172013-07-29 15:28:30 -070011614
11615 /* Perform the standard and gamma tests. */
11616 if (pm.test_standard)
11617 {
11618 perform_interlace_macro_validation();
11619 perform_formatting_test(&pm.this);
11620# ifdef PNG_READ_SUPPORTED
11621 perform_standard_test(&pm);
11622# endif
11623 perform_error_test(&pm);
11624 }
11625
11626 /* Various oddly sized images: */
11627 if (pm.test_size)
11628 {
11629 make_size_images(&pm.this);
11630# ifdef PNG_READ_SUPPORTED
11631 perform_size_test(&pm);
11632# endif
11633 }
11634
11635#ifdef PNG_READ_TRANSFORMS_SUPPORTED
11636 /* Combinatorial transforms: */
11637 if (pm.test_transform)
11638 perform_transform_test(&pm);
11639#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
11640
11641#ifdef PNG_READ_GAMMA_SUPPORTED
11642 if (pm.ngamma_tests > 0)
11643 perform_gamma_test(&pm, summary);
11644#endif
11645 }
11646
11647 Catch_anonymous
11648 {
11649 fprintf(stderr, "pngvalid: test aborted (probably failed in cleanup)\n");
11650 if (!pm.this.verbose)
11651 {
11652 if (pm.this.error[0] != 0)
11653 fprintf(stderr, "pngvalid: first error: %s\n", pm.this.error);
11654
11655 fprintf(stderr, "pngvalid: run with -v to see what happened\n");
11656 }
11657 exit(1);
11658 }
11659
11660 if (summary)
11661 {
11662 printf("%s: %s (%s point arithmetic)\n",
11663 (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
11664 pm.this.nwarnings)) ? "FAIL" : "PASS",
11665 command,
11666#if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || PNG_LIBPNG_VER < 10500
11667 "floating"
11668#else
11669 "fixed"
11670#endif
11671 );
11672 }
11673
11674 if (memstats)
11675 {
11676 printf("Allocated memory statistics (in bytes):\n"
11677 "\tread %lu maximum single, %lu peak, %lu total\n"
11678 "\twrite %lu maximum single, %lu peak, %lu total\n",
11679 (unsigned long)pm.this.read_memory_pool.max_max,
11680 (unsigned long)pm.this.read_memory_pool.max_limit,
11681 (unsigned long)pm.this.read_memory_pool.max_total,
11682 (unsigned long)pm.this.write_memory_pool.max_max,
11683 (unsigned long)pm.this.write_memory_pool.max_limit,
11684 (unsigned long)pm.this.write_memory_pool.max_total);
11685 }
11686
11687 /* Do this here to provoke memory corruption errors in memory not directly
11688 * allocated by libpng - not a complete test, but better than nothing.
11689 */
11690 store_delete(&pm.this);
11691
11692 /* Error exit if there are any errors, and maybe if there are any
11693 * warnings.
11694 */
11695 if (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
11696 pm.this.nwarnings))
11697 {
11698 if (!pm.this.verbose)
11699 fprintf(stderr, "pngvalid: %s\n", pm.this.error);
11700
11701 fprintf(stderr, "pngvalid: %d errors, %d warnings\n", pm.this.nerrors,
11702 pm.this.nwarnings);
11703
11704 exit(1);
11705 }
11706
11707 /* Success case. */
11708 if (touch != NULL)
11709 {
11710 FILE *fsuccess = fopen(touch, "wt");
11711
11712 if (fsuccess != NULL)
11713 {
11714 int error = 0;
11715 fprintf(fsuccess, "PNG validation succeeded\n");
11716 fflush(fsuccess);
11717 error = ferror(fsuccess);
11718
11719 if (fclose(fsuccess) || error)
11720 {
11721 fprintf(stderr, "%s: write failed\n", touch);
11722 exit(1);
11723 }
11724 }
11725
11726 else
11727 {
11728 fprintf(stderr, "%s: open failed\n", touch);
11729 exit(1);
11730 }
11731 }
11732
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011733 /* This is required because some very minimal configurations do not use it:
11734 */
11735 UNUSED(fail)
Chris Craikb50c2172013-07-29 15:28:30 -070011736 return 0;
11737}
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011738#else /* write or low level APIs not supported */
Chris Craikb50c2172013-07-29 15:28:30 -070011739int main(void)
11740{
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011741 fprintf(stderr,
11742 "pngvalid: no low level write support in libpng, all tests skipped\n");
Chris Craikb50c2172013-07-29 15:28:30 -070011743 /* So the test is skipped: */
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011744 return SKIP;
Chris Craikb50c2172013-07-29 15:28:30 -070011745}
11746#endif