blob: 9a2da6a024f92a628e3ecdc67f6fa6785f6c7306 [file] [log] [blame]
Chris Craikb50c2172013-07-29 15:28:30 -07001
2/* pngvalid.c - validate libpng by constructing then reading png files.
3 *
Leon Scroggins III3cc83ac2017-10-06 11:02:56 -04004 * Last changed in libpng 1.6.31 [July 27, 2017]
5 * Copyright (c) 2014-2017 John Cunningham Bowler
Chris Craikb50c2172013-07-29 15:28:30 -07006 *
7 * This code is released under the libpng license.
8 * For conditions of distribution and use, see the disclaimer
9 * and license in png.h
10 *
11 * NOTES:
12 * This is a C program that is intended to be linked against libpng. It
13 * generates bitmaps internally, stores them as PNG files (using the
14 * sequential write code) then reads them back (using the sequential
15 * read code) and validates that the result has the correct data.
16 *
17 * The program can be modified and extended to test the correctness of
18 * transformations performed by libpng.
19 */
20
21#define _POSIX_SOURCE 1
22#define _ISOC99_SOURCE 1 /* For floating point */
23#define _GNU_SOURCE 1 /* For the floating point exception extension */
xNombred07bb0d2020-03-10 20:17:12 +010024#define _BSD_SOURCE 1 /* For the floating point exception extension */
xNombre232e9ca2020-07-03 22:10:22 +020025#define _DEFAULT_SOURCE 1 /* For the floating point exception extension */
Chris Craikb50c2172013-07-29 15:28:30 -070026
27#include <signal.h>
28#include <stdio.h>
29
30#if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
31# include <config.h>
32#endif
33
34#ifdef HAVE_FEENABLEEXCEPT /* from config.h, if included */
35# include <fenv.h>
36#endif
37
Matt Sarett9b1fe632015-11-25 10:21:17 -050038#ifndef FE_DIVBYZERO
39# define FE_DIVBYZERO 0
40#endif
41#ifndef FE_INVALID
42# define FE_INVALID 0
43#endif
44#ifndef FE_OVERFLOW
45# define FE_OVERFLOW 0
46#endif
47
Chris Craikb50c2172013-07-29 15:28:30 -070048/* Define the following to use this test against your installed libpng, rather
49 * than the one being built here:
50 */
51#ifdef PNG_FREESTANDING_TESTS
52# include <png.h>
53#else
54# include "../../png.h"
55#endif
56
Sireesh Tripurarib478e662014-05-09 15:15:10 +053057#ifdef PNG_ZLIB_HEADER
58# include PNG_ZLIB_HEADER
59#else
60# include <zlib.h> /* For crc32 */
61#endif
62
63/* 1.6.1 added support for the configure test harness, which uses 77 to indicate
64 * a skipped test, in earlier versions we need to succeed on a skipped test, so:
65 */
Matt Sarett11466862016-02-19 13:41:30 -050066#if PNG_LIBPNG_VER >= 10601 && defined(HAVE_CONFIG_H)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053067# define SKIP 77
Matt Sarett11466862016-02-19 13:41:30 -050068#else
69# define SKIP 0
Sireesh Tripurarib478e662014-05-09 15:15:10 +053070#endif
71
72/* pngvalid requires write support and one of the fixed or floating point APIs.
73 */
74#if defined(PNG_WRITE_SUPPORTED) &&\
75 (defined(PNG_FIXED_POINT_SUPPORTED) || defined(PNG_FLOATING_POINT_SUPPORTED))
Chris Craikb50c2172013-07-29 15:28:30 -070076
77#if PNG_LIBPNG_VER < 10500
Matt Sarett9b1fe632015-11-25 10:21:17 -050078/* This deliberately lacks the const. */
Chris Craikb50c2172013-07-29 15:28:30 -070079typedef png_byte *png_const_bytep;
80
81/* This is copied from 1.5.1 png.h: */
82#define PNG_INTERLACE_ADAM7_PASSES 7
83#define PNG_PASS_START_ROW(pass) (((1U&~(pass))<<(3-((pass)>>1)))&7)
84#define PNG_PASS_START_COL(pass) (((1U& (pass))<<(3-(((pass)+1)>>1)))&7)
85#define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3)
86#define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3)
87#define PNG_PASS_ROWS(height, pass) (((height)+(((1<<PNG_PASS_ROW_SHIFT(pass))\
88 -1)-PNG_PASS_START_ROW(pass)))>>PNG_PASS_ROW_SHIFT(pass))
89#define PNG_PASS_COLS(width, pass) (((width)+(((1<<PNG_PASS_COL_SHIFT(pass))\
90 -1)-PNG_PASS_START_COL(pass)))>>PNG_PASS_COL_SHIFT(pass))
91#define PNG_ROW_FROM_PASS_ROW(yIn, pass) \
92 (((yIn)<<PNG_PASS_ROW_SHIFT(pass))+PNG_PASS_START_ROW(pass))
93#define PNG_COL_FROM_PASS_COL(xIn, pass) \
94 (((xIn)<<PNG_PASS_COL_SHIFT(pass))+PNG_PASS_START_COL(pass))
95#define PNG_PASS_MASK(pass,off) ( \
96 ((0x110145AFU>>(((7-(off))-(pass))<<2)) & 0xFU) | \
97 ((0x01145AF0U>>(((7-(off))-(pass))<<2)) & 0xF0U))
98#define PNG_ROW_IN_INTERLACE_PASS(y, pass) \
99 ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1)
100#define PNG_COL_IN_INTERLACE_PASS(x, pass) \
101 ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1)
102
103/* These are needed too for the default build: */
104#define PNG_WRITE_16BIT_SUPPORTED
105#define PNG_READ_16BIT_SUPPORTED
106
xNombred07bb0d2020-03-10 20:17:12 +0100107/* This comes from pnglibconf.h after 1.5: */
Chris Craikb50c2172013-07-29 15:28:30 -0700108#define PNG_FP_1 100000
109#define PNG_GAMMA_THRESHOLD_FIXED\
110 ((png_fixed_point)(PNG_GAMMA_THRESHOLD * PNG_FP_1))
111#endif
112
113#if PNG_LIBPNG_VER < 10600
114 /* 1.6.0 constifies many APIs, the following exists to allow pngvalid to be
115 * compiled against earlier versions.
116 */
117# define png_const_structp png_structp
118#endif
119
Matt Sarett11466862016-02-19 13:41:30 -0500120#ifndef RELEASE_BUILD
121 /* RELEASE_BUILD is true for releases and release candidates: */
122# define RELEASE_BUILD (PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC)
123#endif
124#if RELEASE_BUILD
125# define debugonly(something)
126#else /* !RELEASE_BUILD */
127# define debugonly(something) something
128#endif /* !RELEASE_BUILD */
129
Chris Craikb50c2172013-07-29 15:28:30 -0700130#include <float.h> /* For floating point constants */
131#include <stdlib.h> /* For malloc */
132#include <string.h> /* For memcpy, memset */
133#include <math.h> /* For floor */
134
Alex Naidis7a055fd2016-10-01 12:23:07 +0200135/* Convenience macros. */
136#define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d))
137#define CHUNK_IHDR CHUNK(73,72,68,82)
138#define CHUNK_PLTE CHUNK(80,76,84,69)
139#define CHUNK_IDAT CHUNK(73,68,65,84)
140#define CHUNK_IEND CHUNK(73,69,78,68)
141#define CHUNK_cHRM CHUNK(99,72,82,77)
142#define CHUNK_gAMA CHUNK(103,65,77,65)
143#define CHUNK_sBIT CHUNK(115,66,73,84)
144#define CHUNK_sRGB CHUNK(115,82,71,66)
145
Chris Craikb50c2172013-07-29 15:28:30 -0700146/* Unused formal parameter errors are removed using the following macro which is
147 * expected to have no bad effects on performance.
148 */
149#ifndef UNUSED
150# if defined(__GNUC__) || defined(_MSC_VER)
151# define UNUSED(param) (void)param;
152# else
153# define UNUSED(param)
154# endif
155#endif
156
157/***************************** EXCEPTION HANDLING *****************************/
158#ifdef PNG_FREESTANDING_TESTS
159# include <cexcept.h>
160#else
161# include "../visupng/cexcept.h"
162#endif
163
164#ifdef __cplusplus
165# define this not_the_cpp_this
166# define new not_the_cpp_new
167# define voidcast(type, value) static_cast<type>(value)
168#else
169# define voidcast(type, value) (value)
170#endif /* __cplusplus */
171
172struct png_store;
173define_exception_type(struct png_store*);
174
175/* The following are macros to reduce typing everywhere where the well known
176 * name 'the_exception_context' must be defined.
177 */
178#define anon_context(ps) struct exception_context *the_exception_context = \
179 &(ps)->exception_context
180#define context(ps,fault) anon_context(ps); png_store *fault
181
Matt Sarett9b1fe632015-11-25 10:21:17 -0500182/* This macro returns the number of elements in an array as an (unsigned int),
183 * it is necessary to avoid the inability of certain versions of GCC to use
184 * the value of a compile-time constant when performing range checks. It must
185 * be passed an array name.
186 */
187#define ARRAY_SIZE(a) ((unsigned int)((sizeof (a))/(sizeof (a)[0])))
188
189/* GCC BUG 66447 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66447) requires
190 * some broken GCC versions to be fixed up to avoid invalid whining about auto
191 * variables that are *not* changed within the scope of a setjmp being changed.
192 *
193 * Feel free to extend the list of broken versions.
194 */
195#define is_gnu(major,minor)\
196 (defined __GNUC__) && __GNUC__ == (major) && __GNUC_MINOR__ == (minor)
197#define is_gnu_patch(major,minor,patch)\
198 is_gnu(major,minor) && __GNUC_PATCHLEVEL__ == 0
199/* For the moment just do it always; all versions of GCC seem to be broken: */
200#ifdef __GNUC__
201 const void * volatile make_volatile_for_gnu;
202# define gnu_volatile(x) make_volatile_for_gnu = &x;
203#else /* !GNUC broken versions */
204# define gnu_volatile(x)
205#endif /* !GNUC broken versions */
206
Chris Craikb50c2172013-07-29 15:28:30 -0700207/******************************* UTILITIES ************************************/
208/* Error handling is particularly problematic in production code - error
209 * handlers often themselves have bugs which lead to programs that detect
210 * minor errors crashing. The following functions deal with one very
211 * common class of errors in error handlers - attempting to format error or
212 * warning messages into buffers that are too small.
213 */
214static size_t safecat(char *buffer, size_t bufsize, size_t pos,
Matt Sarett9b1fe632015-11-25 10:21:17 -0500215 const char *cat)
Chris Craikb50c2172013-07-29 15:28:30 -0700216{
217 while (pos < bufsize && cat != NULL && *cat != 0)
218 buffer[pos++] = *cat++;
219
220 if (pos >= bufsize)
221 pos = bufsize-1;
222
223 buffer[pos] = 0;
224 return pos;
225}
226
227static size_t safecatn(char *buffer, size_t bufsize, size_t pos, int n)
228{
229 char number[64];
230 sprintf(number, "%d", n);
231 return safecat(buffer, bufsize, pos, number);
232}
233
234#ifdef PNG_READ_TRANSFORMS_SUPPORTED
235static size_t safecatd(char *buffer, size_t bufsize, size_t pos, double d,
236 int precision)
237{
238 char number[64];
239 sprintf(number, "%.*f", precision, d);
240 return safecat(buffer, bufsize, pos, number);
241}
242#endif
243
Matt Sarett9b1fe632015-11-25 10:21:17 -0500244static const char invalid[] = "invalid";
245static const char sep[] = ": ";
Chris Craikb50c2172013-07-29 15:28:30 -0700246
Matt Sarett9b1fe632015-11-25 10:21:17 -0500247static const char *colour_types[8] =
Chris Craikb50c2172013-07-29 15:28:30 -0700248{
249 "grayscale", invalid, "truecolour", "indexed-colour",
250 "grayscale with alpha", invalid, "truecolour with alpha", invalid
251};
252
Matt Sarett9b1fe632015-11-25 10:21:17 -0500253#ifdef PNG_READ_TRANSFORMS_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -0700254/* Convert a double precision value to fixed point. */
255static png_fixed_point
256fix(double d)
257{
258 d = floor(d * PNG_FP_1 + .5);
259 return (png_fixed_point)d;
260}
261#endif /* PNG_READ_SUPPORTED */
262
263/* Generate random bytes. This uses a boring repeatable algorithm and it
264 * is implemented here so that it gives the same set of numbers on every
265 * architecture. It's a linear congruential generator (Knuth or Sedgewick
266 * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
267 * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise
268 * Generation.)
269 */
270static void
271make_random_bytes(png_uint_32* seed, void* pv, size_t size)
272{
273 png_uint_32 u0 = seed[0], u1 = seed[1];
274 png_bytep bytes = voidcast(png_bytep, pv);
275
276 /* There are thirty three bits, the next bit in the sequence is bit-33 XOR
277 * bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
278 */
279 size_t i;
280 for (i=0; i<size; ++i)
281 {
282 /* First generate 8 new bits then shift them in at the end. */
283 png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
284 u1 <<= 8;
285 u1 |= u0 >> 24;
286 u0 <<= 8;
287 u0 |= u;
288 *bytes++ = (png_byte)u;
289 }
290
291 seed[0] = u0;
292 seed[1] = u1;
293}
294
295static void
296make_four_random_bytes(png_uint_32* seed, png_bytep bytes)
297{
298 make_random_bytes(seed, bytes, 4);
299}
300
Matt Sarett11466862016-02-19 13:41:30 -0500301#if defined PNG_READ_SUPPORTED || defined PNG_WRITE_tRNS_SUPPORTED ||\
302 defined PNG_WRITE_FILTER_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -0700303static void
304randomize(void *pv, size_t size)
305{
306 static png_uint_32 random_seed[2] = {0x56789abc, 0xd};
307 make_random_bytes(random_seed, pv, size);
308}
309
Matt Sarett11466862016-02-19 13:41:30 -0500310#define R8(this) randomize(&(this), sizeof (this))
Chris Craikb50c2172013-07-29 15:28:30 -0700311
Alex Naidis7a055fd2016-10-01 12:23:07 +0200312#ifdef PNG_READ_SUPPORTED
313static png_byte
314random_byte(void)
Matt Sarett11466862016-02-19 13:41:30 -0500315{
Alex Naidis7a055fd2016-10-01 12:23:07 +0200316 unsigned char b1[1];
317 randomize(b1, sizeof b1);
318 return b1[0];
Matt Sarett11466862016-02-19 13:41:30 -0500319}
Alex Naidis7a055fd2016-10-01 12:23:07 +0200320#endif /* READ */
Matt Sarett11466862016-02-19 13:41:30 -0500321
Alex Naidis7a055fd2016-10-01 12:23:07 +0200322static png_uint_16
323random_u16(void)
324{
325 unsigned char b2[2];
326 randomize(b2, sizeof b2);
327 return png_get_uint_16(b2);
328}
Matt Sarett11466862016-02-19 13:41:30 -0500329
330#if defined PNG_READ_RGB_TO_GRAY_SUPPORTED ||\
331 defined PNG_READ_FILLER_SUPPORTED
Alex Naidis7a055fd2016-10-01 12:23:07 +0200332static png_uint_32
333random_u32(void)
Matt Sarett11466862016-02-19 13:41:30 -0500334{
Alex Naidis7a055fd2016-10-01 12:23:07 +0200335 unsigned char b4[4];
336 randomize(b4, sizeof b4);
337 return png_get_uint_32(b4);
Matt Sarett11466862016-02-19 13:41:30 -0500338}
Matt Sarett11466862016-02-19 13:41:30 -0500339#endif /* READ_FILLER || READ_RGB_TO_GRAY */
340
341#endif /* READ || WRITE_tRNS || WRITE_FILTER */
342
343#if defined PNG_READ_TRANSFORMS_SUPPORTED ||\
344 defined PNG_WRITE_FILTER_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -0700345static unsigned int
346random_mod(unsigned int max)
347{
Alex Naidis7a055fd2016-10-01 12:23:07 +0200348 return random_u16() % max; /* 0 .. max-1 */
Chris Craikb50c2172013-07-29 15:28:30 -0700349}
Matt Sarett11466862016-02-19 13:41:30 -0500350#endif /* READ_TRANSFORMS || WRITE_FILTER */
Chris Craikb50c2172013-07-29 15:28:30 -0700351
Matt Sarett9b1fe632015-11-25 10:21:17 -0500352#if (defined PNG_READ_RGB_TO_GRAY_SUPPORTED) ||\
353 (defined PNG_READ_FILLER_SUPPORTED)
Chris Craikb50c2172013-07-29 15:28:30 -0700354static int
355random_choice(void)
356{
Alex Naidis7a055fd2016-10-01 12:23:07 +0200357 return random_byte() & 1;
Chris Craikb50c2172013-07-29 15:28:30 -0700358}
Matt Sarett11466862016-02-19 13:41:30 -0500359#endif /* READ_RGB_TO_GRAY || READ_FILLER */
Chris Craikb50c2172013-07-29 15:28:30 -0700360
361/* A numeric ID based on PNG file characteristics. The 'do_interlace' field
362 * simply records whether pngvalid did the interlace itself or whether it
363 * was done by libpng. Width and height must be less than 256. 'palette' is an
Matt Sarett9b1fe632015-11-25 10:21:17 -0500364 * index of the palette to use for formats with a palette otherwise a boolean
365 * indicating if a tRNS chunk was generated.
Chris Craikb50c2172013-07-29 15:28:30 -0700366 */
367#define FILEID(col, depth, palette, interlace, width, height, do_interlace) \
368 ((png_uint_32)((col) + ((depth)<<3) + ((palette)<<8) + ((interlace)<<13) + \
369 (((do_interlace)!=0)<<15) + ((width)<<16) + ((height)<<24)))
370
371#define COL_FROM_ID(id) ((png_byte)((id)& 0x7U))
372#define DEPTH_FROM_ID(id) ((png_byte)(((id) >> 3) & 0x1fU))
373#define PALETTE_FROM_ID(id) (((id) >> 8) & 0x1f)
Matt Sarett9b1fe632015-11-25 10:21:17 -0500374#define INTERLACE_FROM_ID(id) ((png_byte)(((id) >> 13) & 0x3))
Chris Craikb50c2172013-07-29 15:28:30 -0700375#define DO_INTERLACE_FROM_ID(id) ((int)(((id)>>15) & 1))
376#define WIDTH_FROM_ID(id) (((id)>>16) & 0xff)
377#define HEIGHT_FROM_ID(id) (((id)>>24) & 0xff)
378
379/* Utility to construct a standard name for a standard image. */
380static size_t
381standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type,
382 int bit_depth, unsigned int npalette, int interlace_type,
383 png_uint_32 w, png_uint_32 h, int do_interlace)
384{
385 pos = safecat(buffer, bufsize, pos, colour_types[colour_type]);
Matt Sarett9b1fe632015-11-25 10:21:17 -0500386 if (colour_type == 3) /* must have a palette */
Chris Craikb50c2172013-07-29 15:28:30 -0700387 {
388 pos = safecat(buffer, bufsize, pos, "[");
389 pos = safecatn(buffer, bufsize, pos, npalette);
390 pos = safecat(buffer, bufsize, pos, "]");
391 }
Matt Sarett9b1fe632015-11-25 10:21:17 -0500392
393 else if (npalette != 0)
394 pos = safecat(buffer, bufsize, pos, "+tRNS");
395
Chris Craikb50c2172013-07-29 15:28:30 -0700396 pos = safecat(buffer, bufsize, pos, " ");
397 pos = safecatn(buffer, bufsize, pos, bit_depth);
398 pos = safecat(buffer, bufsize, pos, " bit");
399
400 if (interlace_type != PNG_INTERLACE_NONE)
401 {
402 pos = safecat(buffer, bufsize, pos, " interlaced");
403 if (do_interlace)
404 pos = safecat(buffer, bufsize, pos, "(pngvalid)");
405 else
406 pos = safecat(buffer, bufsize, pos, "(libpng)");
407 }
408
409 if (w > 0 || h > 0)
410 {
411 pos = safecat(buffer, bufsize, pos, " ");
412 pos = safecatn(buffer, bufsize, pos, w);
413 pos = safecat(buffer, bufsize, pos, "x");
414 pos = safecatn(buffer, bufsize, pos, h);
415 }
416
417 return pos;
418}
419
420static size_t
421standard_name_from_id(char *buffer, size_t bufsize, size_t pos, png_uint_32 id)
422{
423 return standard_name(buffer, bufsize, pos, COL_FROM_ID(id),
424 DEPTH_FROM_ID(id), PALETTE_FROM_ID(id), INTERLACE_FROM_ID(id),
425 WIDTH_FROM_ID(id), HEIGHT_FROM_ID(id), DO_INTERLACE_FROM_ID(id));
426}
427
428/* Convenience API and defines to list valid formats. Note that 16 bit read and
429 * write support is required to do 16 bit read tests (we must be able to make a
430 * 16 bit image to test!)
431 */
432#ifdef PNG_WRITE_16BIT_SUPPORTED
433# define WRITE_BDHI 4
434# ifdef PNG_READ_16BIT_SUPPORTED
435# define READ_BDHI 4
436# define DO_16BIT
437# endif
438#else
439# define WRITE_BDHI 3
440#endif
441#ifndef DO_16BIT
442# define READ_BDHI 3
443#endif
444
445/* The following defines the number of different palettes to generate for
446 * each log bit depth of a colour type 3 standard image.
447 */
448#define PALETTE_COUNT(bit_depth) ((bit_depth) > 4 ? 1U : 16U)
449
450static int
451next_format(png_bytep colour_type, png_bytep bit_depth,
Matt Sarett9b1fe632015-11-25 10:21:17 -0500452 unsigned int* palette_number, int low_depth_gray, int tRNS)
Chris Craikb50c2172013-07-29 15:28:30 -0700453{
454 if (*bit_depth == 0)
455 {
Sireesh Tripurarib478e662014-05-09 15:15:10 +0530456 *colour_type = 0;
Matt Sarett9b1fe632015-11-25 10:21:17 -0500457 if (low_depth_gray)
Sireesh Tripurarib478e662014-05-09 15:15:10 +0530458 *bit_depth = 1;
Matt Sarett9b1fe632015-11-25 10:21:17 -0500459 else
460 *bit_depth = 8;
Sireesh Tripurarib478e662014-05-09 15:15:10 +0530461 *palette_number = 0;
Chris Craikb50c2172013-07-29 15:28:30 -0700462 return 1;
463 }
464
Matt Sarett9b1fe632015-11-25 10:21:17 -0500465 if (*colour_type < 4/*no alpha channel*/)
Chris Craikb50c2172013-07-29 15:28:30 -0700466 {
Matt Sarett9b1fe632015-11-25 10:21:17 -0500467 /* Add multiple palettes for colour type 3, one image with tRNS
468 * and one without for other non-alpha formats:
469 */
470 unsigned int pn = ++*palette_number;
471 png_byte ct = *colour_type;
472
473 if (((ct == 0/*GRAY*/ || ct/*RGB*/ == 2) && tRNS && pn < 2) ||
474 (ct == 3/*PALETTE*/ && pn < PALETTE_COUNT(*bit_depth)))
Chris Craikb50c2172013-07-29 15:28:30 -0700475 return 1;
476
Matt Sarett9b1fe632015-11-25 10:21:17 -0500477 /* No: next bit depth */
Chris Craikb50c2172013-07-29 15:28:30 -0700478 *palette_number = 0;
479 }
480
481 *bit_depth = (png_byte)(*bit_depth << 1);
482
483 /* Palette images are restricted to 8 bit depth */
484 if (*bit_depth <= 8
Matt Sarett9b1fe632015-11-25 10:21:17 -0500485#ifdef DO_16BIT
Chris Craikb50c2172013-07-29 15:28:30 -0700486 || (*colour_type != 3 && *bit_depth <= 16)
Matt Sarett9b1fe632015-11-25 10:21:17 -0500487#endif
Chris Craikb50c2172013-07-29 15:28:30 -0700488 )
489 return 1;
490
491 /* Move to the next color type, or return 0 at the end. */
492 switch (*colour_type)
493 {
494 case 0:
495 *colour_type = 2;
496 *bit_depth = 8;
497 return 1;
498
499 case 2:
500 *colour_type = 3;
501 *bit_depth = 1;
502 return 1;
503
504 case 3:
505 *colour_type = 4;
506 *bit_depth = 8;
507 return 1;
508
509 case 4:
510 *colour_type = 6;
511 *bit_depth = 8;
512 return 1;
513
514 default:
515 return 0;
516 }
517}
518
519#ifdef PNG_READ_TRANSFORMS_SUPPORTED
520static unsigned int
521sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth,
Matt Sarett9b1fe632015-11-25 10:21:17 -0500522 png_uint_32 x, unsigned int sample_index, int swap16, int littleendian)
Chris Craikb50c2172013-07-29 15:28:30 -0700523{
524 png_uint_32 bit_index, result;
525
526 /* Find a sample index for the desired sample: */
527 x *= bit_depth;
528 bit_index = x;
529
530 if ((colour_type & 1) == 0) /* !palette */
531 {
532 if (colour_type & 2)
533 bit_index *= 3;
534
535 if (colour_type & 4)
536 bit_index += x; /* Alpha channel */
537
538 /* Multiple channels; select one: */
539 if (colour_type & (2+4))
540 bit_index += sample_index * bit_depth;
541 }
542
543 /* Return the sample from the row as an integer. */
544 row += bit_index >> 3;
545 result = *row;
546
547 if (bit_depth == 8)
548 return result;
549
550 else if (bit_depth > 8)
Matt Sarett9b1fe632015-11-25 10:21:17 -0500551 {
552 if (swap16)
553 return (*++row << 8) + result;
554 else
555 return (result << 8) + *++row;
556 }
Chris Craikb50c2172013-07-29 15:28:30 -0700557
Matt Sarett9b1fe632015-11-25 10:21:17 -0500558 /* Less than 8 bits per sample. By default PNG has the big end of
559 * the egg on the left of the screen, but if littleendian is set
560 * then the big end is on the right.
561 */
Chris Craikb50c2172013-07-29 15:28:30 -0700562 bit_index &= 7;
Matt Sarett9b1fe632015-11-25 10:21:17 -0500563
564 if (!littleendian)
565 bit_index = 8-bit_index-bit_depth;
566
567 return (result >> bit_index) & ((1U<<bit_depth)-1);
Chris Craikb50c2172013-07-29 15:28:30 -0700568}
569#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
570
571/* Copy a single pixel, of a given size, from one buffer to another -
572 * while this is basically bit addressed there is an implicit assumption
573 * that pixels 8 or more bits in size are byte aligned and that pixels
574 * do not otherwise cross byte boundaries. (This is, so far as I know,
575 * universally true in bitmap computer graphics. [JCB 20101212])
576 *
577 * NOTE: The to and from buffers may be the same.
578 */
579static void
580pixel_copy(png_bytep toBuffer, png_uint_32 toIndex,
Matt Sarett06f10872016-01-04 12:56:20 -0500581 png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize,
582 int littleendian)
Chris Craikb50c2172013-07-29 15:28:30 -0700583{
584 /* Assume we can multiply by 'size' without overflow because we are
585 * just working in a single buffer.
586 */
587 toIndex *= pixelSize;
588 fromIndex *= pixelSize;
589 if (pixelSize < 8) /* Sub-byte */
590 {
591 /* Mask to select the location of the copied pixel: */
Matt Sarett06f10872016-01-04 12:56:20 -0500592 unsigned int destMask = ((1U<<pixelSize)-1) <<
593 (littleendian ? toIndex&7 : 8-pixelSize-(toIndex&7));
Chris Craikb50c2172013-07-29 15:28:30 -0700594 /* The following read the entire pixels and clears the extra: */
595 unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask;
596 unsigned int sourceByte = fromBuffer[fromIndex >> 3];
597
598 /* Don't rely on << or >> supporting '0' here, just in case: */
599 fromIndex &= 7;
Matt Sarett06f10872016-01-04 12:56:20 -0500600 if (littleendian)
601 {
602 if (fromIndex > 0) sourceByte >>= fromIndex;
603 if ((toIndex & 7) > 0) sourceByte <<= toIndex & 7;
604 }
605
606 else
607 {
608 if (fromIndex > 0) sourceByte <<= fromIndex;
609 if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7;
610 }
Chris Craikb50c2172013-07-29 15:28:30 -0700611
612 toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask));
613 }
614 else /* One or more bytes */
615 memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3);
616}
617
618#ifdef PNG_READ_SUPPORTED
619/* Copy a complete row of pixels, taking into account potential partial
620 * bytes at the end.
621 */
622static void
Matt Sarett06f10872016-01-04 12:56:20 -0500623row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth,
624 int littleendian)
Chris Craikb50c2172013-07-29 15:28:30 -0700625{
626 memcpy(toBuffer, fromBuffer, bitWidth >> 3);
627
628 if ((bitWidth & 7) != 0)
629 {
630 unsigned int mask;
631
632 toBuffer += bitWidth >> 3;
633 fromBuffer += bitWidth >> 3;
Matt Sarett06f10872016-01-04 12:56:20 -0500634 if (littleendian)
635 mask = 0xff << (bitWidth & 7);
636 else
637 mask = 0xff >> (bitWidth & 7);
Chris Craikb50c2172013-07-29 15:28:30 -0700638 *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask));
639 }
640}
641
642/* Compare pixels - they are assumed to start at the first byte in the
643 * given buffers.
644 */
645static int
646pixel_cmp(png_const_bytep pa, png_const_bytep pb, png_uint_32 bit_width)
647{
648#if PNG_LIBPNG_VER < 10506
649 if (memcmp(pa, pb, bit_width>>3) == 0)
650 {
651 png_uint_32 p;
652
653 if ((bit_width & 7) == 0) return 0;
654
655 /* Ok, any differences? */
656 p = pa[bit_width >> 3];
657 p ^= pb[bit_width >> 3];
658
659 if (p == 0) return 0;
660
661 /* There are, but they may not be significant, remove the bits
662 * after the end (the low order bits in PNG.)
663 */
664 bit_width &= 7;
665 p >>= 8-bit_width;
666
667 if (p == 0) return 0;
668 }
669#else
670 /* From libpng-1.5.6 the overwrite should be fixed, so compare the trailing
671 * bits too:
672 */
673 if (memcmp(pa, pb, (bit_width+7)>>3) == 0)
674 return 0;
675#endif
676
677 /* Return the index of the changed byte. */
678 {
679 png_uint_32 where = 0;
680
681 while (pa[where] == pb[where]) ++where;
682 return 1+where;
683 }
684}
685#endif /* PNG_READ_SUPPORTED */
686
687/*************************** BASIC PNG FILE WRITING ***************************/
688/* A png_store takes data from the sequential writer or provides data
689 * to the sequential reader. It can also store the result of a PNG
690 * write for later retrieval.
691 */
692#define STORE_BUFFER_SIZE 500 /* arbitrary */
693typedef struct png_store_buffer
694{
695 struct png_store_buffer* prev; /* NOTE: stored in reverse order */
696 png_byte buffer[STORE_BUFFER_SIZE];
697} png_store_buffer;
698
699#define FILE_NAME_SIZE 64
700
701typedef struct store_palette_entry /* record of a single palette entry */
702{
703 png_byte red;
704 png_byte green;
705 png_byte blue;
706 png_byte alpha;
707} store_palette_entry, store_palette[256];
708
709typedef struct png_store_file
710{
711 struct png_store_file* next; /* as many as you like... */
712 char name[FILE_NAME_SIZE];
Alex Naidis7a055fd2016-10-01 12:23:07 +0200713 unsigned int IDAT_bits; /* Number of bits in IDAT size */
714 png_uint_32 IDAT_size; /* Total size of IDAT data */
Chris Craikb50c2172013-07-29 15:28:30 -0700715 png_uint_32 id; /* must be correct (see FILEID) */
xNombred07bb0d2020-03-10 20:17:12 +0100716 size_t datacount; /* In this (the last) buffer */
Chris Craikb50c2172013-07-29 15:28:30 -0700717 png_store_buffer data; /* Last buffer in file */
718 int npalette; /* Number of entries in palette */
719 store_palette_entry* palette; /* May be NULL */
720} png_store_file;
721
722/* The following is a pool of memory allocated by a single libpng read or write
723 * operation.
724 */
725typedef struct store_pool
726{
727 struct png_store *store; /* Back pointer */
728 struct store_memory *list; /* List of allocated memory */
729 png_byte mark[4]; /* Before and after data */
730
731 /* Statistics for this run. */
732 png_alloc_size_t max; /* Maximum single allocation */
733 png_alloc_size_t current; /* Current allocation */
734 png_alloc_size_t limit; /* Highest current allocation */
735 png_alloc_size_t total; /* Total allocation */
736
737 /* Overall statistics (retained across successive runs). */
738 png_alloc_size_t max_max;
739 png_alloc_size_t max_limit;
740 png_alloc_size_t max_total;
741} store_pool;
742
743typedef struct png_store
744{
745 /* For cexcept.h exception handling - simply store one of these;
746 * the context is a self pointer but it may point to a different
747 * png_store (in fact it never does in this program.)
748 */
749 struct exception_context
750 exception_context;
751
752 unsigned int verbose :1;
753 unsigned int treat_warnings_as_errors :1;
754 unsigned int expect_error :1;
755 unsigned int expect_warning :1;
756 unsigned int saw_warning :1;
757 unsigned int speed :1;
758 unsigned int progressive :1; /* use progressive read */
759 unsigned int validated :1; /* used as a temporary flag */
760 int nerrors;
761 int nwarnings;
Sireesh Tripurarib478e662014-05-09 15:15:10 +0530762 int noptions; /* number of options below: */
763 struct {
764 unsigned char option; /* option number, 0..30 */
765 unsigned char setting; /* setting (unset,invalid,on,off) */
766 } options[16];
767 char test[128]; /* Name of test */
Chris Craikb50c2172013-07-29 15:28:30 -0700768 char error[256];
769
Alex Naidis7a055fd2016-10-01 12:23:07 +0200770 /* Share fields */
771 png_uint_32 chunklen; /* Length of chunk+overhead (chunkpos >= 8) */
772 png_uint_32 chunktype;/* Type of chunk (valid if chunkpos >= 4) */
773 png_uint_32 chunkpos; /* Position in chunk */
774 png_uint_32 IDAT_size;/* Accumulated IDAT size in .new */
775 unsigned int IDAT_bits;/* Cache of the file store value */
776
Chris Craikb50c2172013-07-29 15:28:30 -0700777 /* Read fields */
778 png_structp pread; /* Used to read a saved file */
779 png_infop piread;
780 png_store_file* current; /* Set when reading */
781 png_store_buffer* next; /* Set when reading */
xNombred07bb0d2020-03-10 20:17:12 +0100782 size_t readpos; /* Position in *next */
Chris Craikb50c2172013-07-29 15:28:30 -0700783 png_byte* image; /* Buffer for reading interlaced images */
xNombred07bb0d2020-03-10 20:17:12 +0100784 size_t cb_image; /* Size of this buffer */
785 size_t cb_row; /* Row size of the image(s) */
Alex Naidis7a055fd2016-10-01 12:23:07 +0200786 uLong IDAT_crc;
787 png_uint_32 IDAT_len; /* Used when re-chunking IDAT chunks */
788 png_uint_32 IDAT_pos; /* Used when re-chunking IDAT chunks */
Chris Craikb50c2172013-07-29 15:28:30 -0700789 png_uint_32 image_h; /* Number of rows in a single image */
790 store_pool read_memory_pool;
791
792 /* Write fields */
793 png_store_file* saved;
794 png_structp pwrite; /* Used when writing a new file */
795 png_infop piwrite;
xNombred07bb0d2020-03-10 20:17:12 +0100796 size_t writepos; /* Position in .new */
Chris Craikb50c2172013-07-29 15:28:30 -0700797 char wname[FILE_NAME_SIZE];
798 png_store_buffer new; /* The end of the new PNG file being written. */
799 store_pool write_memory_pool;
800 store_palette_entry* palette;
801 int npalette;
802} png_store;
803
804/* Initialization and cleanup */
805static void
806store_pool_mark(png_bytep mark)
807{
808 static png_uint_32 store_seed[2] = { 0x12345678, 1};
809
810 make_four_random_bytes(store_seed, mark);
811}
812
Matt Sarett9b1fe632015-11-25 10:21:17 -0500813#ifdef PNG_READ_TRANSFORMS_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -0700814/* Use this for random 32 bit values; this function makes sure the result is
815 * non-zero.
816 */
817static png_uint_32
818random_32(void)
819{
820
Matt Sarett9b1fe632015-11-25 10:21:17 -0500821 for (;;)
Chris Craikb50c2172013-07-29 15:28:30 -0700822 {
823 png_byte mark[4];
824 png_uint_32 result;
825
826 store_pool_mark(mark);
827 result = png_get_uint_32(mark);
828
829 if (result != 0)
830 return result;
831 }
832}
833#endif /* PNG_READ_SUPPORTED */
834
835static void
836store_pool_init(png_store *ps, store_pool *pool)
837{
838 memset(pool, 0, sizeof *pool);
839
840 pool->store = ps;
841 pool->list = NULL;
842 pool->max = pool->current = pool->limit = pool->total = 0;
843 pool->max_max = pool->max_limit = pool->max_total = 0;
844 store_pool_mark(pool->mark);
845}
846
847static void
848store_init(png_store* ps)
849{
850 memset(ps, 0, sizeof *ps);
851 init_exception_context(&ps->exception_context);
852 store_pool_init(ps, &ps->read_memory_pool);
853 store_pool_init(ps, &ps->write_memory_pool);
854 ps->verbose = 0;
855 ps->treat_warnings_as_errors = 0;
856 ps->expect_error = 0;
857 ps->expect_warning = 0;
858 ps->saw_warning = 0;
859 ps->speed = 0;
860 ps->progressive = 0;
861 ps->validated = 0;
862 ps->nerrors = ps->nwarnings = 0;
863 ps->pread = NULL;
864 ps->piread = NULL;
865 ps->saved = ps->current = NULL;
866 ps->next = NULL;
867 ps->readpos = 0;
868 ps->image = NULL;
869 ps->cb_image = 0;
870 ps->cb_row = 0;
871 ps->image_h = 0;
872 ps->pwrite = NULL;
873 ps->piwrite = NULL;
874 ps->writepos = 0;
Alex Naidis7a055fd2016-10-01 12:23:07 +0200875 ps->chunkpos = 8;
876 ps->chunktype = 0;
877 ps->chunklen = 16;
878 ps->IDAT_size = 0;
879 ps->IDAT_bits = 0;
Chris Craikb50c2172013-07-29 15:28:30 -0700880 ps->new.prev = NULL;
881 ps->palette = NULL;
882 ps->npalette = 0;
Sireesh Tripurarib478e662014-05-09 15:15:10 +0530883 ps->noptions = 0;
Chris Craikb50c2172013-07-29 15:28:30 -0700884}
885
886static void
887store_freebuffer(png_store_buffer* psb)
888{
889 if (psb->prev)
890 {
891 store_freebuffer(psb->prev);
892 free(psb->prev);
893 psb->prev = NULL;
894 }
895}
896
897static void
898store_freenew(png_store *ps)
899{
900 store_freebuffer(&ps->new);
901 ps->writepos = 0;
Alex Naidis7a055fd2016-10-01 12:23:07 +0200902 ps->chunkpos = 8;
903 ps->chunktype = 0;
904 ps->chunklen = 16;
905 ps->IDAT_size = 0;
906 ps->IDAT_bits = 0;
Chris Craikb50c2172013-07-29 15:28:30 -0700907 if (ps->palette != NULL)
908 {
909 free(ps->palette);
910 ps->palette = NULL;
911 ps->npalette = 0;
912 }
913}
914
915static void
916store_storenew(png_store *ps)
917{
918 png_store_buffer *pb;
919
Chris Craikb50c2172013-07-29 15:28:30 -0700920 pb = voidcast(png_store_buffer*, malloc(sizeof *pb));
921
922 if (pb == NULL)
923 png_error(ps->pwrite, "store new: OOM");
924
925 *pb = ps->new;
926 ps->new.prev = pb;
927 ps->writepos = 0;
928}
929
930static void
931store_freefile(png_store_file **ppf)
932{
933 if (*ppf != NULL)
934 {
935 store_freefile(&(*ppf)->next);
936
937 store_freebuffer(&(*ppf)->data);
938 (*ppf)->datacount = 0;
939 if ((*ppf)->palette != NULL)
940 {
941 free((*ppf)->palette);
942 (*ppf)->palette = NULL;
943 (*ppf)->npalette = 0;
944 }
945 free(*ppf);
946 *ppf = NULL;
947 }
948}
949
Alex Naidis7a055fd2016-10-01 12:23:07 +0200950static unsigned int
951bits_of(png_uint_32 num)
952{
953 /* Return the number of bits in 'num' */
954 unsigned int b = 0;
955
956 if (num & 0xffff0000U) b += 16U, num >>= 16;
957 if (num & 0xff00U) b += 8U, num >>= 8;
958 if (num & 0xf0U) b += 4U, num >>= 4;
959 if (num & 0xcU) b += 2U, num >>= 2;
960 if (num & 0x2U) ++b, num >>= 1;
961 if (num) ++b;
962
963 return b; /* 0..32 */
964}
965
xNombred07bb0d2020-03-10 20:17:12 +0100966/* Main interface to file storage, after writing a new PNG file (see the API
Chris Craikb50c2172013-07-29 15:28:30 -0700967 * below) call store_storefile to store the result with the given name and id.
968 */
969static void
970store_storefile(png_store *ps, png_uint_32 id)
971{
Alex Naidis7a055fd2016-10-01 12:23:07 +0200972 png_store_file *pf;
973
974 if (ps->chunkpos != 0U || ps->chunktype != 0U || ps->chunklen != 0U ||
975 ps->IDAT_size == 0)
976 png_error(ps->pwrite, "storefile: incomplete write");
977
978 pf = voidcast(png_store_file*, malloc(sizeof *pf));
Chris Craikb50c2172013-07-29 15:28:30 -0700979 if (pf == NULL)
980 png_error(ps->pwrite, "storefile: OOM");
981 safecat(pf->name, sizeof pf->name, 0, ps->wname);
982 pf->id = id;
983 pf->data = ps->new;
984 pf->datacount = ps->writepos;
Alex Naidis7a055fd2016-10-01 12:23:07 +0200985 pf->IDAT_size = ps->IDAT_size;
986 pf->IDAT_bits = bits_of(ps->IDAT_size);
987 /* Because the IDAT always has zlib header stuff this must be true: */
988 if (pf->IDAT_bits == 0U)
989 png_error(ps->pwrite, "storefile: 0 sized IDAT");
Chris Craikb50c2172013-07-29 15:28:30 -0700990 ps->new.prev = NULL;
991 ps->writepos = 0;
Alex Naidis7a055fd2016-10-01 12:23:07 +0200992 ps->chunkpos = 8;
993 ps->chunktype = 0;
994 ps->chunklen = 16;
995 ps->IDAT_size = 0;
Chris Craikb50c2172013-07-29 15:28:30 -0700996 pf->palette = ps->palette;
997 pf->npalette = ps->npalette;
998 ps->palette = 0;
999 ps->npalette = 0;
1000
1001 /* And save it. */
1002 pf->next = ps->saved;
1003 ps->saved = pf;
1004}
1005
1006/* Generate an error message (in the given buffer) */
1007static size_t
1008store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize,
Matt Sarett9b1fe632015-11-25 10:21:17 -05001009 size_t pos, const char *msg)
Chris Craikb50c2172013-07-29 15:28:30 -07001010{
1011 if (pp != NULL && pp == ps->pread)
1012 {
1013 /* Reading a file */
1014 pos = safecat(buffer, bufsize, pos, "read: ");
1015
1016 if (ps->current != NULL)
1017 {
1018 pos = safecat(buffer, bufsize, pos, ps->current->name);
1019 pos = safecat(buffer, bufsize, pos, sep);
1020 }
1021 }
1022
1023 else if (pp != NULL && pp == ps->pwrite)
1024 {
1025 /* Writing a file */
1026 pos = safecat(buffer, bufsize, pos, "write: ");
1027 pos = safecat(buffer, bufsize, pos, ps->wname);
1028 pos = safecat(buffer, bufsize, pos, sep);
1029 }
1030
1031 else
1032 {
1033 /* Neither reading nor writing (or a memory error in struct delete) */
1034 pos = safecat(buffer, bufsize, pos, "pngvalid: ");
1035 }
1036
1037 if (ps->test[0] != 0)
1038 {
1039 pos = safecat(buffer, bufsize, pos, ps->test);
1040 pos = safecat(buffer, bufsize, pos, sep);
1041 }
1042 pos = safecat(buffer, bufsize, pos, msg);
1043 return pos;
1044}
1045
1046/* Verbose output to the error stream: */
1047static void
1048store_verbose(png_store *ps, png_const_structp pp, png_const_charp prefix,
1049 png_const_charp message)
1050{
1051 char buffer[512];
1052
1053 if (prefix)
1054 fputs(prefix, stderr);
1055
1056 (void)store_message(ps, pp, buffer, sizeof buffer, 0, message);
1057 fputs(buffer, stderr);
1058 fputc('\n', stderr);
1059}
1060
1061/* Log an error or warning - the relevant count is always incremented. */
1062static void
1063store_log(png_store* ps, png_const_structp pp, png_const_charp message,
1064 int is_error)
1065{
1066 /* The warning is copied to the error buffer if there are no errors and it is
1067 * the first warning. The error is copied to the error buffer if it is the
1068 * first error (overwriting any prior warnings).
1069 */
1070 if (is_error ? (ps->nerrors)++ == 0 :
1071 (ps->nwarnings)++ == 0 && ps->nerrors == 0)
1072 store_message(ps, pp, ps->error, sizeof ps->error, 0, message);
1073
1074 if (ps->verbose)
1075 store_verbose(ps, pp, is_error ? "error: " : "warning: ", message);
1076}
1077
1078#ifdef PNG_READ_SUPPORTED
1079/* Internal error function, called with a png_store but no libpng stuff. */
1080static void
1081internal_error(png_store *ps, png_const_charp message)
1082{
1083 store_log(ps, NULL, message, 1 /* error */);
1084
1085 /* And finally throw an exception. */
1086 {
1087 struct exception_context *the_exception_context = &ps->exception_context;
1088 Throw ps;
1089 }
1090}
1091#endif /* PNG_READ_SUPPORTED */
1092
1093/* Functions to use as PNG callbacks. */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301094static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07001095store_error(png_structp ppIn, png_const_charp message) /* PNG_NORETURN */
1096{
1097 png_const_structp pp = ppIn;
1098 png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
1099
1100 if (!ps->expect_error)
1101 store_log(ps, pp, message, 1 /* error */);
1102
1103 /* And finally throw an exception. */
1104 {
1105 struct exception_context *the_exception_context = &ps->exception_context;
1106 Throw ps;
1107 }
1108}
1109
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301110static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07001111store_warning(png_structp ppIn, png_const_charp message)
1112{
1113 png_const_structp pp = ppIn;
1114 png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
1115
1116 if (!ps->expect_warning)
1117 store_log(ps, pp, message, 0 /* warning */);
1118 else
1119 ps->saw_warning = 1;
1120}
1121
1122/* These somewhat odd functions are used when reading an image to ensure that
1123 * the buffer is big enough, the png_structp is for errors.
1124 */
1125/* Return a single row from the correct image. */
1126static png_bytep
Matt Sarett9b1fe632015-11-25 10:21:17 -05001127store_image_row(const png_store* ps, png_const_structp pp, int nImage,
Chris Craikb50c2172013-07-29 15:28:30 -07001128 png_uint_32 y)
1129{
xNombred07bb0d2020-03-10 20:17:12 +01001130 size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2;
Chris Craikb50c2172013-07-29 15:28:30 -07001131
1132 if (ps->image == NULL)
1133 png_error(pp, "no allocated image");
1134
1135 if (coffset + ps->cb_row + 3 > ps->cb_image)
1136 png_error(pp, "image too small");
1137
1138 return ps->image + coffset;
1139}
1140
1141static void
1142store_image_free(png_store *ps, png_const_structp pp)
1143{
1144 if (ps->image != NULL)
1145 {
1146 png_bytep image = ps->image;
1147
1148 if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
1149 {
1150 if (pp != NULL)
1151 png_error(pp, "png_store image overwrite (1)");
1152 else
1153 store_log(ps, NULL, "png_store image overwrite (2)", 1);
1154 }
1155
1156 ps->image = NULL;
1157 ps->cb_image = 0;
1158 --image;
1159 free(image);
1160 }
1161}
1162
1163static void
1164store_ensure_image(png_store *ps, png_const_structp pp, int nImages,
xNombred07bb0d2020-03-10 20:17:12 +01001165 size_t cbRow, png_uint_32 cRows)
Chris Craikb50c2172013-07-29 15:28:30 -07001166{
xNombred07bb0d2020-03-10 20:17:12 +01001167 size_t cb = nImages * cRows * (cbRow + 5);
Chris Craikb50c2172013-07-29 15:28:30 -07001168
1169 if (ps->cb_image < cb)
1170 {
1171 png_bytep image;
1172
1173 store_image_free(ps, pp);
1174
1175 /* The buffer is deliberately mis-aligned. */
1176 image = voidcast(png_bytep, malloc(cb+2));
1177 if (image == NULL)
1178 {
1179 /* Called from the startup - ignore the error for the moment. */
1180 if (pp == NULL)
1181 return;
1182
1183 png_error(pp, "OOM allocating image buffer");
1184 }
1185
1186 /* These magic tags are used to detect overwrites above. */
1187 ++image;
1188 image[-1] = 0xed;
1189 image[cb] = 0xfe;
1190
1191 ps->image = image;
1192 ps->cb_image = cb;
1193 }
1194
1195 /* We have an adequate sized image; lay out the rows. There are 2 bytes at
1196 * the start and three at the end of each (this ensures that the row
1197 * alignment starts out odd - 2+1 and changes for larger images on each row.)
1198 */
1199 ps->cb_row = cbRow;
1200 ps->image_h = cRows;
1201
1202 /* For error checking, the whole buffer is set to 10110010 (0xb2 - 178).
1203 * This deliberately doesn't match the bits in the size test image which are
1204 * outside the image; these are set to 0xff (all 1). To make the row
1205 * comparison work in the 'size' test case the size rows are pre-initialized
1206 * to the same value prior to calling 'standard_row'.
1207 */
1208 memset(ps->image, 178, cb);
1209
1210 /* Then put in the marks. */
1211 while (--nImages >= 0)
1212 {
1213 png_uint_32 y;
1214
1215 for (y=0; y<cRows; ++y)
1216 {
1217 png_bytep row = store_image_row(ps, pp, nImages, y);
1218
1219 /* The markers: */
1220 row[-2] = 190;
1221 row[-1] = 239;
1222 row[cbRow] = 222;
1223 row[cbRow+1] = 173;
1224 row[cbRow+2] = 17;
1225 }
1226 }
1227}
1228
1229#ifdef PNG_READ_SUPPORTED
1230static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05001231store_image_check(const png_store* ps, png_const_structp pp, int iImage)
Chris Craikb50c2172013-07-29 15:28:30 -07001232{
1233 png_const_bytep image = ps->image;
1234
1235 if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
1236 png_error(pp, "image overwrite");
1237 else
1238 {
xNombred07bb0d2020-03-10 20:17:12 +01001239 size_t cbRow = ps->cb_row;
Chris Craikb50c2172013-07-29 15:28:30 -07001240 png_uint_32 rows = ps->image_h;
1241
1242 image += iImage * (cbRow+5) * ps->image_h;
1243
1244 image += 2; /* skip image first row markers */
1245
Leon Scroggins III3cc83ac2017-10-06 11:02:56 -04001246 for (; rows > 0; --rows)
Chris Craikb50c2172013-07-29 15:28:30 -07001247 {
1248 if (image[-2] != 190 || image[-1] != 239)
1249 png_error(pp, "row start overwritten");
1250
1251 if (image[cbRow] != 222 || image[cbRow+1] != 173 ||
1252 image[cbRow+2] != 17)
1253 png_error(pp, "row end overwritten");
1254
1255 image += cbRow+5;
1256 }
1257 }
1258}
1259#endif /* PNG_READ_SUPPORTED */
1260
Alex Naidis7a055fd2016-10-01 12:23:07 +02001261static int
1262valid_chunktype(png_uint_32 chunktype)
1263{
1264 /* Each byte in the chunk type must be in one of the ranges 65..90, 97..122
1265 * (both inclusive), so:
1266 */
1267 unsigned int i;
1268
1269 for (i=0; i<4; ++i)
1270 {
1271 unsigned int c = chunktype & 0xffU;
1272
1273 if (!((c >= 65U && c <= 90U) || (c >= 97U && c <= 122U)))
1274 return 0;
1275
1276 chunktype >>= 8;
1277 }
1278
1279 return 1; /* It's valid */
1280}
1281
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301282static void PNGCBAPI
xNombred07bb0d2020-03-10 20:17:12 +01001283store_write(png_structp ppIn, png_bytep pb, size_t st)
Chris Craikb50c2172013-07-29 15:28:30 -07001284{
1285 png_const_structp pp = ppIn;
1286 png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
Alex Naidis7a055fd2016-10-01 12:23:07 +02001287 size_t writepos = ps->writepos;
1288 png_uint_32 chunkpos = ps->chunkpos;
1289 png_uint_32 chunktype = ps->chunktype;
1290 png_uint_32 chunklen = ps->chunklen;
Chris Craikb50c2172013-07-29 15:28:30 -07001291
1292 if (ps->pwrite != pp)
1293 png_error(pp, "store state damaged");
1294
Alex Naidis7a055fd2016-10-01 12:23:07 +02001295 /* Technically this is legal, but in practice libpng never writes more than
1296 * the maximum chunk size at once so if it happens something weird has
1297 * changed inside libpng (probably).
1298 */
1299 if (st > 0x7fffffffU)
1300 png_error(pp, "unexpected write size");
1301
1302 /* Now process the bytes to be written. Do this in units of the space in the
1303 * output (write) buffer or, at the start 4 bytes for the chunk type and
1304 * length limited in any case by the amount of data.
1305 */
Chris Craikb50c2172013-07-29 15:28:30 -07001306 while (st > 0)
1307 {
Alex Naidis7a055fd2016-10-01 12:23:07 +02001308 if (writepos >= STORE_BUFFER_SIZE)
1309 store_storenew(ps), writepos = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07001310
Alex Naidis7a055fd2016-10-01 12:23:07 +02001311 if (chunkpos < 4)
1312 {
1313 png_byte b = *pb++;
1314 --st;
1315 chunklen = (chunklen << 8) + b;
1316 ps->new.buffer[writepos++] = b;
1317 ++chunkpos;
1318 }
Chris Craikb50c2172013-07-29 15:28:30 -07001319
Alex Naidis7a055fd2016-10-01 12:23:07 +02001320 else if (chunkpos < 8)
1321 {
1322 png_byte b = *pb++;
1323 --st;
1324 chunktype = (chunktype << 8) + b;
1325 ps->new.buffer[writepos++] = b;
Chris Craikb50c2172013-07-29 15:28:30 -07001326
Alex Naidis7a055fd2016-10-01 12:23:07 +02001327 if (++chunkpos == 8)
1328 {
1329 chunklen &= 0xffffffffU;
1330 if (chunklen > 0x7fffffffU)
1331 png_error(pp, "chunk length too great");
Chris Craikb50c2172013-07-29 15:28:30 -07001332
Alex Naidis7a055fd2016-10-01 12:23:07 +02001333 chunktype &= 0xffffffffU;
1334 if (chunktype == CHUNK_IDAT)
1335 {
1336 if (chunklen > ~ps->IDAT_size)
1337 png_error(pp, "pngvalid internal image too large");
1338
1339 ps->IDAT_size += chunklen;
1340 }
1341
1342 else if (!valid_chunktype(chunktype))
1343 png_error(pp, "invalid chunk type");
1344
1345 chunklen += 12; /* for header and CRC */
1346 }
1347 }
1348
1349 else /* chunkpos >= 8 */
1350 {
xNombred07bb0d2020-03-10 20:17:12 +01001351 size_t cb = st;
Alex Naidis7a055fd2016-10-01 12:23:07 +02001352
1353 if (cb > STORE_BUFFER_SIZE - writepos)
1354 cb = STORE_BUFFER_SIZE - writepos;
1355
1356 if (cb > chunklen - chunkpos/* bytes left in chunk*/)
xNombred07bb0d2020-03-10 20:17:12 +01001357 cb = (size_t)/*SAFE*/(chunklen - chunkpos);
Alex Naidis7a055fd2016-10-01 12:23:07 +02001358
1359 memcpy(ps->new.buffer + writepos, pb, cb);
1360 chunkpos += (png_uint_32)/*SAFE*/cb;
1361 pb += cb;
1362 writepos += cb;
1363 st -= cb;
1364
1365 if (chunkpos >= chunklen) /* must be equal */
1366 chunkpos = chunktype = chunklen = 0;
1367 }
1368 } /* while (st > 0) */
1369
1370 ps->writepos = writepos;
1371 ps->chunkpos = chunkpos;
1372 ps->chunktype = chunktype;
1373 ps->chunklen = chunklen;
Chris Craikb50c2172013-07-29 15:28:30 -07001374}
1375
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301376static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07001377store_flush(png_structp ppIn)
1378{
1379 UNUSED(ppIn) /*DOES NOTHING*/
1380}
1381
1382#ifdef PNG_READ_SUPPORTED
1383static size_t
1384store_read_buffer_size(png_store *ps)
1385{
1386 /* Return the bytes available for read in the current buffer. */
1387 if (ps->next != &ps->current->data)
1388 return STORE_BUFFER_SIZE;
1389
1390 return ps->current->datacount;
1391}
1392
Chris Craikb50c2172013-07-29 15:28:30 -07001393/* Return total bytes available for read. */
1394static size_t
1395store_read_buffer_avail(png_store *ps)
1396{
1397 if (ps->current != NULL && ps->next != NULL)
1398 {
1399 png_store_buffer *next = &ps->current->data;
1400 size_t cbAvail = ps->current->datacount;
1401
1402 while (next != ps->next && next != NULL)
1403 {
1404 next = next->prev;
1405 cbAvail += STORE_BUFFER_SIZE;
1406 }
1407
1408 if (next != ps->next)
1409 png_error(ps->pread, "buffer read error");
1410
1411 if (cbAvail > ps->readpos)
1412 return cbAvail - ps->readpos;
1413 }
1414
1415 return 0;
1416}
Chris Craikb50c2172013-07-29 15:28:30 -07001417
1418static int
1419store_read_buffer_next(png_store *ps)
1420{
1421 png_store_buffer *pbOld = ps->next;
1422 png_store_buffer *pbNew = &ps->current->data;
1423 if (pbOld != pbNew)
1424 {
1425 while (pbNew != NULL && pbNew->prev != pbOld)
1426 pbNew = pbNew->prev;
1427
1428 if (pbNew != NULL)
1429 {
1430 ps->next = pbNew;
1431 ps->readpos = 0;
1432 return 1;
1433 }
1434
1435 png_error(ps->pread, "buffer lost");
1436 }
1437
1438 return 0; /* EOF or error */
1439}
1440
1441/* Need separate implementation and callback to allow use of the same code
1442 * during progressive read, where the io_ptr is set internally by libpng.
1443 */
1444static void
xNombred07bb0d2020-03-10 20:17:12 +01001445store_read_imp(png_store *ps, png_bytep pb, size_t st)
Chris Craikb50c2172013-07-29 15:28:30 -07001446{
1447 if (ps->current == NULL || ps->next == NULL)
1448 png_error(ps->pread, "store state damaged");
1449
1450 while (st > 0)
1451 {
1452 size_t cbAvail = store_read_buffer_size(ps) - ps->readpos;
1453
1454 if (cbAvail > 0)
1455 {
1456 if (cbAvail > st) cbAvail = st;
1457 memcpy(pb, ps->next->buffer + ps->readpos, cbAvail);
1458 st -= cbAvail;
1459 pb += cbAvail;
1460 ps->readpos += cbAvail;
1461 }
1462
1463 else if (!store_read_buffer_next(ps))
1464 png_error(ps->pread, "read beyond end of file");
1465 }
1466}
1467
xNombred07bb0d2020-03-10 20:17:12 +01001468static size_t
1469store_read_chunk(png_store *ps, png_bytep pb, size_t max, size_t min)
Alex Naidis7a055fd2016-10-01 12:23:07 +02001470{
1471 png_uint_32 chunklen = ps->chunklen;
1472 png_uint_32 chunktype = ps->chunktype;
1473 png_uint_32 chunkpos = ps->chunkpos;
xNombred07bb0d2020-03-10 20:17:12 +01001474 size_t st = max;
Alex Naidis7a055fd2016-10-01 12:23:07 +02001475
1476 if (st > 0) do
1477 {
1478 if (chunkpos >= chunklen) /* end of last chunk */
1479 {
1480 png_byte buffer[8];
1481
1482 /* Read the header of the next chunk: */
1483 store_read_imp(ps, buffer, 8U);
1484 chunklen = png_get_uint_32(buffer) + 12U;
1485 chunktype = png_get_uint_32(buffer+4U);
1486 chunkpos = 0U; /* Position read so far */
1487 }
1488
1489 if (chunktype == CHUNK_IDAT)
1490 {
1491 png_uint_32 IDAT_pos = ps->IDAT_pos;
1492 png_uint_32 IDAT_len = ps->IDAT_len;
1493 png_uint_32 IDAT_size = ps->IDAT_size;
1494
1495 /* The IDAT headers are constructed here; skip the input header. */
1496 if (chunkpos < 8U)
1497 chunkpos = 8U;
1498
1499 if (IDAT_pos == IDAT_len)
1500 {
1501 png_byte random = random_byte();
1502
1503 /* Make a new IDAT chunk, if IDAT_len is 0 this is the first IDAT,
1504 * if IDAT_size is 0 this is the end. At present this is set up
1505 * using a random number so that there is a 25% chance before
1506 * the start of the first IDAT chunk being 0 length.
1507 */
1508 if (IDAT_len == 0U) /* First IDAT */
1509 {
1510 switch (random & 3U)
1511 {
1512 case 0U: IDAT_len = 12U; break; /* 0 bytes */
1513 case 1U: IDAT_len = 13U; break; /* 1 byte */
1514 default: IDAT_len = random_u32();
1515 IDAT_len %= IDAT_size;
1516 IDAT_len += 13U; /* 1..IDAT_size bytes */
1517 break;
1518 }
1519 }
1520
1521 else if (IDAT_size == 0U) /* all IDAT data read */
1522 {
1523 /* The last (IDAT) chunk should be positioned at the CRC now: */
1524 if (chunkpos != chunklen-4U)
1525 png_error(ps->pread, "internal: IDAT size mismatch");
1526
1527 /* The only option here is to add a zero length IDAT, this
1528 * happens 25% of the time. Because of the check above
1529 * chunklen-4U-chunkpos must be zero, we just need to skip the
1530 * CRC now.
1531 */
1532 if ((random & 3U) == 0U)
1533 IDAT_len = 12U; /* Output another 0 length IDAT */
1534
1535 else
1536 {
1537 /* End of IDATs, skip the CRC to make the code above load the
1538 * next chunk header next time round.
1539 */
1540 png_byte buffer[4];
1541
1542 store_read_imp(ps, buffer, 4U);
1543 chunkpos += 4U;
1544 ps->IDAT_pos = IDAT_pos;
1545 ps->IDAT_len = IDAT_len;
1546 ps->IDAT_size = 0U;
1547 continue; /* Read the next chunk */
1548 }
1549 }
1550
1551 else
1552 {
1553 /* Middle of IDATs, use 'random' to determine the number of bits
1554 * to use in the IDAT length.
1555 */
1556 IDAT_len = random_u32();
1557 IDAT_len &= (1U << (1U + random % ps->IDAT_bits)) - 1U;
1558 if (IDAT_len > IDAT_size)
1559 IDAT_len = IDAT_size;
1560 IDAT_len += 12U; /* zero bytes may occur */
1561 }
1562
1563 IDAT_pos = 0U;
1564 ps->IDAT_crc = 0x35af061e; /* Ie: crc32(0UL, "IDAT", 4) */
1565 } /* IDAT_pos == IDAT_len */
1566
1567 if (IDAT_pos < 8U) /* Return the header */ do
1568 {
1569 png_uint_32 b;
1570 unsigned int shift;
1571
1572 if (IDAT_pos < 4U)
1573 b = IDAT_len - 12U;
1574
1575 else
1576 b = CHUNK_IDAT;
1577
1578 shift = 3U & IDAT_pos;
1579 ++IDAT_pos;
1580
1581 if (shift < 3U)
1582 b >>= 8U*(3U-shift);
1583
1584 *pb++ = 0xffU & b;
1585 }
1586 while (--st > 0 && IDAT_pos < 8);
1587
1588 else if (IDAT_pos < IDAT_len - 4U) /* I.e not the CRC */
1589 {
1590 if (chunkpos < chunklen-4U)
1591 {
1592 uInt avail = (uInt)-1;
1593
1594 if (avail > (IDAT_len-4U) - IDAT_pos)
1595 avail = (uInt)/*SAFE*/((IDAT_len-4U) - IDAT_pos);
1596
1597 if (avail > st)
1598 avail = (uInt)/*SAFE*/st;
1599
1600 if (avail > (chunklen-4U) - chunkpos)
1601 avail = (uInt)/*SAFE*/((chunklen-4U) - chunkpos);
1602
1603 store_read_imp(ps, pb, avail);
1604 ps->IDAT_crc = crc32(ps->IDAT_crc, pb, avail);
xNombred07bb0d2020-03-10 20:17:12 +01001605 pb += (size_t)/*SAFE*/avail;
1606 st -= (size_t)/*SAFE*/avail;
Alex Naidis7a055fd2016-10-01 12:23:07 +02001607 chunkpos += (png_uint_32)/*SAFE*/avail;
1608 IDAT_size -= (png_uint_32)/*SAFE*/avail;
1609 IDAT_pos += (png_uint_32)/*SAFE*/avail;
1610 }
1611
1612 else /* skip the input CRC */
1613 {
1614 png_byte buffer[4];
1615
1616 store_read_imp(ps, buffer, 4U);
1617 chunkpos += 4U;
1618 }
1619 }
1620
1621 else /* IDAT crc */ do
1622 {
1623 uLong b = ps->IDAT_crc;
1624 unsigned int shift = (IDAT_len - IDAT_pos); /* 4..1 */
1625 ++IDAT_pos;
1626
1627 if (shift > 1U)
1628 b >>= 8U*(shift-1U);
1629
1630 *pb++ = 0xffU & b;
1631 }
1632 while (--st > 0 && IDAT_pos < IDAT_len);
1633
1634 ps->IDAT_pos = IDAT_pos;
1635 ps->IDAT_len = IDAT_len;
1636 ps->IDAT_size = IDAT_size;
1637 }
1638
1639 else /* !IDAT */
1640 {
1641 /* If there is still some pending IDAT data after the IDAT chunks have
1642 * been processed there is a problem:
1643 */
1644 if (ps->IDAT_len > 0 && ps->IDAT_size > 0)
1645 png_error(ps->pread, "internal: missing IDAT data");
1646
1647 if (chunktype == CHUNK_IEND && ps->IDAT_len == 0U)
1648 png_error(ps->pread, "internal: missing IDAT");
1649
1650 if (chunkpos < 8U) /* Return the header */ do
1651 {
1652 png_uint_32 b;
1653 unsigned int shift;
1654
1655 if (chunkpos < 4U)
1656 b = chunklen - 12U;
1657
1658 else
1659 b = chunktype;
1660
1661 shift = 3U & chunkpos;
1662 ++chunkpos;
1663
1664 if (shift < 3U)
1665 b >>= 8U*(3U-shift);
1666
1667 *pb++ = 0xffU & b;
1668 }
1669 while (--st > 0 && chunkpos < 8);
1670
1671 else /* Return chunk bytes, including the CRC */
1672 {
xNombred07bb0d2020-03-10 20:17:12 +01001673 size_t avail = st;
Alex Naidis7a055fd2016-10-01 12:23:07 +02001674
1675 if (avail > chunklen - chunkpos)
xNombred07bb0d2020-03-10 20:17:12 +01001676 avail = (size_t)/*SAFE*/(chunklen - chunkpos);
Alex Naidis7a055fd2016-10-01 12:23:07 +02001677
1678 store_read_imp(ps, pb, avail);
1679 pb += avail;
1680 st -= avail;
1681 chunkpos += (png_uint_32)/*SAFE*/avail;
1682
1683 /* Check for end of chunk and end-of-file; don't try to read a new
1684 * chunk header at this point unless instructed to do so by 'min'.
1685 */
1686 if (chunkpos >= chunklen && max-st >= min &&
1687 store_read_buffer_avail(ps) == 0)
1688 break;
1689 }
1690 } /* !IDAT */
1691 }
1692 while (st > 0);
1693
1694 ps->chunklen = chunklen;
1695 ps->chunktype = chunktype;
1696 ps->chunkpos = chunkpos;
1697
1698 return st; /* space left */
1699}
1700
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301701static void PNGCBAPI
xNombred07bb0d2020-03-10 20:17:12 +01001702store_read(png_structp ppIn, png_bytep pb, size_t st)
Chris Craikb50c2172013-07-29 15:28:30 -07001703{
1704 png_const_structp pp = ppIn;
1705 png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
1706
1707 if (ps == NULL || ps->pread != pp)
1708 png_error(pp, "bad store read call");
1709
Alex Naidis7a055fd2016-10-01 12:23:07 +02001710 store_read_chunk(ps, pb, st, st);
Chris Craikb50c2172013-07-29 15:28:30 -07001711}
1712
1713static void
1714store_progressive_read(png_store *ps, png_structp pp, png_infop pi)
1715{
Chris Craikb50c2172013-07-29 15:28:30 -07001716 if (ps->pread != pp || ps->current == NULL || ps->next == NULL)
1717 png_error(pp, "store state damaged (progressive)");
1718
Alex Naidis7a055fd2016-10-01 12:23:07 +02001719 /* This is another Horowitz and Hill random noise generator. In this case
1720 * the aim is to stress the progressive reader with truly horrible variable
1721 * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers
1722 * is generated. We could probably just count from 1 to 32767 and get as
1723 * good a result.
1724 */
1725 while (store_read_buffer_avail(ps) > 0)
Chris Craikb50c2172013-07-29 15:28:30 -07001726 {
Alex Naidis7a055fd2016-10-01 12:23:07 +02001727 static png_uint_32 noise = 2;
xNombred07bb0d2020-03-10 20:17:12 +01001728 size_t cb;
Alex Naidis7a055fd2016-10-01 12:23:07 +02001729 png_byte buffer[512];
Chris Craikb50c2172013-07-29 15:28:30 -07001730
Alex Naidis7a055fd2016-10-01 12:23:07 +02001731 /* Generate 15 more bits of stuff: */
1732 noise = (noise << 9) | ((noise ^ (noise >> (9-5))) & 0x1ff);
1733 cb = noise & 0x1ff;
1734 cb -= store_read_chunk(ps, buffer, cb, 1);
1735 png_process_data(pp, pi, buffer, cb);
Chris Craikb50c2172013-07-29 15:28:30 -07001736 }
Chris Craikb50c2172013-07-29 15:28:30 -07001737}
1738#endif /* PNG_READ_SUPPORTED */
1739
1740/* The caller must fill this in: */
1741static store_palette_entry *
1742store_write_palette(png_store *ps, int npalette)
1743{
1744 if (ps->pwrite == NULL)
1745 store_log(ps, NULL, "attempt to write palette without write stream", 1);
1746
1747 if (ps->palette != NULL)
1748 png_error(ps->pwrite, "multiple store_write_palette calls");
1749
1750 /* This function can only return NULL if called with '0'! */
1751 if (npalette > 0)
1752 {
1753 ps->palette = voidcast(store_palette_entry*, malloc(npalette *
1754 sizeof *ps->palette));
1755
1756 if (ps->palette == NULL)
1757 png_error(ps->pwrite, "store new palette: OOM");
1758
1759 ps->npalette = npalette;
1760 }
1761
1762 return ps->palette;
1763}
1764
1765#ifdef PNG_READ_SUPPORTED
1766static store_palette_entry *
1767store_current_palette(png_store *ps, int *npalette)
1768{
1769 /* This is an internal error (the call has been made outside a read
1770 * operation.)
1771 */
1772 if (ps->current == NULL)
Matt Sarett9b1fe632015-11-25 10:21:17 -05001773 {
Chris Craikb50c2172013-07-29 15:28:30 -07001774 store_log(ps, ps->pread, "no current stream for palette", 1);
Matt Sarett9b1fe632015-11-25 10:21:17 -05001775 return NULL;
1776 }
Chris Craikb50c2172013-07-29 15:28:30 -07001777
1778 /* The result may be null if there is no palette. */
1779 *npalette = ps->current->npalette;
1780 return ps->current->palette;
1781}
1782#endif /* PNG_READ_SUPPORTED */
1783
1784/***************************** MEMORY MANAGEMENT*** ***************************/
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301785#ifdef PNG_USER_MEM_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07001786/* A store_memory is simply the header for an allocated block of memory. The
1787 * pointer returned to libpng is just after the end of the header block, the
1788 * allocated memory is followed by a second copy of the 'mark'.
1789 */
1790typedef struct store_memory
1791{
1792 store_pool *pool; /* Originating pool */
1793 struct store_memory *next; /* Singly linked list */
1794 png_alloc_size_t size; /* Size of memory allocated */
1795 png_byte mark[4]; /* ID marker */
1796} store_memory;
1797
1798/* Handle a fatal error in memory allocation. This calls png_error if the
1799 * libpng struct is non-NULL, else it outputs a message and returns. This means
1800 * that a memory problem while libpng is running will abort (png_error) the
1801 * handling of particular file while one in cleanup (after the destroy of the
1802 * struct has returned) will simply keep going and free (or attempt to free)
1803 * all the memory.
1804 */
1805static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05001806store_pool_error(png_store *ps, png_const_structp pp, const char *msg)
Chris Craikb50c2172013-07-29 15:28:30 -07001807{
1808 if (pp != NULL)
1809 png_error(pp, msg);
1810
1811 /* Else we have to do it ourselves. png_error eventually calls store_log,
1812 * above. store_log accepts a NULL png_structp - it just changes what gets
1813 * output by store_message.
1814 */
1815 store_log(ps, pp, msg, 1 /* error */);
1816}
1817
1818static void
1819store_memory_free(png_const_structp pp, store_pool *pool, store_memory *memory)
1820{
1821 /* Note that pp may be NULL (see store_pool_delete below), the caller has
1822 * found 'memory' in pool->list *and* unlinked this entry, so this is a valid
1823 * pointer (for sure), but the contents may have been trashed.
1824 */
1825 if (memory->pool != pool)
1826 store_pool_error(pool->store, pp, "memory corrupted (pool)");
1827
1828 else if (memcmp(memory->mark, pool->mark, sizeof memory->mark) != 0)
1829 store_pool_error(pool->store, pp, "memory corrupted (start)");
1830
1831 /* It should be safe to read the size field now. */
1832 else
1833 {
1834 png_alloc_size_t cb = memory->size;
1835
1836 if (cb > pool->max)
1837 store_pool_error(pool->store, pp, "memory corrupted (size)");
1838
1839 else if (memcmp((png_bytep)(memory+1)+cb, pool->mark, sizeof pool->mark)
1840 != 0)
1841 store_pool_error(pool->store, pp, "memory corrupted (end)");
1842
1843 /* Finally give the library a chance to find problems too: */
1844 else
1845 {
1846 pool->current -= cb;
1847 free(memory);
1848 }
1849 }
1850}
1851
1852static void
1853store_pool_delete(png_store *ps, store_pool *pool)
1854{
1855 if (pool->list != NULL)
1856 {
1857 fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
1858 pool == &ps->read_memory_pool ? "read" : "write",
1859 pool == &ps->read_memory_pool ? (ps->current != NULL ?
1860 ps->current->name : "unknown file") : ps->wname);
1861 ++ps->nerrors;
1862
1863 do
1864 {
1865 store_memory *next = pool->list;
1866 pool->list = next->next;
1867 next->next = NULL;
1868
1869 fprintf(stderr, "\t%lu bytes @ %p\n",
Matt Sarett9b1fe632015-11-25 10:21:17 -05001870 (unsigned long)next->size, (const void*)(next+1));
Chris Craikb50c2172013-07-29 15:28:30 -07001871 /* The NULL means this will always return, even if the memory is
1872 * corrupted.
1873 */
1874 store_memory_free(NULL, pool, next);
1875 }
1876 while (pool->list != NULL);
1877 }
1878
1879 /* And reset the other fields too for the next time. */
1880 if (pool->max > pool->max_max) pool->max_max = pool->max;
1881 pool->max = 0;
1882 if (pool->current != 0) /* unexpected internal error */
1883 fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
1884 ps->test, pool == &ps->read_memory_pool ? "read" : "write",
1885 pool == &ps->read_memory_pool ? (ps->current != NULL ?
1886 ps->current->name : "unknown file") : ps->wname);
1887 pool->current = 0;
1888
1889 if (pool->limit > pool->max_limit)
1890 pool->max_limit = pool->limit;
1891
1892 pool->limit = 0;
1893
1894 if (pool->total > pool->max_total)
1895 pool->max_total = pool->total;
1896
1897 pool->total = 0;
1898
1899 /* Get a new mark too. */
1900 store_pool_mark(pool->mark);
1901}
1902
1903/* The memory callbacks: */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301904static png_voidp PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07001905store_malloc(png_structp ppIn, png_alloc_size_t cb)
1906{
1907 png_const_structp pp = ppIn;
1908 store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
1909 store_memory *new = voidcast(store_memory*, malloc(cb + (sizeof *new) +
1910 (sizeof pool->mark)));
1911
1912 if (new != NULL)
1913 {
1914 if (cb > pool->max)
1915 pool->max = cb;
1916
1917 pool->current += cb;
1918
1919 if (pool->current > pool->limit)
1920 pool->limit = pool->current;
1921
1922 pool->total += cb;
1923
1924 new->size = cb;
1925 memcpy(new->mark, pool->mark, sizeof new->mark);
1926 memcpy((png_byte*)(new+1) + cb, pool->mark, sizeof pool->mark);
1927 new->pool = pool;
1928 new->next = pool->list;
1929 pool->list = new;
1930 ++new;
1931 }
1932
1933 else
1934 {
1935 /* NOTE: the PNG user malloc function cannot use the png_ptr it is passed
1936 * other than to retrieve the allocation pointer! libpng calls the
1937 * store_malloc callback in two basic cases:
1938 *
1939 * 1) From png_malloc; png_malloc will do a png_error itself if NULL is
1940 * returned.
1941 * 2) From png_struct or png_info structure creation; png_malloc is
1942 * to return so cleanup can be performed.
1943 *
1944 * To handle this store_malloc can log a message, but can't do anything
1945 * else.
1946 */
1947 store_log(pool->store, pp, "out of memory", 1 /* is_error */);
1948 }
1949
1950 return new;
1951}
1952
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301953static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07001954store_free(png_structp ppIn, png_voidp memory)
1955{
1956 png_const_structp pp = ppIn;
1957 store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
1958 store_memory *this = voidcast(store_memory*, memory), **test;
1959
1960 /* Because libpng calls store_free with a dummy png_struct when deleting
1961 * png_struct or png_info via png_destroy_struct_2 it is necessary to check
1962 * the passed in png_structp to ensure it is valid, and not pass it to
1963 * png_error if it is not.
1964 */
1965 if (pp != pool->store->pread && pp != pool->store->pwrite)
1966 pp = NULL;
1967
1968 /* First check that this 'memory' really is valid memory - it must be in the
1969 * pool list. If it is, use the shared memory_free function to free it.
1970 */
1971 --this;
1972 for (test = &pool->list; *test != this; test = &(*test)->next)
1973 {
1974 if (*test == NULL)
1975 {
1976 store_pool_error(pool->store, pp, "bad pointer to free");
1977 return;
1978 }
1979 }
1980
1981 /* Unlink this entry, *test == this. */
1982 *test = this->next;
1983 this->next = NULL;
1984 store_memory_free(pp, pool, this);
1985}
Sireesh Tripurarib478e662014-05-09 15:15:10 +05301986#endif /* PNG_USER_MEM_SUPPORTED */
Chris Craikb50c2172013-07-29 15:28:30 -07001987
1988/* Setup functions. */
1989/* Cleanup when aborting a write or after storing the new file. */
1990static void
1991store_write_reset(png_store *ps)
1992{
1993 if (ps->pwrite != NULL)
1994 {
1995 anon_context(ps);
1996
1997 Try
1998 png_destroy_write_struct(&ps->pwrite, &ps->piwrite);
1999
2000 Catch_anonymous
2001 {
2002 /* memory corruption: continue. */
2003 }
2004
2005 ps->pwrite = NULL;
2006 ps->piwrite = NULL;
2007 }
2008
2009 /* And make sure that all the memory has been freed - this will output
2010 * spurious errors in the case of memory corruption above, but this is safe.
2011 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302012# ifdef PNG_USER_MEM_SUPPORTED
2013 store_pool_delete(ps, &ps->write_memory_pool);
2014# endif
Chris Craikb50c2172013-07-29 15:28:30 -07002015
2016 store_freenew(ps);
2017}
2018
2019/* The following is the main write function, it returns a png_struct and,
2020 * optionally, a png_info suitable for writiing a new PNG file. Use
2021 * store_storefile above to record this file after it has been written. The
2022 * returned libpng structures as destroyed by store_write_reset above.
2023 */
2024static png_structp
Matt Sarett9b1fe632015-11-25 10:21:17 -05002025set_store_for_write(png_store *ps, png_infopp ppi, const char *name)
Chris Craikb50c2172013-07-29 15:28:30 -07002026{
2027 anon_context(ps);
2028
2029 Try
2030 {
2031 if (ps->pwrite != NULL)
2032 png_error(ps->pwrite, "write store already in use");
2033
2034 store_write_reset(ps);
2035 safecat(ps->wname, sizeof ps->wname, 0, name);
2036
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302037 /* Don't do the slow memory checks if doing a speed test, also if user
2038 * memory is not supported we can't do it anyway.
2039 */
2040# ifdef PNG_USER_MEM_SUPPORTED
2041 if (!ps->speed)
2042 ps->pwrite = png_create_write_struct_2(PNG_LIBPNG_VER_STRING,
2043 ps, store_error, store_warning, &ps->write_memory_pool,
2044 store_malloc, store_free);
2045
2046 else
2047# endif
Chris Craikb50c2172013-07-29 15:28:30 -07002048 ps->pwrite = png_create_write_struct(PNG_LIBPNG_VER_STRING,
2049 ps, store_error, store_warning);
2050
Chris Craikb50c2172013-07-29 15:28:30 -07002051 png_set_write_fn(ps->pwrite, ps, store_write, store_flush);
2052
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302053# ifdef PNG_SET_OPTION_SUPPORTED
2054 {
2055 int opt;
2056 for (opt=0; opt<ps->noptions; ++opt)
2057 if (png_set_option(ps->pwrite, ps->options[opt].option,
2058 ps->options[opt].setting) == PNG_OPTION_INVALID)
2059 png_error(ps->pwrite, "png option invalid");
2060 }
2061# endif
2062
Chris Craikb50c2172013-07-29 15:28:30 -07002063 if (ppi != NULL)
2064 *ppi = ps->piwrite = png_create_info_struct(ps->pwrite);
2065 }
2066
2067 Catch_anonymous
2068 return NULL;
2069
2070 return ps->pwrite;
2071}
2072
2073/* Cleanup when finished reading (either due to error or in the success case).
2074 * This routine exists even when there is no read support to make the code
2075 * tidier (avoid a mass of ifdefs) and so easier to maintain.
2076 */
2077static void
2078store_read_reset(png_store *ps)
2079{
2080# ifdef PNG_READ_SUPPORTED
2081 if (ps->pread != NULL)
2082 {
2083 anon_context(ps);
2084
2085 Try
2086 png_destroy_read_struct(&ps->pread, &ps->piread, NULL);
2087
2088 Catch_anonymous
2089 {
2090 /* error already output: continue */
2091 }
2092
2093 ps->pread = NULL;
2094 ps->piread = NULL;
2095 }
2096# endif
2097
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302098# ifdef PNG_USER_MEM_SUPPORTED
2099 /* Always do this to be safe. */
2100 store_pool_delete(ps, &ps->read_memory_pool);
2101# endif
Chris Craikb50c2172013-07-29 15:28:30 -07002102
2103 ps->current = NULL;
2104 ps->next = NULL;
2105 ps->readpos = 0;
2106 ps->validated = 0;
Alex Naidis7a055fd2016-10-01 12:23:07 +02002107
2108 ps->chunkpos = 8;
2109 ps->chunktype = 0;
2110 ps->chunklen = 16;
2111 ps->IDAT_size = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07002112}
2113
2114#ifdef PNG_READ_SUPPORTED
2115static void
2116store_read_set(png_store *ps, png_uint_32 id)
2117{
2118 png_store_file *pf = ps->saved;
2119
2120 while (pf != NULL)
2121 {
2122 if (pf->id == id)
2123 {
2124 ps->current = pf;
2125 ps->next = NULL;
Alex Naidis7a055fd2016-10-01 12:23:07 +02002126 ps->IDAT_size = pf->IDAT_size;
2127 ps->IDAT_bits = pf->IDAT_bits; /* just a cache */
2128 ps->IDAT_len = 0;
2129 ps->IDAT_pos = 0;
2130 ps->IDAT_crc = 0UL;
Chris Craikb50c2172013-07-29 15:28:30 -07002131 store_read_buffer_next(ps);
2132 return;
2133 }
2134
2135 pf = pf->next;
2136 }
2137
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302138 {
Chris Craikb50c2172013-07-29 15:28:30 -07002139 size_t pos;
2140 char msg[FILE_NAME_SIZE+64];
2141
2142 pos = standard_name_from_id(msg, sizeof msg, 0, id);
2143 pos = safecat(msg, sizeof msg, pos, ": file not found");
2144 png_error(ps->pread, msg);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302145 }
Chris Craikb50c2172013-07-29 15:28:30 -07002146}
2147
2148/* The main interface for reading a saved file - pass the id number of the file
2149 * to retrieve. Ids must be unique or the earlier file will be hidden. The API
2150 * returns a png_struct and, optionally, a png_info. Both of these will be
2151 * destroyed by store_read_reset above.
2152 */
2153static png_structp
2154set_store_for_read(png_store *ps, png_infopp ppi, png_uint_32 id,
Matt Sarett9b1fe632015-11-25 10:21:17 -05002155 const char *name)
Chris Craikb50c2172013-07-29 15:28:30 -07002156{
2157 /* Set the name for png_error */
2158 safecat(ps->test, sizeof ps->test, 0, name);
2159
2160 if (ps->pread != NULL)
2161 png_error(ps->pread, "read store already in use");
2162
2163 store_read_reset(ps);
2164
2165 /* Both the create APIs can return NULL if used in their default mode
2166 * (because there is no other way of handling an error because the jmp_buf
2167 * by default is stored in png_struct and that has not been allocated!)
2168 * However, given that store_error works correctly in these circumstances
2169 * we don't ever expect NULL in this program.
2170 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302171# ifdef PNG_USER_MEM_SUPPORTED
2172 if (!ps->speed)
2173 ps->pread = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, ps,
2174 store_error, store_warning, &ps->read_memory_pool, store_malloc,
2175 store_free);
Chris Craikb50c2172013-07-29 15:28:30 -07002176
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302177 else
2178# endif
2179 ps->pread = png_create_read_struct(PNG_LIBPNG_VER_STRING, ps, store_error,
2180 store_warning);
Chris Craikb50c2172013-07-29 15:28:30 -07002181
2182 if (ps->pread == NULL)
2183 {
2184 struct exception_context *the_exception_context = &ps->exception_context;
2185
2186 store_log(ps, NULL, "png_create_read_struct returned NULL (unexpected)",
2187 1 /*error*/);
2188
2189 Throw ps;
2190 }
2191
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302192# ifdef PNG_SET_OPTION_SUPPORTED
2193 {
2194 int opt;
2195 for (opt=0; opt<ps->noptions; ++opt)
2196 if (png_set_option(ps->pread, ps->options[opt].option,
2197 ps->options[opt].setting) == PNG_OPTION_INVALID)
2198 png_error(ps->pread, "png option invalid");
2199 }
2200# endif
2201
Chris Craikb50c2172013-07-29 15:28:30 -07002202 store_read_set(ps, id);
2203
2204 if (ppi != NULL)
2205 *ppi = ps->piread = png_create_info_struct(ps->pread);
2206
2207 return ps->pread;
2208}
2209#endif /* PNG_READ_SUPPORTED */
2210
2211/* The overall cleanup of a store simply calls the above then removes all the
2212 * saved files. This does not delete the store itself.
2213 */
2214static void
2215store_delete(png_store *ps)
2216{
2217 store_write_reset(ps);
2218 store_read_reset(ps);
2219 store_freefile(&ps->saved);
2220 store_image_free(ps, NULL);
2221}
2222
2223/*********************** PNG FILE MODIFICATION ON READ ************************/
2224/* Files may be modified on read. The following structure contains a complete
2225 * png_store together with extra members to handle modification and a special
2226 * read callback for libpng. To use this the 'modifications' field must be set
2227 * to a list of png_modification structures that actually perform the
2228 * modification, otherwise a png_modifier is functionally equivalent to a
2229 * png_store. There is a special read function, set_modifier_for_read, which
2230 * replaces set_store_for_read.
2231 */
2232typedef enum modifier_state
2233{
2234 modifier_start, /* Initial value */
2235 modifier_signature, /* Have a signature */
2236 modifier_IHDR /* Have an IHDR */
2237} modifier_state;
2238
2239typedef struct CIE_color
2240{
2241 /* A single CIE tristimulus value, representing the unique response of a
2242 * standard observer to a variety of light spectra. The observer recognizes
2243 * all spectra that produce this response as the same color, therefore this
2244 * is effectively a description of a color.
2245 */
2246 double X, Y, Z;
2247} CIE_color;
2248
2249typedef struct color_encoding
2250{
2251 /* A description of an (R,G,B) encoding of color (as defined above); this
2252 * includes the actual colors of the (R,G,B) triples (1,0,0), (0,1,0) and
2253 * (0,0,1) plus an encoding value that is used to encode the linear
2254 * components R, G and B to give the actual values R^gamma, G^gamma and
2255 * B^gamma that are stored.
2256 */
2257 double gamma; /* Encoding (file) gamma of space */
2258 CIE_color red, green, blue; /* End points */
2259} color_encoding;
2260
2261#ifdef PNG_READ_SUPPORTED
Matt Sarett9b1fe632015-11-25 10:21:17 -05002262#if defined PNG_READ_TRANSFORMS_SUPPORTED && defined PNG_READ_cHRM_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07002263static double
2264chromaticity_x(CIE_color c)
2265{
2266 return c.X / (c.X + c.Y + c.Z);
2267}
2268
2269static double
2270chromaticity_y(CIE_color c)
2271{
2272 return c.Y / (c.X + c.Y + c.Z);
2273}
2274
2275static CIE_color
Matt Sarett9b1fe632015-11-25 10:21:17 -05002276white_point(const color_encoding *encoding)
Chris Craikb50c2172013-07-29 15:28:30 -07002277{
2278 CIE_color white;
2279
2280 white.X = encoding->red.X + encoding->green.X + encoding->blue.X;
2281 white.Y = encoding->red.Y + encoding->green.Y + encoding->blue.Y;
2282 white.Z = encoding->red.Z + encoding->green.Z + encoding->blue.Z;
2283
2284 return white;
2285}
Matt Sarett9b1fe632015-11-25 10:21:17 -05002286#endif /* READ_TRANSFORMS && READ_cHRM */
Chris Craikb50c2172013-07-29 15:28:30 -07002287
2288#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
2289static void
2290normalize_color_encoding(color_encoding *encoding)
2291{
Matt Sarett9b1fe632015-11-25 10:21:17 -05002292 const double whiteY = encoding->red.Y + encoding->green.Y +
Chris Craikb50c2172013-07-29 15:28:30 -07002293 encoding->blue.Y;
2294
2295 if (whiteY != 1)
2296 {
2297 encoding->red.X /= whiteY;
2298 encoding->red.Y /= whiteY;
2299 encoding->red.Z /= whiteY;
2300 encoding->green.X /= whiteY;
2301 encoding->green.Y /= whiteY;
2302 encoding->green.Z /= whiteY;
2303 encoding->blue.X /= whiteY;
2304 encoding->blue.Y /= whiteY;
2305 encoding->blue.Z /= whiteY;
2306 }
2307}
2308#endif
2309
Matt Sarett9b1fe632015-11-25 10:21:17 -05002310#ifdef PNG_READ_TRANSFORMS_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07002311static size_t
2312safecat_color_encoding(char *buffer, size_t bufsize, size_t pos,
Matt Sarett9b1fe632015-11-25 10:21:17 -05002313 const color_encoding *e, double encoding_gamma)
Chris Craikb50c2172013-07-29 15:28:30 -07002314{
2315 if (e != 0)
2316 {
2317 if (encoding_gamma != 0)
2318 pos = safecat(buffer, bufsize, pos, "(");
2319 pos = safecat(buffer, bufsize, pos, "R(");
2320 pos = safecatd(buffer, bufsize, pos, e->red.X, 4);
2321 pos = safecat(buffer, bufsize, pos, ",");
2322 pos = safecatd(buffer, bufsize, pos, e->red.Y, 4);
2323 pos = safecat(buffer, bufsize, pos, ",");
2324 pos = safecatd(buffer, bufsize, pos, e->red.Z, 4);
2325 pos = safecat(buffer, bufsize, pos, "),G(");
2326 pos = safecatd(buffer, bufsize, pos, e->green.X, 4);
2327 pos = safecat(buffer, bufsize, pos, ",");
2328 pos = safecatd(buffer, bufsize, pos, e->green.Y, 4);
2329 pos = safecat(buffer, bufsize, pos, ",");
2330 pos = safecatd(buffer, bufsize, pos, e->green.Z, 4);
2331 pos = safecat(buffer, bufsize, pos, "),B(");
2332 pos = safecatd(buffer, bufsize, pos, e->blue.X, 4);
2333 pos = safecat(buffer, bufsize, pos, ",");
2334 pos = safecatd(buffer, bufsize, pos, e->blue.Y, 4);
2335 pos = safecat(buffer, bufsize, pos, ",");
2336 pos = safecatd(buffer, bufsize, pos, e->blue.Z, 4);
2337 pos = safecat(buffer, bufsize, pos, ")");
2338 if (encoding_gamma != 0)
2339 pos = safecat(buffer, bufsize, pos, ")");
2340 }
2341
2342 if (encoding_gamma != 0)
2343 {
2344 pos = safecat(buffer, bufsize, pos, "^");
2345 pos = safecatd(buffer, bufsize, pos, encoding_gamma, 5);
2346 }
2347
2348 return pos;
2349}
Matt Sarett9b1fe632015-11-25 10:21:17 -05002350#endif /* READ_TRANSFORMS */
Chris Craikb50c2172013-07-29 15:28:30 -07002351#endif /* PNG_READ_SUPPORTED */
2352
2353typedef struct png_modifier
2354{
2355 png_store this; /* I am a png_store */
2356 struct png_modification *modifications; /* Changes to make */
2357
2358 modifier_state state; /* My state */
2359
2360 /* Information from IHDR: */
2361 png_byte bit_depth; /* From IHDR */
2362 png_byte colour_type; /* From IHDR */
2363
2364 /* While handling PLTE, IDAT and IEND these chunks may be pended to allow
2365 * other chunks to be inserted.
2366 */
2367 png_uint_32 pending_len;
2368 png_uint_32 pending_chunk;
2369
2370 /* Test values */
2371 double *gammas;
2372 unsigned int ngammas;
2373 unsigned int ngamma_tests; /* Number of gamma tests to run*/
2374 double current_gamma; /* 0 if not set */
Matt Sarett9b1fe632015-11-25 10:21:17 -05002375 const color_encoding *encodings;
Chris Craikb50c2172013-07-29 15:28:30 -07002376 unsigned int nencodings;
Matt Sarett9b1fe632015-11-25 10:21:17 -05002377 const color_encoding *current_encoding; /* If an encoding has been set */
Chris Craikb50c2172013-07-29 15:28:30 -07002378 unsigned int encoding_counter; /* For iteration */
2379 int encoding_ignored; /* Something overwrote it */
2380
2381 /* Control variables used to iterate through possible encodings, the
2382 * following must be set to 0 and tested by the function that uses the
2383 * png_modifier because the modifier only sets it to 1 (true.)
2384 */
2385 unsigned int repeat :1; /* Repeat this transform test. */
2386 unsigned int test_uses_encoding :1;
2387
Matt Sarett9b1fe632015-11-25 10:21:17 -05002388 /* Lowest sbit to test (pre-1.7 libpng fails for sbit < 8) */
Chris Craikb50c2172013-07-29 15:28:30 -07002389 png_byte sbitlow;
2390
2391 /* Error control - these are the limits on errors accepted by the gamma tests
2392 * below.
2393 */
2394 double maxout8; /* Maximum output value error */
2395 double maxabs8; /* Absolute sample error 0..1 */
2396 double maxcalc8; /* Absolute sample error 0..1 */
2397 double maxpc8; /* Percentage sample error 0..100% */
2398 double maxout16; /* Maximum output value error */
2399 double maxabs16; /* Absolute sample error 0..1 */
2400 double maxcalc16;/* Absolute sample error 0..1 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302401 double maxcalcG; /* Absolute sample error 0..1 */
Chris Craikb50c2172013-07-29 15:28:30 -07002402 double maxpc16; /* Percentage sample error 0..100% */
2403
2404 /* This is set by transforms that need to allow a higher limit, it is an
2405 * internal check on pngvalid to ensure that the calculated error limits are
2406 * not ridiculous; without this it is too easy to make a mistake in pngvalid
2407 * that allows any value through.
Matt Sarett11466862016-02-19 13:41:30 -05002408 *
2409 * NOTE: this is not checked in release builds.
Chris Craikb50c2172013-07-29 15:28:30 -07002410 */
2411 double limit; /* limit on error values, normally 4E-3 */
2412
2413 /* Log limits - values above this are logged, but not necessarily
2414 * warned.
2415 */
2416 double log8; /* Absolute error in 8 bits to log */
2417 double log16; /* Absolute error in 16 bits to log */
2418
2419 /* Logged 8 and 16 bit errors ('output' values): */
2420 double error_gray_2;
2421 double error_gray_4;
2422 double error_gray_8;
2423 double error_gray_16;
2424 double error_color_8;
2425 double error_color_16;
2426 double error_indexed;
2427
2428 /* Flags: */
2429 /* Whether to call png_read_update_info, not png_read_start_image, and how
2430 * many times to call it.
2431 */
2432 int use_update_info;
2433
2434 /* Whether or not to interlace. */
2435 int interlace_type :9; /* int, but must store '1' */
2436
2437 /* Run the standard tests? */
2438 unsigned int test_standard :1;
2439
2440 /* Run the odd-sized image and interlace read/write tests? */
2441 unsigned int test_size :1;
2442
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302443 /* Run tests on reading with a combination of transforms, */
Chris Craikb50c2172013-07-29 15:28:30 -07002444 unsigned int test_transform :1;
Matt Sarett9b1fe632015-11-25 10:21:17 -05002445 unsigned int test_tRNS :1; /* Includes tRNS images */
Chris Craikb50c2172013-07-29 15:28:30 -07002446
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302447 /* When to use the use_input_precision option, this controls the gamma
2448 * validation code checks. If set any value that is within the transformed
2449 * range input-.5 to input+.5 will be accepted, otherwise the value must be
2450 * within the normal limits. It should not be necessary to set this; the
2451 * result should always be exact within the permitted error limits.
2452 */
Chris Craikb50c2172013-07-29 15:28:30 -07002453 unsigned int use_input_precision :1;
2454 unsigned int use_input_precision_sbit :1;
2455 unsigned int use_input_precision_16to8 :1;
2456
2457 /* If set assume that the calculation bit depth is set by the input
2458 * precision, not the output precision.
2459 */
2460 unsigned int calculations_use_input_precision :1;
2461
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302462 /* If set assume that the calculations are done in 16 bits even if the sample
2463 * depth is 8 bits.
Chris Craikb50c2172013-07-29 15:28:30 -07002464 */
2465 unsigned int assume_16_bit_calculations :1;
2466
2467 /* Which gamma tests to run: */
2468 unsigned int test_gamma_threshold :1;
2469 unsigned int test_gamma_transform :1; /* main tests */
2470 unsigned int test_gamma_sbit :1;
2471 unsigned int test_gamma_scale16 :1;
2472 unsigned int test_gamma_background :1;
2473 unsigned int test_gamma_alpha_mode :1;
2474 unsigned int test_gamma_expand16 :1;
2475 unsigned int test_exhaustive :1;
2476
Matt Sarett9b1fe632015-11-25 10:21:17 -05002477 /* Whether or not to run the low-bit-depth grayscale tests. This fails on
2478 * gamma images in some cases because of gross inaccuracies in the grayscale
2479 * gamma handling for low bit depth.
2480 */
2481 unsigned int test_lbg :1;
2482 unsigned int test_lbg_gamma_threshold :1;
2483 unsigned int test_lbg_gamma_transform :1;
2484 unsigned int test_lbg_gamma_sbit :1;
2485 unsigned int test_lbg_gamma_composition :1;
2486
Chris Craikb50c2172013-07-29 15:28:30 -07002487 unsigned int log :1; /* Log max error */
2488
2489 /* Buffer information, the buffer size limits the size of the chunks that can
2490 * be modified - they must fit (including header and CRC) into the buffer!
2491 */
2492 size_t flush; /* Count of bytes to flush */
2493 size_t buffer_count; /* Bytes in buffer */
2494 size_t buffer_position; /* Position in buffer */
2495 png_byte buffer[1024];
2496} png_modifier;
2497
2498/* This returns true if the test should be stopped now because it has already
2499 * failed and it is running silently.
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302500 */
Chris Craikb50c2172013-07-29 15:28:30 -07002501static int fail(png_modifier *pm)
2502{
2503 return !pm->log && !pm->this.verbose && (pm->this.nerrors > 0 ||
2504 (pm->this.treat_warnings_as_errors && pm->this.nwarnings > 0));
2505}
2506
2507static void
2508modifier_init(png_modifier *pm)
2509{
2510 memset(pm, 0, sizeof *pm);
2511 store_init(&pm->this);
2512 pm->modifications = NULL;
2513 pm->state = modifier_start;
2514 pm->sbitlow = 1U;
2515 pm->ngammas = 0;
2516 pm->ngamma_tests = 0;
2517 pm->gammas = 0;
2518 pm->current_gamma = 0;
2519 pm->encodings = 0;
2520 pm->nencodings = 0;
2521 pm->current_encoding = 0;
2522 pm->encoding_counter = 0;
2523 pm->encoding_ignored = 0;
2524 pm->repeat = 0;
2525 pm->test_uses_encoding = 0;
2526 pm->maxout8 = pm->maxpc8 = pm->maxabs8 = pm->maxcalc8 = 0;
2527 pm->maxout16 = pm->maxpc16 = pm->maxabs16 = pm->maxcalc16 = 0;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302528 pm->maxcalcG = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07002529 pm->limit = 4E-3;
2530 pm->log8 = pm->log16 = 0; /* Means 'off' */
2531 pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = 0;
2532 pm->error_gray_16 = pm->error_color_8 = pm->error_color_16 = 0;
2533 pm->error_indexed = 0;
2534 pm->use_update_info = 0;
2535 pm->interlace_type = PNG_INTERLACE_NONE;
2536 pm->test_standard = 0;
2537 pm->test_size = 0;
2538 pm->test_transform = 0;
Matt Sarett9b1fe632015-11-25 10:21:17 -05002539# ifdef PNG_WRITE_tRNS_SUPPORTED
2540 pm->test_tRNS = 1;
2541# else
2542 pm->test_tRNS = 0;
2543# endif
Chris Craikb50c2172013-07-29 15:28:30 -07002544 pm->use_input_precision = 0;
2545 pm->use_input_precision_sbit = 0;
2546 pm->use_input_precision_16to8 = 0;
2547 pm->calculations_use_input_precision = 0;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302548 pm->assume_16_bit_calculations = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07002549 pm->test_gamma_threshold = 0;
2550 pm->test_gamma_transform = 0;
2551 pm->test_gamma_sbit = 0;
2552 pm->test_gamma_scale16 = 0;
2553 pm->test_gamma_background = 0;
2554 pm->test_gamma_alpha_mode = 0;
2555 pm->test_gamma_expand16 = 0;
Matt Sarett9b1fe632015-11-25 10:21:17 -05002556 pm->test_lbg = 1;
2557 pm->test_lbg_gamma_threshold = 1;
2558 pm->test_lbg_gamma_transform = 1;
2559 pm->test_lbg_gamma_sbit = 1;
2560 pm->test_lbg_gamma_composition = 1;
Chris Craikb50c2172013-07-29 15:28:30 -07002561 pm->test_exhaustive = 0;
2562 pm->log = 0;
2563
2564 /* Rely on the memset for all the other fields - there are no pointers */
2565}
2566
2567#ifdef PNG_READ_TRANSFORMS_SUPPORTED
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302568
2569/* This controls use of checks that explicitly know how libpng digitizes the
2570 * samples in calculations; setting this circumvents simple error limit checking
2571 * in the rgb_to_gray check, replacing it with an exact copy of the libpng 1.5
2572 * algorithm.
2573 */
2574#define DIGITIZE PNG_LIBPNG_VER < 10700
2575
Chris Craikb50c2172013-07-29 15:28:30 -07002576/* If pm->calculations_use_input_precision is set then operations will happen
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302577 * with the precision of the input, not the precision of the output depth.
Chris Craikb50c2172013-07-29 15:28:30 -07002578 *
2579 * If pm->assume_16_bit_calculations is set then even 8 bit calculations use 16
2580 * bit precision. This only affects those of the following limits that pertain
2581 * to a calculation - not a digitization operation - unless the following API is
2582 * called directly.
2583 */
2584#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302585#if DIGITIZE
2586static double digitize(double value, int depth, int do_round)
Chris Craikb50c2172013-07-29 15:28:30 -07002587{
2588 /* 'value' is in the range 0 to 1, the result is the same value rounded to a
2589 * multiple of the digitization factor - 8 or 16 bits depending on both the
2590 * sample depth and the 'assume' setting. Digitization is normally by
2591 * rounding and 'do_round' should be 1, if it is 0 the digitized value will
2592 * be truncated.
2593 */
xNombred07bb0d2020-03-10 20:17:12 +01002594 unsigned int digitization_factor = (1U << depth) - 1;
Chris Craikb50c2172013-07-29 15:28:30 -07002595
2596 /* Limiting the range is done as a convenience to the caller - it's easier to
2597 * do it once here than every time at the call site.
2598 */
2599 if (value <= 0)
2600 value = 0;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302601
Chris Craikb50c2172013-07-29 15:28:30 -07002602 else if (value >= 1)
2603 value = 1;
2604
2605 value *= digitization_factor;
2606 if (do_round) value += .5;
2607 return floor(value)/digitization_factor;
2608}
2609#endif
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302610#endif /* RGB_TO_GRAY */
Chris Craikb50c2172013-07-29 15:28:30 -07002611
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302612#ifdef PNG_READ_GAMMA_SUPPORTED
Matt Sarett9b1fe632015-11-25 10:21:17 -05002613static double abserr(const png_modifier *pm, int in_depth, int out_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07002614{
2615 /* Absolute error permitted in linear values - affected by the bit depth of
2616 * the calculations.
2617 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302618 if (pm->assume_16_bit_calculations ||
2619 (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
Chris Craikb50c2172013-07-29 15:28:30 -07002620 return pm->maxabs16;
2621 else
2622 return pm->maxabs8;
2623}
Chris Craikb50c2172013-07-29 15:28:30 -07002624
Matt Sarett9b1fe632015-11-25 10:21:17 -05002625static double calcerr(const png_modifier *pm, int in_depth, int out_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07002626{
2627 /* Error in the linear composition arithmetic - only relevant when
2628 * composition actually happens (0 < alpha < 1).
2629 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302630 if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
Chris Craikb50c2172013-07-29 15:28:30 -07002631 return pm->maxcalc16;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302632 else if (pm->assume_16_bit_calculations)
2633 return pm->maxcalcG;
Chris Craikb50c2172013-07-29 15:28:30 -07002634 else
2635 return pm->maxcalc8;
2636}
2637
Matt Sarett9b1fe632015-11-25 10:21:17 -05002638static double pcerr(const png_modifier *pm, int in_depth, int out_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07002639{
2640 /* Percentage error permitted in the linear values. Note that the specified
2641 * value is a percentage but this routine returns a simple number.
2642 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302643 if (pm->assume_16_bit_calculations ||
2644 (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
Chris Craikb50c2172013-07-29 15:28:30 -07002645 return pm->maxpc16 * .01;
2646 else
2647 return pm->maxpc8 * .01;
2648}
2649
2650/* Output error - the error in the encoded value. This is determined by the
2651 * digitization of the output so can be +/-0.5 in the actual output value. In
2652 * the expand_16 case with the current code in libpng the expand happens after
2653 * all the calculations are done in 8 bit arithmetic, so even though the output
2654 * depth is 16 the output error is determined by the 8 bit calculation.
2655 *
2656 * This limit is not determined by the bit depth of internal calculations.
2657 *
2658 * The specified parameter does *not* include the base .5 digitization error but
2659 * it is added here.
2660 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05002661static double outerr(const png_modifier *pm, int in_depth, int out_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07002662{
2663 /* There is a serious error in the 2 and 4 bit grayscale transform because
2664 * the gamma table value (8 bits) is simply shifted, not rounded, so the
2665 * error in 4 bit grayscale gamma is up to the value below. This is a hack
2666 * to allow pngvalid to succeed:
2667 *
2668 * TODO: fix this in libpng
2669 */
2670 if (out_depth == 2)
2671 return .73182-.5;
2672
2673 if (out_depth == 4)
2674 return .90644-.5;
2675
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302676 if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
Chris Craikb50c2172013-07-29 15:28:30 -07002677 return pm->maxout16;
2678
2679 /* This is the case where the value was calculated at 8-bit precision then
2680 * scaled to 16 bits.
2681 */
2682 else if (out_depth == 16)
2683 return pm->maxout8 * 257;
2684
2685 else
2686 return pm->maxout8;
2687}
2688
2689/* This does the same thing as the above however it returns the value to log,
2690 * rather than raising a warning. This is useful for debugging to track down
2691 * exactly what set of parameters cause high error values.
2692 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05002693static double outlog(const png_modifier *pm, int in_depth, int out_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07002694{
2695 /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535)
2696 * and so must be adjusted for low bit depth grayscale:
2697 */
2698 if (out_depth <= 8)
2699 {
2700 if (pm->log8 == 0) /* switched off */
2701 return 256;
2702
2703 if (out_depth < 8)
2704 return pm->log8 / 255 * ((1<<out_depth)-1);
2705
2706 return pm->log8;
2707 }
2708
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302709 if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
Chris Craikb50c2172013-07-29 15:28:30 -07002710 {
2711 if (pm->log16 == 0)
2712 return 65536;
2713
2714 return pm->log16;
2715 }
2716
2717 /* This is the case where the value was calculated at 8-bit precision then
2718 * scaled to 16 bits.
2719 */
2720 if (pm->log8 == 0)
2721 return 65536;
2722
2723 return pm->log8 * 257;
2724}
2725
2726/* This complements the above by providing the appropriate quantization for the
2727 * final value. Normally this would just be quantization to an integral value,
2728 * but in the 8 bit calculation case it's actually quantization to a multiple of
2729 * 257!
2730 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05002731static int output_quantization_factor(const png_modifier *pm, int in_depth,
Chris Craikb50c2172013-07-29 15:28:30 -07002732 int out_depth)
2733{
Sireesh Tripurarib478e662014-05-09 15:15:10 +05302734 if (out_depth == 16 && in_depth != 16 &&
2735 pm->calculations_use_input_precision)
Chris Craikb50c2172013-07-29 15:28:30 -07002736 return 257;
2737 else
2738 return 1;
2739}
2740#endif /* PNG_READ_GAMMA_SUPPORTED */
2741
2742/* One modification structure must be provided for each chunk to be modified (in
2743 * fact more than one can be provided if multiple separate changes are desired
2744 * for a single chunk.) Modifications include adding a new chunk when a
2745 * suitable chunk does not exist.
2746 *
2747 * The caller of modify_fn will reset the CRC of the chunk and record 'modified'
2748 * or 'added' as appropriate if the modify_fn returns 1 (true). If the
2749 * modify_fn is NULL the chunk is simply removed.
2750 */
2751typedef struct png_modification
2752{
2753 struct png_modification *next;
2754 png_uint_32 chunk;
2755
2756 /* If the following is NULL all matching chunks will be removed: */
2757 int (*modify_fn)(struct png_modifier *pm,
2758 struct png_modification *me, int add);
2759
2760 /* If the following is set to PLTE, IDAT or IEND and the chunk has not been
2761 * found and modified (and there is a modify_fn) the modify_fn will be called
2762 * to add the chunk before the relevant chunk.
2763 */
2764 png_uint_32 add;
2765 unsigned int modified :1; /* Chunk was modified */
2766 unsigned int added :1; /* Chunk was added */
2767 unsigned int removed :1; /* Chunk was removed */
2768} png_modification;
2769
2770static void
2771modification_reset(png_modification *pmm)
2772{
2773 if (pmm != NULL)
2774 {
2775 pmm->modified = 0;
2776 pmm->added = 0;
2777 pmm->removed = 0;
2778 modification_reset(pmm->next);
2779 }
2780}
2781
2782static void
2783modification_init(png_modification *pmm)
2784{
2785 memset(pmm, 0, sizeof *pmm);
2786 pmm->next = NULL;
2787 pmm->chunk = 0;
2788 pmm->modify_fn = NULL;
2789 pmm->add = 0;
2790 modification_reset(pmm);
2791}
2792
2793#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
2794static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05002795modifier_current_encoding(const png_modifier *pm, color_encoding *ce)
Chris Craikb50c2172013-07-29 15:28:30 -07002796{
2797 if (pm->current_encoding != 0)
2798 *ce = *pm->current_encoding;
2799
2800 else
2801 memset(ce, 0, sizeof *ce);
2802
2803 ce->gamma = pm->current_gamma;
2804}
2805#endif
2806
Matt Sarett9b1fe632015-11-25 10:21:17 -05002807#ifdef PNG_READ_TRANSFORMS_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07002808static size_t
2809safecat_current_encoding(char *buffer, size_t bufsize, size_t pos,
Matt Sarett9b1fe632015-11-25 10:21:17 -05002810 const png_modifier *pm)
Chris Craikb50c2172013-07-29 15:28:30 -07002811{
2812 pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding,
2813 pm->current_gamma);
2814
2815 if (pm->encoding_ignored)
2816 pos = safecat(buffer, bufsize, pos, "[overridden]");
2817
2818 return pos;
2819}
Matt Sarett9b1fe632015-11-25 10:21:17 -05002820#endif
Chris Craikb50c2172013-07-29 15:28:30 -07002821
2822/* Iterate through the usefully testable color encodings. An encoding is one
2823 * of:
2824 *
2825 * 1) Nothing (no color space, no gamma).
2826 * 2) Just a gamma value from the gamma array (including 1.0)
2827 * 3) A color space from the encodings array with the corresponding gamma.
2828 * 4) The same, but with gamma 1.0 (only really useful with 16 bit calculations)
2829 *
2830 * The iterator selects these in turn, the randomizer selects one at random,
2831 * which is used depends on the setting of the 'test_exhaustive' flag. Notice
2832 * that this function changes the colour space encoding so it must only be
2833 * called on completion of the previous test. This is what 'modifier_reset'
2834 * does, below.
2835 *
2836 * After the function has been called the 'repeat' flag will still be set; the
2837 * caller of modifier_reset must reset it at the start of each run of the test!
2838 */
2839static unsigned int
Matt Sarett9b1fe632015-11-25 10:21:17 -05002840modifier_total_encodings(const png_modifier *pm)
Chris Craikb50c2172013-07-29 15:28:30 -07002841{
2842 return 1 + /* (1) nothing */
2843 pm->ngammas + /* (2) gamma values to test */
2844 pm->nencodings + /* (3) total number of encodings */
2845 /* The following test only works after the first time through the
2846 * png_modifier code because 'bit_depth' is set when the IHDR is read.
2847 * modifier_reset, below, preserves the setting until after it has called
2848 * the iterate function (also below.)
2849 *
2850 * For this reason do not rely on this function outside a call to
2851 * modifier_reset.
2852 */
2853 ((pm->bit_depth == 16 || pm->assume_16_bit_calculations) ?
2854 pm->nencodings : 0); /* (4) encodings with gamma == 1.0 */
2855}
2856
2857static void
2858modifier_encoding_iterate(png_modifier *pm)
2859{
2860 if (!pm->repeat && /* Else something needs the current encoding again. */
2861 pm->test_uses_encoding) /* Some transform is encoding dependent */
2862 {
2863 if (pm->test_exhaustive)
2864 {
2865 if (++pm->encoding_counter >= modifier_total_encodings(pm))
2866 pm->encoding_counter = 0; /* This will stop the repeat */
2867 }
2868
2869 else
2870 {
2871 /* Not exhaustive - choose an encoding at random; generate a number in
2872 * the range 1..(max-1), so the result is always non-zero:
2873 */
2874 if (pm->encoding_counter == 0)
2875 pm->encoding_counter = random_mod(modifier_total_encodings(pm)-1)+1;
2876 else
2877 pm->encoding_counter = 0;
2878 }
2879
2880 if (pm->encoding_counter > 0)
2881 pm->repeat = 1;
2882 }
2883
2884 else if (!pm->repeat)
2885 pm->encoding_counter = 0;
2886}
2887
2888static void
2889modifier_reset(png_modifier *pm)
2890{
2891 store_read_reset(&pm->this);
2892 pm->limit = 4E-3;
2893 pm->pending_len = pm->pending_chunk = 0;
2894 pm->flush = pm->buffer_count = pm->buffer_position = 0;
2895 pm->modifications = NULL;
2896 pm->state = modifier_start;
2897 modifier_encoding_iterate(pm);
2898 /* The following must be set in the next run. In particular
2899 * test_uses_encodings must be set in the _ini function of each transform
2900 * that looks at the encodings. (Not the 'add' function!)
2901 */
2902 pm->test_uses_encoding = 0;
2903 pm->current_gamma = 0;
2904 pm->current_encoding = 0;
2905 pm->encoding_ignored = 0;
2906 /* These only become value after IHDR is read: */
2907 pm->bit_depth = pm->colour_type = 0;
2908}
2909
2910/* The following must be called before anything else to get the encoding set up
2911 * on the modifier. In particular it must be called before the transform init
2912 * functions are called.
2913 */
2914static void
2915modifier_set_encoding(png_modifier *pm)
2916{
2917 /* Set the encoding to the one specified by the current encoding counter,
2918 * first clear out all the settings - this corresponds to an encoding_counter
2919 * of 0.
2920 */
2921 pm->current_gamma = 0;
2922 pm->current_encoding = 0;
2923 pm->encoding_ignored = 0; /* not ignored yet - happens in _ini functions. */
2924
2925 /* Now, if required, set the gamma and encoding fields. */
2926 if (pm->encoding_counter > 0)
2927 {
2928 /* The gammas[] array is an array of screen gammas, not encoding gammas,
2929 * so we need the inverse:
2930 */
2931 if (pm->encoding_counter <= pm->ngammas)
2932 pm->current_gamma = 1/pm->gammas[pm->encoding_counter-1];
2933
2934 else
2935 {
2936 unsigned int i = pm->encoding_counter - pm->ngammas;
2937
2938 if (i >= pm->nencodings)
2939 {
2940 i %= pm->nencodings;
2941 pm->current_gamma = 1; /* Linear, only in the 16 bit case */
2942 }
2943
2944 else
2945 pm->current_gamma = pm->encodings[i].gamma;
2946
2947 pm->current_encoding = pm->encodings + i;
2948 }
2949 }
2950}
2951
2952/* Enquiry functions to find out what is set. Notice that there is an implicit
2953 * assumption below that the first encoding in the list is the one for sRGB.
2954 */
2955static int
Matt Sarett9b1fe632015-11-25 10:21:17 -05002956modifier_color_encoding_is_sRGB(const png_modifier *pm)
Chris Craikb50c2172013-07-29 15:28:30 -07002957{
2958 return pm->current_encoding != 0 && pm->current_encoding == pm->encodings &&
2959 pm->current_encoding->gamma == pm->current_gamma;
2960}
2961
2962static int
Matt Sarett9b1fe632015-11-25 10:21:17 -05002963modifier_color_encoding_is_set(const png_modifier *pm)
Chris Craikb50c2172013-07-29 15:28:30 -07002964{
2965 return pm->current_gamma != 0;
2966}
2967
Chris Craikb50c2172013-07-29 15:28:30 -07002968/* The guts of modification are performed during a read. */
2969static void
2970modifier_crc(png_bytep buffer)
2971{
2972 /* Recalculate the chunk CRC - a complete chunk must be in
2973 * the buffer, at the start.
2974 */
2975 uInt datalen = png_get_uint_32(buffer);
2976 uLong crc = crc32(0, buffer+4, datalen+4);
2977 /* The cast to png_uint_32 is safe because a crc32 is always a 32 bit value.
2978 */
2979 png_save_uint_32(buffer+datalen+8, (png_uint_32)crc);
2980}
2981
2982static void
2983modifier_setbuffer(png_modifier *pm)
2984{
2985 modifier_crc(pm->buffer);
2986 pm->buffer_count = png_get_uint_32(pm->buffer)+12;
2987 pm->buffer_position = 0;
2988}
2989
2990/* Separate the callback into the actual implementation (which is passed the
2991 * png_modifier explicitly) and the callback, which gets the modifier from the
2992 * png_struct.
2993 */
2994static void
xNombred07bb0d2020-03-10 20:17:12 +01002995modifier_read_imp(png_modifier *pm, png_bytep pb, size_t st)
Chris Craikb50c2172013-07-29 15:28:30 -07002996{
2997 while (st > 0)
2998 {
2999 size_t cb;
3000 png_uint_32 len, chunk;
3001 png_modification *mod;
3002
3003 if (pm->buffer_position >= pm->buffer_count) switch (pm->state)
3004 {
3005 static png_byte sign[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
3006 case modifier_start:
Alex Naidis7a055fd2016-10-01 12:23:07 +02003007 store_read_chunk(&pm->this, pm->buffer, 8, 8); /* signature. */
Chris Craikb50c2172013-07-29 15:28:30 -07003008 pm->buffer_count = 8;
3009 pm->buffer_position = 0;
3010
3011 if (memcmp(pm->buffer, sign, 8) != 0)
3012 png_error(pm->this.pread, "invalid PNG file signature");
3013 pm->state = modifier_signature;
3014 break;
3015
3016 case modifier_signature:
Alex Naidis7a055fd2016-10-01 12:23:07 +02003017 store_read_chunk(&pm->this, pm->buffer, 13+12, 13+12); /* IHDR */
Chris Craikb50c2172013-07-29 15:28:30 -07003018 pm->buffer_count = 13+12;
3019 pm->buffer_position = 0;
3020
3021 if (png_get_uint_32(pm->buffer) != 13 ||
3022 png_get_uint_32(pm->buffer+4) != CHUNK_IHDR)
3023 png_error(pm->this.pread, "invalid IHDR");
3024
3025 /* Check the list of modifiers for modifications to the IHDR. */
3026 mod = pm->modifications;
3027 while (mod != NULL)
3028 {
3029 if (mod->chunk == CHUNK_IHDR && mod->modify_fn &&
3030 (*mod->modify_fn)(pm, mod, 0))
3031 {
3032 mod->modified = 1;
3033 modifier_setbuffer(pm);
3034 }
3035
3036 /* Ignore removal or add if IHDR! */
3037 mod = mod->next;
3038 }
3039
3040 /* Cache information from the IHDR (the modified one.) */
3041 pm->bit_depth = pm->buffer[8+8];
3042 pm->colour_type = pm->buffer[8+8+1];
3043
3044 pm->state = modifier_IHDR;
3045 pm->flush = 0;
3046 break;
3047
3048 case modifier_IHDR:
3049 default:
3050 /* Read a new chunk and process it until we see PLTE, IDAT or
3051 * IEND. 'flush' indicates that there is still some data to
3052 * output from the preceding chunk.
3053 */
3054 if ((cb = pm->flush) > 0)
3055 {
3056 if (cb > st) cb = st;
3057 pm->flush -= cb;
Alex Naidis7a055fd2016-10-01 12:23:07 +02003058 store_read_chunk(&pm->this, pb, cb, cb);
Chris Craikb50c2172013-07-29 15:28:30 -07003059 pb += cb;
3060 st -= cb;
3061 if (st == 0) return;
3062 }
3063
3064 /* No more bytes to flush, read a header, or handle a pending
3065 * chunk.
3066 */
3067 if (pm->pending_chunk != 0)
3068 {
3069 png_save_uint_32(pm->buffer, pm->pending_len);
3070 png_save_uint_32(pm->buffer+4, pm->pending_chunk);
3071 pm->pending_len = 0;
3072 pm->pending_chunk = 0;
3073 }
3074 else
Alex Naidis7a055fd2016-10-01 12:23:07 +02003075 store_read_chunk(&pm->this, pm->buffer, 8, 8);
Chris Craikb50c2172013-07-29 15:28:30 -07003076
3077 pm->buffer_count = 8;
3078 pm->buffer_position = 0;
3079
3080 /* Check for something to modify or a terminator chunk. */
3081 len = png_get_uint_32(pm->buffer);
3082 chunk = png_get_uint_32(pm->buffer+4);
3083
3084 /* Terminators first, they may have to be delayed for added
3085 * chunks
3086 */
3087 if (chunk == CHUNK_PLTE || chunk == CHUNK_IDAT ||
3088 chunk == CHUNK_IEND)
3089 {
3090 mod = pm->modifications;
3091
3092 while (mod != NULL)
3093 {
3094 if ((mod->add == chunk ||
3095 (mod->add == CHUNK_PLTE && chunk == CHUNK_IDAT)) &&
3096 mod->modify_fn != NULL && !mod->modified && !mod->added)
3097 {
3098 /* Regardless of what the modify function does do not run
3099 * this again.
3100 */
3101 mod->added = 1;
3102
3103 if ((*mod->modify_fn)(pm, mod, 1 /*add*/))
3104 {
3105 /* Reset the CRC on a new chunk */
3106 if (pm->buffer_count > 0)
3107 modifier_setbuffer(pm);
3108
3109 else
3110 {
3111 pm->buffer_position = 0;
3112 mod->removed = 1;
3113 }
3114
3115 /* The buffer has been filled with something (we assume)
3116 * so output this. Pend the current chunk.
3117 */
3118 pm->pending_len = len;
3119 pm->pending_chunk = chunk;
3120 break; /* out of while */
3121 }
3122 }
3123
3124 mod = mod->next;
3125 }
3126
3127 /* Don't do any further processing if the buffer was modified -
3128 * otherwise the code will end up modifying a chunk that was
3129 * just added.
3130 */
3131 if (mod != NULL)
3132 break; /* out of switch */
3133 }
3134
3135 /* If we get to here then this chunk may need to be modified. To
3136 * do this it must be less than 1024 bytes in total size, otherwise
3137 * it just gets flushed.
3138 */
3139 if (len+12 <= sizeof pm->buffer)
3140 {
xNombred07bb0d2020-03-10 20:17:12 +01003141 size_t s = len+12-pm->buffer_count;
Alex Naidis7a055fd2016-10-01 12:23:07 +02003142 store_read_chunk(&pm->this, pm->buffer+pm->buffer_count, s, s);
Chris Craikb50c2172013-07-29 15:28:30 -07003143 pm->buffer_count = len+12;
3144
3145 /* Check for a modification, else leave it be. */
3146 mod = pm->modifications;
3147 while (mod != NULL)
3148 {
3149 if (mod->chunk == chunk)
3150 {
3151 if (mod->modify_fn == NULL)
3152 {
3153 /* Remove this chunk */
3154 pm->buffer_count = pm->buffer_position = 0;
3155 mod->removed = 1;
3156 break; /* Terminate the while loop */
3157 }
3158
3159 else if ((*mod->modify_fn)(pm, mod, 0))
3160 {
3161 mod->modified = 1;
3162 /* The chunk may have been removed: */
3163 if (pm->buffer_count == 0)
3164 {
3165 pm->buffer_position = 0;
3166 break;
3167 }
3168 modifier_setbuffer(pm);
3169 }
3170 }
3171
3172 mod = mod->next;
3173 }
3174 }
3175
3176 else
3177 pm->flush = len+12 - pm->buffer_count; /* data + crc */
3178
3179 /* Take the data from the buffer (if there is any). */
3180 break;
3181 }
3182
3183 /* Here to read from the modifier buffer (not directly from
3184 * the store, as in the flush case above.)
3185 */
3186 cb = pm->buffer_count - pm->buffer_position;
3187
3188 if (cb > st)
3189 cb = st;
3190
3191 memcpy(pb, pm->buffer + pm->buffer_position, cb);
3192 st -= cb;
3193 pb += cb;
3194 pm->buffer_position += cb;
3195 }
3196}
3197
3198/* The callback: */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303199static void PNGCBAPI
xNombred07bb0d2020-03-10 20:17:12 +01003200modifier_read(png_structp ppIn, png_bytep pb, size_t st)
Chris Craikb50c2172013-07-29 15:28:30 -07003201{
3202 png_const_structp pp = ppIn;
3203 png_modifier *pm = voidcast(png_modifier*, png_get_io_ptr(pp));
3204
3205 if (pm == NULL || pm->this.pread != pp)
3206 png_error(pp, "bad modifier_read call");
3207
3208 modifier_read_imp(pm, pb, st);
3209}
3210
3211/* Like store_progressive_read but the data is getting changed as we go so we
3212 * need a local buffer.
3213 */
3214static void
3215modifier_progressive_read(png_modifier *pm, png_structp pp, png_infop pi)
3216{
3217 if (pm->this.pread != pp || pm->this.current == NULL ||
3218 pm->this.next == NULL)
3219 png_error(pp, "store state damaged (progressive)");
3220
3221 /* This is another Horowitz and Hill random noise generator. In this case
3222 * the aim is to stress the progressive reader with truly horrible variable
3223 * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers
3224 * is generated. We could probably just count from 1 to 32767 and get as
3225 * good a result.
3226 */
3227 for (;;)
3228 {
3229 static png_uint_32 noise = 1;
xNombred07bb0d2020-03-10 20:17:12 +01003230 size_t cb, cbAvail;
Chris Craikb50c2172013-07-29 15:28:30 -07003231 png_byte buffer[512];
3232
3233 /* Generate 15 more bits of stuff: */
3234 noise = (noise << 9) | ((noise ^ (noise >> (9-5))) & 0x1ff);
3235 cb = noise & 0x1ff;
3236
3237 /* Check that this number of bytes are available (in the current buffer.)
3238 * (This doesn't quite work - the modifier might delete a chunk; unlikely
3239 * but possible, it doesn't happen at present because the modifier only
3240 * adds chunks to standard images.)
3241 */
3242 cbAvail = store_read_buffer_avail(&pm->this);
3243 if (pm->buffer_count > pm->buffer_position)
3244 cbAvail += pm->buffer_count - pm->buffer_position;
3245
3246 if (cb > cbAvail)
3247 {
3248 /* Check for EOF: */
3249 if (cbAvail == 0)
3250 break;
3251
3252 cb = cbAvail;
3253 }
3254
3255 modifier_read_imp(pm, buffer, cb);
3256 png_process_data(pp, pi, buffer, cb);
3257 }
3258
3259 /* Check the invariants at the end (if this fails it's a problem in this
3260 * file!)
3261 */
3262 if (pm->buffer_count > pm->buffer_position ||
3263 pm->this.next != &pm->this.current->data ||
3264 pm->this.readpos < pm->this.current->datacount)
3265 png_error(pp, "progressive read implementation error");
3266}
3267
3268/* Set up a modifier. */
3269static png_structp
3270set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id,
Matt Sarett9b1fe632015-11-25 10:21:17 -05003271 const char *name)
Chris Craikb50c2172013-07-29 15:28:30 -07003272{
3273 /* Do this first so that the modifier fields are cleared even if an error
3274 * happens allocating the png_struct. No allocation is done here so no
3275 * cleanup is required.
3276 */
3277 pm->state = modifier_start;
3278 pm->bit_depth = 0;
3279 pm->colour_type = 255;
3280
3281 pm->pending_len = 0;
3282 pm->pending_chunk = 0;
3283 pm->flush = 0;
3284 pm->buffer_count = 0;
3285 pm->buffer_position = 0;
3286
3287 return set_store_for_read(&pm->this, ppi, id, name);
3288}
3289
3290
3291/******************************** MODIFICATIONS *******************************/
3292/* Standard modifications to add chunks. These do not require the _SUPPORTED
3293 * macros because the chunks can be there regardless of whether this specific
3294 * libpng supports them.
3295 */
3296typedef struct gama_modification
3297{
3298 png_modification this;
3299 png_fixed_point gamma;
3300} gama_modification;
3301
3302static int
3303gama_modify(png_modifier *pm, png_modification *me, int add)
3304{
3305 UNUSED(add)
3306 /* This simply dumps the given gamma value into the buffer. */
3307 png_save_uint_32(pm->buffer, 4);
3308 png_save_uint_32(pm->buffer+4, CHUNK_gAMA);
3309 png_save_uint_32(pm->buffer+8, ((gama_modification*)me)->gamma);
3310 return 1;
3311}
3312
3313static void
3314gama_modification_init(gama_modification *me, png_modifier *pm, double gammad)
3315{
3316 double g;
3317
3318 modification_init(&me->this);
3319 me->this.chunk = CHUNK_gAMA;
3320 me->this.modify_fn = gama_modify;
3321 me->this.add = CHUNK_PLTE;
3322 g = fix(gammad);
3323 me->gamma = (png_fixed_point)g;
3324 me->this.next = pm->modifications;
3325 pm->modifications = &me->this;
3326}
3327
3328typedef struct chrm_modification
3329{
3330 png_modification this;
Matt Sarett9b1fe632015-11-25 10:21:17 -05003331 const color_encoding *encoding;
Chris Craikb50c2172013-07-29 15:28:30 -07003332 png_fixed_point wx, wy, rx, ry, gx, gy, bx, by;
3333} chrm_modification;
3334
3335static int
3336chrm_modify(png_modifier *pm, png_modification *me, int add)
3337{
3338 UNUSED(add)
3339 /* As with gAMA this just adds the required cHRM chunk to the buffer. */
3340 png_save_uint_32(pm->buffer , 32);
3341 png_save_uint_32(pm->buffer+ 4, CHUNK_cHRM);
3342 png_save_uint_32(pm->buffer+ 8, ((chrm_modification*)me)->wx);
3343 png_save_uint_32(pm->buffer+12, ((chrm_modification*)me)->wy);
3344 png_save_uint_32(pm->buffer+16, ((chrm_modification*)me)->rx);
3345 png_save_uint_32(pm->buffer+20, ((chrm_modification*)me)->ry);
3346 png_save_uint_32(pm->buffer+24, ((chrm_modification*)me)->gx);
3347 png_save_uint_32(pm->buffer+28, ((chrm_modification*)me)->gy);
3348 png_save_uint_32(pm->buffer+32, ((chrm_modification*)me)->bx);
3349 png_save_uint_32(pm->buffer+36, ((chrm_modification*)me)->by);
3350 return 1;
3351}
3352
3353static void
3354chrm_modification_init(chrm_modification *me, png_modifier *pm,
Matt Sarett9b1fe632015-11-25 10:21:17 -05003355 const color_encoding *encoding)
Chris Craikb50c2172013-07-29 15:28:30 -07003356{
3357 CIE_color white = white_point(encoding);
3358
3359 /* Original end points: */
3360 me->encoding = encoding;
3361
3362 /* Chromaticities (in fixed point): */
3363 me->wx = fix(chromaticity_x(white));
3364 me->wy = fix(chromaticity_y(white));
3365
3366 me->rx = fix(chromaticity_x(encoding->red));
3367 me->ry = fix(chromaticity_y(encoding->red));
3368 me->gx = fix(chromaticity_x(encoding->green));
3369 me->gy = fix(chromaticity_y(encoding->green));
3370 me->bx = fix(chromaticity_x(encoding->blue));
3371 me->by = fix(chromaticity_y(encoding->blue));
3372
3373 modification_init(&me->this);
3374 me->this.chunk = CHUNK_cHRM;
3375 me->this.modify_fn = chrm_modify;
3376 me->this.add = CHUNK_PLTE;
3377 me->this.next = pm->modifications;
3378 pm->modifications = &me->this;
3379}
3380
3381typedef struct srgb_modification
3382{
3383 png_modification this;
3384 png_byte intent;
3385} srgb_modification;
3386
3387static int
3388srgb_modify(png_modifier *pm, png_modification *me, int add)
3389{
3390 UNUSED(add)
3391 /* As above, ignore add and just make a new chunk */
3392 png_save_uint_32(pm->buffer, 1);
3393 png_save_uint_32(pm->buffer+4, CHUNK_sRGB);
3394 pm->buffer[8] = ((srgb_modification*)me)->intent;
3395 return 1;
3396}
3397
3398static void
3399srgb_modification_init(srgb_modification *me, png_modifier *pm, png_byte intent)
3400{
3401 modification_init(&me->this);
3402 me->this.chunk = CHUNK_sBIT;
3403
3404 if (intent <= 3) /* if valid, else *delete* sRGB chunks */
3405 {
3406 me->this.modify_fn = srgb_modify;
3407 me->this.add = CHUNK_PLTE;
3408 me->intent = intent;
3409 }
3410
3411 else
3412 {
3413 me->this.modify_fn = 0;
3414 me->this.add = 0;
3415 me->intent = 0;
3416 }
3417
3418 me->this.next = pm->modifications;
3419 pm->modifications = &me->this;
3420}
3421
3422#ifdef PNG_READ_GAMMA_SUPPORTED
3423typedef struct sbit_modification
3424{
3425 png_modification this;
3426 png_byte sbit;
3427} sbit_modification;
3428
3429static int
3430sbit_modify(png_modifier *pm, png_modification *me, int add)
3431{
3432 png_byte sbit = ((sbit_modification*)me)->sbit;
3433 if (pm->bit_depth > sbit)
3434 {
3435 int cb = 0;
3436 switch (pm->colour_type)
3437 {
3438 case 0:
3439 cb = 1;
3440 break;
3441
3442 case 2:
3443 case 3:
3444 cb = 3;
3445 break;
3446
3447 case 4:
3448 cb = 2;
3449 break;
3450
3451 case 6:
3452 cb = 4;
3453 break;
3454
3455 default:
3456 png_error(pm->this.pread,
3457 "unexpected colour type in sBIT modification");
3458 }
3459
3460 png_save_uint_32(pm->buffer, cb);
3461 png_save_uint_32(pm->buffer+4, CHUNK_sBIT);
3462
3463 while (cb > 0)
3464 (pm->buffer+8)[--cb] = sbit;
3465
3466 return 1;
3467 }
3468 else if (!add)
3469 {
3470 /* Remove the sBIT chunk */
3471 pm->buffer_count = pm->buffer_position = 0;
3472 return 1;
3473 }
3474 else
3475 return 0; /* do nothing */
3476}
3477
3478static void
3479sbit_modification_init(sbit_modification *me, png_modifier *pm, png_byte sbit)
3480{
3481 modification_init(&me->this);
3482 me->this.chunk = CHUNK_sBIT;
3483 me->this.modify_fn = sbit_modify;
3484 me->this.add = CHUNK_PLTE;
3485 me->sbit = sbit;
3486 me->this.next = pm->modifications;
3487 pm->modifications = &me->this;
3488}
3489#endif /* PNG_READ_GAMMA_SUPPORTED */
3490#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
3491
3492/***************************** STANDARD PNG FILES *****************************/
3493/* Standard files - write and save standard files. */
3494/* There are two basic forms of standard images. Those which attempt to have
3495 * all the possible pixel values (not possible for 16bpp images, but a range of
3496 * values are produced) and those which have a range of image sizes. The former
3497 * are used for testing transforms, in particular gamma correction and bit
3498 * reduction and increase. The latter are reserved for testing the behavior of
3499 * libpng with respect to 'odd' image sizes - particularly small images where
3500 * rows become 1 byte and interlace passes disappear.
3501 *
3502 * The first, most useful, set are the 'transform' images, the second set of
3503 * small images are the 'size' images.
3504 *
3505 * The transform files are constructed with rows which fit into a 1024 byte row
3506 * buffer. This makes allocation easier below. Further regardless of the file
3507 * format every row has 128 pixels (giving 1024 bytes for 64bpp formats).
3508 *
3509 * Files are stored with no gAMA or sBIT chunks, with a PLTE only when needed
3510 * and with an ID derived from the colour type, bit depth and interlace type
3511 * as above (FILEID). The width (128) and height (variable) are not stored in
3512 * the FILEID - instead the fields are set to 0, indicating a transform file.
3513 *
3514 * The size files ar constructed with rows a maximum of 128 bytes wide, allowing
3515 * a maximum width of 16 pixels (for the 64bpp case.) They also have a maximum
3516 * height of 16 rows. The width and height are stored in the FILEID and, being
3517 * non-zero, indicate a size file.
3518 *
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303519 * Because the PNG filter code is typically the largest CPU consumer within
3520 * libpng itself there is a tendency to attempt to optimize it. This results in
3521 * special case code which needs to be validated. To cause this to happen the
3522 * 'size' images are made to use each possible filter, in so far as this is
3523 * possible for smaller images.
3524 *
Chris Craikb50c2172013-07-29 15:28:30 -07003525 * For palette image (colour type 3) multiple transform images are stored with
3526 * the same bit depth to allow testing of more colour combinations -
3527 * particularly important for testing the gamma code because libpng uses a
3528 * different code path for palette images. For size images a single palette is
3529 * used.
3530 */
3531
3532/* Make a 'standard' palette. Because there are only 256 entries in a palette
3533 * (maximum) this actually makes a random palette in the hope that enough tests
3534 * will catch enough errors. (Note that the same palette isn't produced every
3535 * time for the same test - it depends on what previous tests have been run -
3536 * but a given set of arguments to pngvalid will always produce the same palette
3537 * at the same test! This is why pseudo-random number generators are useful for
3538 * testing.)
3539 *
3540 * The store must be open for write when this is called, otherwise an internal
3541 * error will occur. This routine contains its own magic number seed, so the
3542 * palettes generated don't change if there are intervening errors (changing the
3543 * calls to the store_mark seed.)
3544 */
3545static store_palette_entry *
3546make_standard_palette(png_store* ps, int npalette, int do_tRNS)
3547{
3548 static png_uint_32 palette_seed[2] = { 0x87654321, 9 };
3549
3550 int i = 0;
3551 png_byte values[256][4];
3552
3553 /* Always put in black and white plus the six primary and secondary colors.
3554 */
3555 for (; i<8; ++i)
3556 {
3557 values[i][1] = (png_byte)((i&1) ? 255U : 0U);
3558 values[i][2] = (png_byte)((i&2) ? 255U : 0U);
3559 values[i][3] = (png_byte)((i&4) ? 255U : 0U);
3560 }
3561
3562 /* Then add 62 grays (one quarter of the remaining 256 slots). */
3563 {
3564 int j = 0;
3565 png_byte random_bytes[4];
3566 png_byte need[256];
3567
3568 need[0] = 0; /*got black*/
3569 memset(need+1, 1, (sizeof need)-2); /*need these*/
3570 need[255] = 0; /*but not white*/
3571
3572 while (i<70)
3573 {
3574 png_byte b;
3575
3576 if (j==0)
3577 {
3578 make_four_random_bytes(palette_seed, random_bytes);
3579 j = 4;
3580 }
3581
3582 b = random_bytes[--j];
3583 if (need[b])
3584 {
3585 values[i][1] = b;
3586 values[i][2] = b;
3587 values[i++][3] = b;
3588 }
3589 }
3590 }
3591
3592 /* Finally add 192 colors at random - don't worry about matches to things we
3593 * already have, chance is less than 1/65536. Don't worry about grays,
3594 * chance is the same, so we get a duplicate or extra gray less than 1 time
3595 * in 170.
3596 */
3597 for (; i<256; ++i)
3598 make_four_random_bytes(palette_seed, values[i]);
3599
3600 /* Fill in the alpha values in the first byte. Just use all possible values
3601 * (0..255) in an apparently random order:
3602 */
3603 {
3604 store_palette_entry *palette;
3605 png_byte selector[4];
3606
3607 make_four_random_bytes(palette_seed, selector);
3608
3609 if (do_tRNS)
3610 for (i=0; i<256; ++i)
3611 values[i][0] = (png_byte)(i ^ selector[0]);
3612
3613 else
3614 for (i=0; i<256; ++i)
3615 values[i][0] = 255; /* no transparency/tRNS chunk */
3616
3617 /* 'values' contains 256 ARGB values, but we only need 'npalette'.
3618 * 'npalette' will always be a power of 2: 2, 4, 16 or 256. In the low
3619 * bit depth cases select colors at random, else it is difficult to have
3620 * a set of low bit depth palette test with any chance of a reasonable
3621 * range of colors. Do this by randomly permuting values into the low
3622 * 'npalette' entries using an XOR mask generated here. This also
3623 * permutes the npalette == 256 case in a potentially useful way (there is
3624 * no relationship between palette index and the color value therein!)
3625 */
3626 palette = store_write_palette(ps, npalette);
3627
3628 for (i=0; i<npalette; ++i)
3629 {
3630 palette[i].alpha = values[i ^ selector[1]][0];
3631 palette[i].red = values[i ^ selector[1]][1];
3632 palette[i].green = values[i ^ selector[1]][2];
3633 palette[i].blue = values[i ^ selector[1]][3];
3634 }
3635
3636 return palette;
3637 }
3638}
3639
3640/* Initialize a standard palette on a write stream. The 'do_tRNS' argument
3641 * indicates whether or not to also set the tRNS chunk.
3642 */
3643/* TODO: the png_structp here can probably be 'const' in the future */
3644static void
3645init_standard_palette(png_store *ps, png_structp pp, png_infop pi, int npalette,
3646 int do_tRNS)
3647{
3648 store_palette_entry *ppal = make_standard_palette(ps, npalette, do_tRNS);
3649
3650 {
3651 int i;
3652 png_color palette[256];
3653
3654 /* Set all entries to detect overread errors. */
3655 for (i=0; i<npalette; ++i)
3656 {
3657 palette[i].red = ppal[i].red;
3658 palette[i].green = ppal[i].green;
3659 palette[i].blue = ppal[i].blue;
3660 }
3661
3662 /* Just in case fill in the rest with detectable values: */
3663 for (; i<256; ++i)
3664 palette[i].red = palette[i].green = palette[i].blue = 42;
3665
3666 png_set_PLTE(pp, pi, palette, npalette);
3667 }
3668
3669 if (do_tRNS)
3670 {
3671 int i, j;
3672 png_byte tRNS[256];
3673
3674 /* Set all the entries, but skip trailing opaque entries */
3675 for (i=j=0; i<npalette; ++i)
3676 if ((tRNS[i] = ppal[i].alpha) < 255)
3677 j = i+1;
3678
3679 /* Fill in the remainder with a detectable value: */
3680 for (; i<256; ++i)
3681 tRNS[i] = 24;
3682
Alex Naidis7a055fd2016-10-01 12:23:07 +02003683#ifdef PNG_WRITE_tRNS_SUPPORTED
3684 if (j > 0)
3685 png_set_tRNS(pp, pi, tRNS, j, 0/*color*/);
3686#endif
Chris Craikb50c2172013-07-29 15:28:30 -07003687 }
3688}
3689
Matt Sarett9b1fe632015-11-25 10:21:17 -05003690#ifdef PNG_WRITE_tRNS_SUPPORTED
3691static void
xNombred07bb0d2020-03-10 20:17:12 +01003692set_random_tRNS(png_structp pp, png_infop pi, png_byte colour_type,
3693 int bit_depth)
Matt Sarett9b1fe632015-11-25 10:21:17 -05003694{
3695 /* To make this useful the tRNS color needs to match at least one pixel.
3696 * Random values are fine for gray, including the 16-bit case where we know
3697 * that the test image contains all the gray values. For RGB we need more
3698 * method as only 65536 different RGB values are generated.
3699 */
3700 png_color_16 tRNS;
xNombred07bb0d2020-03-10 20:17:12 +01003701 png_uint_16 mask = (png_uint_16)((1U << bit_depth)-1);
Matt Sarett9b1fe632015-11-25 10:21:17 -05003702
Matt Sarett11466862016-02-19 13:41:30 -05003703 R8(tRNS); /* makes unset fields random */
Matt Sarett9b1fe632015-11-25 10:21:17 -05003704
3705 if (colour_type & 2/*RGB*/)
3706 {
3707 if (bit_depth == 8)
3708 {
Alex Naidis7a055fd2016-10-01 12:23:07 +02003709 tRNS.red = random_u16();
3710 tRNS.green = random_u16();
Matt Sarett9b1fe632015-11-25 10:21:17 -05003711 tRNS.blue = tRNS.red ^ tRNS.green;
3712 tRNS.red &= mask;
3713 tRNS.green &= mask;
3714 tRNS.blue &= mask;
3715 }
3716
3717 else /* bit_depth == 16 */
3718 {
Alex Naidis7a055fd2016-10-01 12:23:07 +02003719 tRNS.red = random_u16();
Matt Sarett9b1fe632015-11-25 10:21:17 -05003720 tRNS.green = (png_uint_16)(tRNS.red * 257);
3721 tRNS.blue = (png_uint_16)(tRNS.green * 17);
3722 }
3723 }
3724
3725 else
Matt Sarett11466862016-02-19 13:41:30 -05003726 {
Alex Naidis7a055fd2016-10-01 12:23:07 +02003727 tRNS.gray = random_u16();
Matt Sarett9b1fe632015-11-25 10:21:17 -05003728 tRNS.gray &= mask;
Matt Sarett11466862016-02-19 13:41:30 -05003729 }
Matt Sarett9b1fe632015-11-25 10:21:17 -05003730
3731 png_set_tRNS(pp, pi, NULL, 0, &tRNS);
3732}
3733#endif
3734
Chris Craikb50c2172013-07-29 15:28:30 -07003735/* The number of passes is related to the interlace type. There was no libpng
3736 * API to determine this prior to 1.5, so we need an inquiry function:
3737 */
3738static int
3739npasses_from_interlace_type(png_const_structp pp, int interlace_type)
3740{
3741 switch (interlace_type)
3742 {
3743 default:
3744 png_error(pp, "invalid interlace type");
3745
3746 case PNG_INTERLACE_NONE:
3747 return 1;
3748
3749 case PNG_INTERLACE_ADAM7:
3750 return PNG_INTERLACE_ADAM7_PASSES;
3751 }
3752}
3753
3754static unsigned int
3755bit_size(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
3756{
3757 switch (colour_type)
3758 {
3759 default: png_error(pp, "invalid color type");
3760
3761 case 0: return bit_depth;
3762
3763 case 2: return 3*bit_depth;
3764
3765 case 3: return bit_depth;
3766
3767 case 4: return 2*bit_depth;
3768
3769 case 6: return 4*bit_depth;
3770 }
3771}
3772
3773#define TRANSFORM_WIDTH 128U
3774#define TRANSFORM_ROWMAX (TRANSFORM_WIDTH*8U)
3775#define SIZE_ROWMAX (16*8U) /* 16 pixels, max 8 bytes each - 128 bytes */
3776#define STANDARD_ROWMAX TRANSFORM_ROWMAX /* The larger of the two */
3777#define SIZE_HEIGHTMAX 16 /* Maximum range of size images */
3778
3779static size_t
3780transform_rowsize(png_const_structp pp, png_byte colour_type,
3781 png_byte bit_depth)
3782{
3783 return (TRANSFORM_WIDTH * bit_size(pp, colour_type, bit_depth)) / 8;
3784}
3785
3786/* transform_width(pp, colour_type, bit_depth) current returns the same number
3787 * every time, so just use a macro:
3788 */
3789#define transform_width(pp, colour_type, bit_depth) TRANSFORM_WIDTH
3790
3791static png_uint_32
3792transform_height(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
3793{
3794 switch (bit_size(pp, colour_type, bit_depth))
3795 {
3796 case 1:
3797 case 2:
3798 case 4:
3799 return 1; /* Total of 128 pixels */
3800
3801 case 8:
3802 return 2; /* Total of 256 pixels/bytes */
3803
3804 case 16:
3805 return 512; /* Total of 65536 pixels */
3806
3807 case 24:
3808 case 32:
3809 return 512; /* 65536 pixels */
3810
3811 case 48:
3812 case 64:
3813 return 2048;/* 4 x 65536 pixels. */
3814# define TRANSFORM_HEIGHTMAX 2048
3815
3816 default:
3817 return 0; /* Error, will be caught later */
3818 }
3819}
3820
3821#ifdef PNG_READ_SUPPORTED
3822/* The following can only be defined here, now we have the definitions
3823 * of the transform image sizes.
3824 */
3825static png_uint_32
3826standard_width(png_const_structp pp, png_uint_32 id)
3827{
3828 png_uint_32 width = WIDTH_FROM_ID(id);
3829 UNUSED(pp)
3830
3831 if (width == 0)
3832 width = transform_width(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
3833
3834 return width;
3835}
3836
3837static png_uint_32
3838standard_height(png_const_structp pp, png_uint_32 id)
3839{
3840 png_uint_32 height = HEIGHT_FROM_ID(id);
3841
3842 if (height == 0)
3843 height = transform_height(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
3844
3845 return height;
3846}
3847
3848static png_uint_32
3849standard_rowsize(png_const_structp pp, png_uint_32 id)
3850{
3851 png_uint_32 width = standard_width(pp, id);
3852
3853 /* This won't overflow: */
3854 width *= bit_size(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
3855 return (width + 7) / 8;
3856}
3857#endif /* PNG_READ_SUPPORTED */
3858
3859static void
3860transform_row(png_const_structp pp, png_byte buffer[TRANSFORM_ROWMAX],
3861 png_byte colour_type, png_byte bit_depth, png_uint_32 y)
3862{
3863 png_uint_32 v = y << 7;
3864 png_uint_32 i = 0;
3865
3866 switch (bit_size(pp, colour_type, bit_depth))
3867 {
3868 case 1:
3869 while (i<128/8) buffer[i] = (png_byte)(v & 0xff), v += 17, ++i;
3870 return;
3871
3872 case 2:
3873 while (i<128/4) buffer[i] = (png_byte)(v & 0xff), v += 33, ++i;
3874 return;
3875
3876 case 4:
3877 while (i<128/2) buffer[i] = (png_byte)(v & 0xff), v += 65, ++i;
3878 return;
3879
3880 case 8:
3881 /* 256 bytes total, 128 bytes in each row set as follows: */
3882 while (i<128) buffer[i] = (png_byte)(v & 0xff), ++v, ++i;
3883 return;
3884
3885 case 16:
3886 /* Generate all 65536 pixel values in order, which includes the 8 bit
3887 * GA case as well as the 16 bit G case.
3888 */
3889 while (i<128)
3890 {
3891 buffer[2*i] = (png_byte)((v>>8) & 0xff);
3892 buffer[2*i+1] = (png_byte)(v & 0xff);
3893 ++v;
3894 ++i;
3895 }
3896
3897 return;
3898
3899 case 24:
3900 /* 65535 pixels, but rotate the values. */
3901 while (i<128)
3902 {
3903 /* Three bytes per pixel, r, g, b, make b by r^g */
3904 buffer[3*i+0] = (png_byte)((v >> 8) & 0xff);
3905 buffer[3*i+1] = (png_byte)(v & 0xff);
3906 buffer[3*i+2] = (png_byte)(((v >> 8) ^ v) & 0xff);
3907 ++v;
3908 ++i;
3909 }
3910
3911 return;
3912
3913 case 32:
3914 /* 65535 pixels, r, g, b, a; just replicate */
3915 while (i<128)
3916 {
3917 buffer[4*i+0] = (png_byte)((v >> 8) & 0xff);
3918 buffer[4*i+1] = (png_byte)(v & 0xff);
3919 buffer[4*i+2] = (png_byte)((v >> 8) & 0xff);
3920 buffer[4*i+3] = (png_byte)(v & 0xff);
3921 ++v;
3922 ++i;
3923 }
3924
3925 return;
3926
3927 case 48:
3928 /* y is maximum 2047, giving 4x65536 pixels, make 'r' increase by 1 at
3929 * each pixel, g increase by 257 (0x101) and 'b' by 0x1111:
3930 */
3931 while (i<128)
3932 {
3933 png_uint_32 t = v++;
3934 buffer[6*i+0] = (png_byte)((t >> 8) & 0xff);
3935 buffer[6*i+1] = (png_byte)(t & 0xff);
3936 t *= 257;
3937 buffer[6*i+2] = (png_byte)((t >> 8) & 0xff);
3938 buffer[6*i+3] = (png_byte)(t & 0xff);
3939 t *= 17;
3940 buffer[6*i+4] = (png_byte)((t >> 8) & 0xff);
3941 buffer[6*i+5] = (png_byte)(t & 0xff);
3942 ++i;
3943 }
3944
3945 return;
3946
3947 case 64:
3948 /* As above in the 32 bit case. */
3949 while (i<128)
3950 {
3951 png_uint_32 t = v++;
3952 buffer[8*i+0] = (png_byte)((t >> 8) & 0xff);
3953 buffer[8*i+1] = (png_byte)(t & 0xff);
3954 buffer[8*i+4] = (png_byte)((t >> 8) & 0xff);
3955 buffer[8*i+5] = (png_byte)(t & 0xff);
3956 t *= 257;
3957 buffer[8*i+2] = (png_byte)((t >> 8) & 0xff);
3958 buffer[8*i+3] = (png_byte)(t & 0xff);
3959 buffer[8*i+6] = (png_byte)((t >> 8) & 0xff);
3960 buffer[8*i+7] = (png_byte)(t & 0xff);
3961 ++i;
3962 }
3963 return;
3964
3965 default:
3966 break;
3967 }
3968
3969 png_error(pp, "internal error");
3970}
3971
3972/* This is just to do the right cast - could be changed to a function to check
3973 * 'bd' but there isn't much point.
3974 */
3975#define DEPTH(bd) ((png_byte)(1U << (bd)))
3976
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303977/* This is just a helper for compiling on minimal systems with no write
3978 * interlacing support. If there is no write interlacing we can't generate test
3979 * cases with interlace:
3980 */
3981#ifdef PNG_WRITE_INTERLACING_SUPPORTED
3982# define INTERLACE_LAST PNG_INTERLACE_LAST
3983# define check_interlace_type(type) ((void)(type))
Matt Sarett9b1fe632015-11-25 10:21:17 -05003984# define set_write_interlace_handling(pp,type) png_set_interlace_handling(pp)
Matt Sarett06f10872016-01-04 12:56:20 -05003985# define do_own_interlace 0
Matt Sarett9b1fe632015-11-25 10:21:17 -05003986#elif PNG_LIBPNG_VER < 10700
3987# define set_write_interlace_handling(pp,type) (1)
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303988static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05003989check_interlace_type(int const interlace_type)
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303990{
Matt Sarett9b1fe632015-11-25 10:21:17 -05003991 /* Prior to 1.7.0 libpng does not support the write of an interlaced image
3992 * unless PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the
3993 * code here does the pixel interlace itself, so:
3994 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05303995 if (interlace_type != PNG_INTERLACE_NONE)
3996 {
3997 /* This is an internal error - --interlace tests should be skipped, not
3998 * attempted.
3999 */
4000 fprintf(stderr, "pngvalid: no interlace support\n");
4001 exit(99);
4002 }
4003}
Matt Sarett9b1fe632015-11-25 10:21:17 -05004004# define INTERLACE_LAST (PNG_INTERLACE_NONE+1)
Matt Sarett06f10872016-01-04 12:56:20 -05004005# define do_own_interlace 0
Matt Sarett9b1fe632015-11-25 10:21:17 -05004006#else /* libpng 1.7+ */
4007# define set_write_interlace_handling(pp,type)\
4008 npasses_from_interlace_type(pp,type)
4009# define check_interlace_type(type) ((void)(type))
Matt Sarett06f10872016-01-04 12:56:20 -05004010# define INTERLACE_LAST PNG_INTERLACE_LAST
4011# define do_own_interlace 1
Matt Sarett9b1fe632015-11-25 10:21:17 -05004012#endif /* WRITE_INTERLACING tests */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304013
Leon Scroggins III3cc83ac2017-10-06 11:02:56 -04004014#if PNG_LIBPNG_VER >= 10700 || defined PNG_WRITE_INTERLACING_SUPPORTED
4015# define CAN_WRITE_INTERLACE 1
4016#else
4017# define CAN_WRITE_INTERLACE 0
4018#endif
Matt Sarett9b1fe632015-11-25 10:21:17 -05004019
Matt Sarett06f10872016-01-04 12:56:20 -05004020/* Do the same thing for read interlacing; this controls whether read tests do
4021 * their own de-interlace or use libpng.
4022 */
4023#ifdef PNG_READ_INTERLACING_SUPPORTED
4024# define do_read_interlace 0
4025#else /* no libpng read interlace support */
4026# define do_read_interlace 1
4027#endif
4028/* The following two routines use the PNG interlace support macros from
4029 * png.h to interlace or deinterlace rows.
4030 */
4031static void
4032interlace_row(png_bytep buffer, png_const_bytep imageRow,
4033 unsigned int pixel_size, png_uint_32 w, int pass, int littleendian)
4034{
4035 png_uint_32 xin, xout, xstep;
4036
4037 /* Note that this can, trivially, be optimized to a memcpy on pass 7, the
4038 * code is presented this way to make it easier to understand. In practice
4039 * consult the code in the libpng source to see other ways of doing this.
4040 *
4041 * It is OK for buffer and imageRow to be identical, because 'xin' moves
4042 * faster than 'xout' and we copy up.
4043 */
4044 xin = PNG_PASS_START_COL(pass);
4045 xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
4046
4047 for (xout=0; xin<w; xin+=xstep)
4048 {
4049 pixel_copy(buffer, xout, imageRow, xin, pixel_size, littleendian);
4050 ++xout;
4051 }
4052}
4053
4054#ifdef PNG_READ_SUPPORTED
4055static void
4056deinterlace_row(png_bytep buffer, png_const_bytep row,
4057 unsigned int pixel_size, png_uint_32 w, int pass, int littleendian)
4058{
4059 /* The inverse of the above, 'row' is part of row 'y' of the output image,
4060 * in 'buffer'. The image is 'w' wide and this is pass 'pass', distribute
4061 * the pixels of row into buffer and return the number written (to allow
4062 * this to be checked).
4063 */
4064 png_uint_32 xin, xout, xstep;
4065
4066 xout = PNG_PASS_START_COL(pass);
4067 xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
4068
4069 for (xin=0; xout<w; xout+=xstep)
4070 {
4071 pixel_copy(buffer, xout, row, xin, pixel_size, littleendian);
4072 ++xin;
4073 }
4074}
4075#endif /* PNG_READ_SUPPORTED */
4076
Matt Sarett9b1fe632015-11-25 10:21:17 -05004077/* Make a standardized image given an image colour type, bit depth and
Chris Craikb50c2172013-07-29 15:28:30 -07004078 * interlace type. The standard images have a very restricted range of
4079 * rows and heights and are used for testing transforms rather than image
4080 * layout details. See make_size_images below for a way to make images
4081 * that test odd sizes along with the libpng interlace handling.
4082 */
Matt Sarett11466862016-02-19 13:41:30 -05004083#ifdef PNG_WRITE_FILTER_SUPPORTED
4084static void
4085choose_random_filter(png_structp pp, int start)
4086{
4087 /* Choose filters randomly except that on the very first row ensure that
4088 * there is at least one previous row filter.
4089 */
4090 int filters = PNG_ALL_FILTERS & random_mod(256U);
4091
4092 /* There may be no filters; skip the setting. */
4093 if (filters != 0)
4094 {
4095 if (start && filters < PNG_FILTER_UP)
4096 filters |= PNG_FILTER_UP;
4097
4098 png_set_filter(pp, 0/*method*/, filters);
4099 }
4100}
4101#else /* !WRITE_FILTER */
4102# define choose_random_filter(pp, start) ((void)0)
4103#endif /* !WRITE_FILTER */
4104
Chris Craikb50c2172013-07-29 15:28:30 -07004105static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05004106make_transform_image(png_store* const ps, png_byte const colour_type,
4107 png_byte const bit_depth, unsigned int palette_number,
Chris Craikb50c2172013-07-29 15:28:30 -07004108 int interlace_type, png_const_charp name)
4109{
4110 context(ps, fault);
4111
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304112 check_interlace_type(interlace_type);
4113
Chris Craikb50c2172013-07-29 15:28:30 -07004114 Try
4115 {
4116 png_infop pi;
4117 png_structp pp = set_store_for_write(ps, &pi, name);
Matt Sarett06f10872016-01-04 12:56:20 -05004118 png_uint_32 h, w;
Chris Craikb50c2172013-07-29 15:28:30 -07004119
4120 /* In the event of a problem return control to the Catch statement below
4121 * to do the clean up - it is not possible to 'return' directly from a Try
4122 * block.
4123 */
4124 if (pp == NULL)
4125 Throw ps;
4126
Matt Sarett06f10872016-01-04 12:56:20 -05004127 w = transform_width(pp, colour_type, bit_depth);
Chris Craikb50c2172013-07-29 15:28:30 -07004128 h = transform_height(pp, colour_type, bit_depth);
4129
Matt Sarett06f10872016-01-04 12:56:20 -05004130 png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
Chris Craikb50c2172013-07-29 15:28:30 -07004131 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
4132
4133#ifdef PNG_TEXT_SUPPORTED
4134# if defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED)
4135# define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_zTXt
4136# else
4137# define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_NONE
4138# endif
4139 {
4140 static char key[] = "image name"; /* must be writeable */
4141 size_t pos;
4142 png_text text;
4143 char copy[FILE_NAME_SIZE];
4144
4145 /* Use a compressed text string to test the correct interaction of text
4146 * compression and IDAT compression.
4147 */
4148 text.compression = TEXT_COMPRESSION;
4149 text.key = key;
4150 /* Yuck: the text must be writable! */
4151 pos = safecat(copy, sizeof copy, 0, ps->wname);
4152 text.text = copy;
4153 text.text_length = pos;
4154 text.itxt_length = 0;
4155 text.lang = 0;
4156 text.lang_key = 0;
4157
4158 png_set_text(pp, pi, &text, 1);
4159 }
4160#endif
4161
4162 if (colour_type == 3) /* palette */
4163 init_standard_palette(ps, pp, pi, 1U << bit_depth, 1/*do tRNS*/);
4164
Matt Sarett9b1fe632015-11-25 10:21:17 -05004165# ifdef PNG_WRITE_tRNS_SUPPORTED
4166 else if (palette_number)
4167 set_random_tRNS(pp, pi, colour_type, bit_depth);
4168# endif
4169
Chris Craikb50c2172013-07-29 15:28:30 -07004170 png_write_info(pp, pi);
4171
4172 if (png_get_rowbytes(pp, pi) !=
4173 transform_rowsize(pp, colour_type, bit_depth))
Matt Sarett9b1fe632015-11-25 10:21:17 -05004174 png_error(pp, "transform row size incorrect");
Chris Craikb50c2172013-07-29 15:28:30 -07004175
4176 else
4177 {
4178 /* Somewhat confusingly this must be called *after* png_write_info
4179 * because if it is called before, the information in *pp has not been
4180 * updated to reflect the interlaced image.
4181 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05004182 int npasses = set_write_interlace_handling(pp, interlace_type);
Chris Craikb50c2172013-07-29 15:28:30 -07004183 int pass;
4184
4185 if (npasses != npasses_from_interlace_type(pp, interlace_type))
4186 png_error(pp, "write: png_set_interlace_handling failed");
4187
4188 for (pass=0; pass<npasses; ++pass)
4189 {
4190 png_uint_32 y;
4191
Matt Sarett06f10872016-01-04 12:56:20 -05004192 /* do_own_interlace is a pre-defined boolean (a #define) which is
4193 * set if we have to work out the interlaced rows here.
4194 */
Chris Craikb50c2172013-07-29 15:28:30 -07004195 for (y=0; y<h; ++y)
4196 {
4197 png_byte buffer[TRANSFORM_ROWMAX];
4198
4199 transform_row(pp, buffer, colour_type, bit_depth, y);
Matt Sarett06f10872016-01-04 12:56:20 -05004200
4201# if do_own_interlace
4202 /* If do_own_interlace *and* the image is interlaced we need a
4203 * reduced interlace row; this may be reduced to empty.
4204 */
4205 if (interlace_type == PNG_INTERLACE_ADAM7)
4206 {
4207 /* The row must not be written if it doesn't exist, notice
4208 * that there are two conditions here, either the row isn't
4209 * ever in the pass or the row would be but isn't wide
4210 * enough to contribute any pixels. In fact the wPass test
4211 * can be used to skip the whole y loop in this case.
4212 */
4213 if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
4214 PNG_PASS_COLS(w, pass) > 0)
4215 interlace_row(buffer, buffer,
4216 bit_size(pp, colour_type, bit_depth), w, pass,
4217 0/*data always bigendian*/);
4218 else
4219 continue;
4220 }
4221# endif /* do_own_interlace */
4222
Matt Sarett11466862016-02-19 13:41:30 -05004223 choose_random_filter(pp, pass == 0 && y == 0);
Chris Craikb50c2172013-07-29 15:28:30 -07004224 png_write_row(pp, buffer);
4225 }
4226 }
4227 }
4228
4229#ifdef PNG_TEXT_SUPPORTED
4230 {
4231 static char key[] = "end marker";
4232 static char comment[] = "end";
4233 png_text text;
4234
4235 /* Use a compressed text string to test the correct interaction of text
4236 * compression and IDAT compression.
4237 */
4238 text.compression = TEXT_COMPRESSION;
4239 text.key = key;
4240 text.text = comment;
4241 text.text_length = (sizeof comment)-1;
4242 text.itxt_length = 0;
4243 text.lang = 0;
4244 text.lang_key = 0;
4245
4246 png_set_text(pp, pi, &text, 1);
4247 }
4248#endif
4249
4250 png_write_end(pp, pi);
4251
4252 /* And store this under the appropriate id, then clean up. */
4253 store_storefile(ps, FILEID(colour_type, bit_depth, palette_number,
4254 interlace_type, 0, 0, 0));
4255
4256 store_write_reset(ps);
4257 }
4258
4259 Catch(fault)
4260 {
4261 /* Use the png_store returned by the exception. This may help the compiler
4262 * because 'ps' is not used in this branch of the setjmp. Note that fault
4263 * and ps will always be the same value.
4264 */
4265 store_write_reset(fault);
4266 }
4267}
4268
4269static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05004270make_transform_images(png_modifier *pm)
Chris Craikb50c2172013-07-29 15:28:30 -07004271{
4272 png_byte colour_type = 0;
4273 png_byte bit_depth = 0;
4274 unsigned int palette_number = 0;
4275
4276 /* This is in case of errors. */
Matt Sarett9b1fe632015-11-25 10:21:17 -05004277 safecat(pm->this.test, sizeof pm->this.test, 0, "make standard images");
Chris Craikb50c2172013-07-29 15:28:30 -07004278
4279 /* Use next_format to enumerate all the combinations we test, including
Matt Sarett9b1fe632015-11-25 10:21:17 -05004280 * generating multiple low bit depth palette images. Non-A images (palette
4281 * and direct) are created with and without tRNS chunks.
Chris Craikb50c2172013-07-29 15:28:30 -07004282 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05004283 while (next_format(&colour_type, &bit_depth, &palette_number, 1, 1))
Chris Craikb50c2172013-07-29 15:28:30 -07004284 {
4285 int interlace_type;
4286
4287 for (interlace_type = PNG_INTERLACE_NONE;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304288 interlace_type < INTERLACE_LAST; ++interlace_type)
Chris Craikb50c2172013-07-29 15:28:30 -07004289 {
4290 char name[FILE_NAME_SIZE];
4291
4292 standard_name(name, sizeof name, 0, colour_type, bit_depth,
Matt Sarett06f10872016-01-04 12:56:20 -05004293 palette_number, interlace_type, 0, 0, do_own_interlace);
Matt Sarett9b1fe632015-11-25 10:21:17 -05004294 make_transform_image(&pm->this, colour_type, bit_depth, palette_number,
Chris Craikb50c2172013-07-29 15:28:30 -07004295 interlace_type, name);
4296 }
4297 }
4298}
4299
Chris Craikb50c2172013-07-29 15:28:30 -07004300/* Build a single row for the 'size' test images; this fills in only the
4301 * first bit_width bits of the sample row.
4302 */
4303static void
4304size_row(png_byte buffer[SIZE_ROWMAX], png_uint_32 bit_width, png_uint_32 y)
4305{
4306 /* height is in the range 1 to 16, so: */
4307 y = ((y & 1) << 7) + ((y & 2) << 6) + ((y & 4) << 5) + ((y & 8) << 4);
4308 /* the following ensures bits are set in small images: */
4309 y ^= 0xA5;
4310
4311 while (bit_width >= 8)
4312 *buffer++ = (png_byte)y++, bit_width -= 8;
4313
4314 /* There may be up to 7 remaining bits, these go in the most significant
4315 * bits of the byte.
4316 */
4317 if (bit_width > 0)
4318 {
4319 png_uint_32 mask = (1U<<(8-bit_width))-1;
4320 *buffer = (png_byte)((*buffer & mask) | (y & ~mask));
4321 }
4322}
4323
4324static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05004325make_size_image(png_store* const ps, png_byte const colour_type,
4326 png_byte const bit_depth, int const interlace_type,
4327 png_uint_32 const w, png_uint_32 const h,
4328 int const do_interlace)
Chris Craikb50c2172013-07-29 15:28:30 -07004329{
4330 context(ps, fault);
4331
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304332 check_interlace_type(interlace_type);
4333
Chris Craikb50c2172013-07-29 15:28:30 -07004334 Try
4335 {
4336 png_infop pi;
4337 png_structp pp;
4338 unsigned int pixel_size;
4339
4340 /* Make a name and get an appropriate id for the store: */
4341 char name[FILE_NAME_SIZE];
xNombred07bb0d2020-03-10 20:17:12 +01004342 png_uint_32 id = FILEID(colour_type, bit_depth, 0/*palette*/,
Chris Craikb50c2172013-07-29 15:28:30 -07004343 interlace_type, w, h, do_interlace);
4344
4345 standard_name_from_id(name, sizeof name, 0, id);
4346 pp = set_store_for_write(ps, &pi, name);
4347
4348 /* In the event of a problem return control to the Catch statement below
4349 * to do the clean up - it is not possible to 'return' directly from a Try
4350 * block.
4351 */
4352 if (pp == NULL)
4353 Throw ps;
4354
4355 png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
4356 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
4357
4358#ifdef PNG_TEXT_SUPPORTED
4359 {
4360 static char key[] = "image name"; /* must be writeable */
4361 size_t pos;
4362 png_text text;
4363 char copy[FILE_NAME_SIZE];
4364
4365 /* Use a compressed text string to test the correct interaction of text
4366 * compression and IDAT compression.
4367 */
4368 text.compression = TEXT_COMPRESSION;
4369 text.key = key;
4370 /* Yuck: the text must be writable! */
4371 pos = safecat(copy, sizeof copy, 0, ps->wname);
4372 text.text = copy;
4373 text.text_length = pos;
4374 text.itxt_length = 0;
4375 text.lang = 0;
4376 text.lang_key = 0;
4377
4378 png_set_text(pp, pi, &text, 1);
4379 }
4380#endif
4381
4382 if (colour_type == 3) /* palette */
4383 init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
4384
4385 png_write_info(pp, pi);
4386
4387 /* Calculate the bit size, divide by 8 to get the byte size - this won't
4388 * overflow because we know the w values are all small enough even for
4389 * a system where 'unsigned int' is only 16 bits.
4390 */
4391 pixel_size = bit_size(pp, colour_type, bit_depth);
4392 if (png_get_rowbytes(pp, pi) != ((w * pixel_size) + 7) / 8)
Matt Sarett9b1fe632015-11-25 10:21:17 -05004393 png_error(pp, "size row size incorrect");
Chris Craikb50c2172013-07-29 15:28:30 -07004394
4395 else
4396 {
4397 int npasses = npasses_from_interlace_type(pp, interlace_type);
4398 png_uint_32 y;
4399 int pass;
4400 png_byte image[16][SIZE_ROWMAX];
4401
4402 /* To help consistent error detection make the parts of this buffer
4403 * that aren't set below all '1':
4404 */
4405 memset(image, 0xff, sizeof image);
4406
Matt Sarett9b1fe632015-11-25 10:21:17 -05004407 if (!do_interlace &&
4408 npasses != set_write_interlace_handling(pp, interlace_type))
Chris Craikb50c2172013-07-29 15:28:30 -07004409 png_error(pp, "write: png_set_interlace_handling failed");
4410
4411 /* Prepare the whole image first to avoid making it 7 times: */
4412 for (y=0; y<h; ++y)
4413 size_row(image[y], w * pixel_size, y);
4414
4415 for (pass=0; pass<npasses; ++pass)
4416 {
4417 /* The following two are for checking the macros: */
xNombred07bb0d2020-03-10 20:17:12 +01004418 png_uint_32 wPass = PNG_PASS_COLS(w, pass);
Chris Craikb50c2172013-07-29 15:28:30 -07004419
4420 /* If do_interlace is set we don't call png_write_row for every
4421 * row because some of them are empty. In fact, for a 1x1 image,
4422 * most of them are empty!
4423 */
4424 for (y=0; y<h; ++y)
4425 {
4426 png_const_bytep row = image[y];
4427 png_byte tempRow[SIZE_ROWMAX];
4428
4429 /* If do_interlace *and* the image is interlaced we
4430 * need a reduced interlace row; this may be reduced
4431 * to empty.
4432 */
4433 if (do_interlace && interlace_type == PNG_INTERLACE_ADAM7)
4434 {
4435 /* The row must not be written if it doesn't exist, notice
4436 * that there are two conditions here, either the row isn't
4437 * ever in the pass or the row would be but isn't wide
4438 * enough to contribute any pixels. In fact the wPass test
4439 * can be used to skip the whole y loop in this case.
4440 */
4441 if (PNG_ROW_IN_INTERLACE_PASS(y, pass) && wPass > 0)
4442 {
4443 /* Set to all 1's for error detection (libpng tends to
4444 * set unset things to 0).
4445 */
4446 memset(tempRow, 0xff, sizeof tempRow);
Matt Sarett06f10872016-01-04 12:56:20 -05004447 interlace_row(tempRow, row, pixel_size, w, pass,
4448 0/*data always bigendian*/);
Chris Craikb50c2172013-07-29 15:28:30 -07004449 row = tempRow;
4450 }
4451 else
4452 continue;
4453 }
4454
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304455# ifdef PNG_WRITE_FILTER_SUPPORTED
4456 /* Only get to here if the row has some pixels in it, set the
4457 * filters to 'all' for the very first row and thereafter to a
4458 * single filter. It isn't well documented, but png_set_filter
4459 * does accept a filter number (per the spec) as well as a bit
4460 * mask.
4461 *
Matt Sarett11466862016-02-19 13:41:30 -05004462 * The code now uses filters at random, except that on the first
4463 * row of an image it ensures that a previous row filter is in
4464 * the set so that libpng allocates the row buffer.
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304465 */
Matt Sarett11466862016-02-19 13:41:30 -05004466 {
4467 int filters = 8 << random_mod(PNG_FILTER_VALUE_LAST);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304468
Matt Sarett11466862016-02-19 13:41:30 -05004469 if (pass == 0 && y == 0 &&
4470 (filters < PNG_FILTER_UP || w == 1U))
4471 filters |= PNG_FILTER_UP;
4472
4473 png_set_filter(pp, 0/*method*/, filters);
4474 }
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304475# endif
4476
Chris Craikb50c2172013-07-29 15:28:30 -07004477 png_write_row(pp, row);
4478 }
4479 }
4480 }
4481
4482#ifdef PNG_TEXT_SUPPORTED
4483 {
4484 static char key[] = "end marker";
4485 static char comment[] = "end";
4486 png_text text;
4487
4488 /* Use a compressed text string to test the correct interaction of text
4489 * compression and IDAT compression.
4490 */
4491 text.compression = TEXT_COMPRESSION;
4492 text.key = key;
4493 text.text = comment;
4494 text.text_length = (sizeof comment)-1;
4495 text.itxt_length = 0;
4496 text.lang = 0;
4497 text.lang_key = 0;
4498
4499 png_set_text(pp, pi, &text, 1);
4500 }
4501#endif
4502
4503 png_write_end(pp, pi);
4504
4505 /* And store this under the appropriate id, then clean up. */
4506 store_storefile(ps, id);
4507
4508 store_write_reset(ps);
4509 }
4510
4511 Catch(fault)
4512 {
4513 /* Use the png_store returned by the exception. This may help the compiler
4514 * because 'ps' is not used in this branch of the setjmp. Note that fault
4515 * and ps will always be the same value.
4516 */
4517 store_write_reset(fault);
4518 }
4519}
4520
4521static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05004522make_size(png_store* const ps, png_byte const colour_type, int bdlo,
4523 int const bdhi)
Chris Craikb50c2172013-07-29 15:28:30 -07004524{
4525 for (; bdlo <= bdhi; ++bdlo)
4526 {
4527 png_uint_32 width;
4528
4529 for (width = 1; width <= 16; ++width)
4530 {
4531 png_uint_32 height;
4532
4533 for (height = 1; height <= 16; ++height)
4534 {
4535 /* The four combinations of DIY interlace and interlace or not -
4536 * no interlace + DIY should be identical to no interlace with
4537 * libpng doing it.
4538 */
4539 make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
4540 width, height, 0);
4541 make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
4542 width, height, 1);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304543# ifdef PNG_WRITE_INTERLACING_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07004544 make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
4545 width, height, 0);
Matt Sarett9b1fe632015-11-25 10:21:17 -05004546# endif
4547# if CAN_WRITE_INTERLACE
4548 /* 1.7.0 removes the hack that prevented app write of an interlaced
Matt Sarett06f10872016-01-04 12:56:20 -05004549 * image if WRITE_INTERLACE was not supported
Matt Sarett9b1fe632015-11-25 10:21:17 -05004550 */
Chris Craikb50c2172013-07-29 15:28:30 -07004551 make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
4552 width, height, 1);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304553# endif
Chris Craikb50c2172013-07-29 15:28:30 -07004554 }
4555 }
4556 }
4557}
4558
4559static void
4560make_size_images(png_store *ps)
4561{
4562 /* This is in case of errors. */
4563 safecat(ps->test, sizeof ps->test, 0, "make size images");
4564
4565 /* Arguments are colour_type, low bit depth, high bit depth
4566 */
4567 make_size(ps, 0, 0, WRITE_BDHI);
4568 make_size(ps, 2, 3, WRITE_BDHI);
4569 make_size(ps, 3, 0, 3 /*palette: max 8 bits*/);
4570 make_size(ps, 4, 3, WRITE_BDHI);
4571 make_size(ps, 6, 3, WRITE_BDHI);
4572}
4573
4574#ifdef PNG_READ_SUPPORTED
4575/* Return a row based on image id and 'y' for checking: */
4576static void
4577standard_row(png_const_structp pp, png_byte std[STANDARD_ROWMAX],
4578 png_uint_32 id, png_uint_32 y)
4579{
4580 if (WIDTH_FROM_ID(id) == 0)
4581 transform_row(pp, std, COL_FROM_ID(id), DEPTH_FROM_ID(id), y);
4582 else
4583 size_row(std, WIDTH_FROM_ID(id) * bit_size(pp, COL_FROM_ID(id),
4584 DEPTH_FROM_ID(id)), y);
4585}
4586#endif /* PNG_READ_SUPPORTED */
4587
4588/* Tests - individual test cases */
4589/* Like 'make_standard' but errors are deliberately introduced into the calls
4590 * to ensure that they get detected - it should not be possible to write an
4591 * invalid image with libpng!
4592 */
4593/* TODO: the 'set' functions can probably all be made to take a
4594 * png_const_structp rather than a modifiable one.
4595 */
4596#ifdef PNG_WARNINGS_SUPPORTED
4597static void
4598sBIT0_error_fn(png_structp pp, png_infop pi)
4599{
4600 /* 0 is invalid... */
4601 png_color_8 bad;
4602 bad.red = bad.green = bad.blue = bad.gray = bad.alpha = 0;
4603 png_set_sBIT(pp, pi, &bad);
4604}
4605
4606static void
4607sBIT_error_fn(png_structp pp, png_infop pi)
4608{
4609 png_byte bit_depth;
4610 png_color_8 bad;
4611
4612 if (png_get_color_type(pp, pi) == PNG_COLOR_TYPE_PALETTE)
4613 bit_depth = 8;
4614
4615 else
4616 bit_depth = png_get_bit_depth(pp, pi);
4617
4618 /* Now we know the bit depth we can easily generate an invalid sBIT entry */
4619 bad.red = bad.green = bad.blue = bad.gray = bad.alpha =
4620 (png_byte)(bit_depth+1);
4621 png_set_sBIT(pp, pi, &bad);
4622}
4623
Matt Sarett9b1fe632015-11-25 10:21:17 -05004624static const struct
Chris Craikb50c2172013-07-29 15:28:30 -07004625{
4626 void (*fn)(png_structp, png_infop);
Matt Sarett9b1fe632015-11-25 10:21:17 -05004627 const char *msg;
Chris Craikb50c2172013-07-29 15:28:30 -07004628 unsigned int warning :1; /* the error is a warning... */
4629} error_test[] =
4630 {
Matt Sarett9b1fe632015-11-25 10:21:17 -05004631 /* no warnings makes these errors undetectable prior to 1.7.0 */
4632 { sBIT0_error_fn, "sBIT(0): failed to detect error",
4633 PNG_LIBPNG_VER < 10700 },
4634
Matt Sarett06f10872016-01-04 12:56:20 -05004635 { sBIT_error_fn, "sBIT(too big): failed to detect error",
Matt Sarett9b1fe632015-11-25 10:21:17 -05004636 PNG_LIBPNG_VER < 10700 },
Chris Craikb50c2172013-07-29 15:28:30 -07004637 };
4638
4639static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05004640make_error(png_store* const ps, png_byte const colour_type,
Chris Craikb50c2172013-07-29 15:28:30 -07004641 png_byte bit_depth, int interlace_type, int test, png_const_charp name)
4642{
Chris Craikb50c2172013-07-29 15:28:30 -07004643 context(ps, fault);
4644
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304645 check_interlace_type(interlace_type);
4646
Chris Craikb50c2172013-07-29 15:28:30 -07004647 Try
4648 {
Chris Craikb50c2172013-07-29 15:28:30 -07004649 png_infop pi;
xNombred07bb0d2020-03-10 20:17:12 +01004650 png_structp pp = set_store_for_write(ps, &pi, name);
Matt Sarett06f10872016-01-04 12:56:20 -05004651 png_uint_32 w, h;
Matt Sarett9b1fe632015-11-25 10:21:17 -05004652 gnu_volatile(pp)
Chris Craikb50c2172013-07-29 15:28:30 -07004653
4654 if (pp == NULL)
4655 Throw ps;
4656
Matt Sarett06f10872016-01-04 12:56:20 -05004657 w = transform_width(pp, colour_type, bit_depth);
4658 gnu_volatile(w)
4659 h = transform_height(pp, colour_type, bit_depth);
4660 gnu_volatile(h)
4661 png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
4662 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
Chris Craikb50c2172013-07-29 15:28:30 -07004663
4664 if (colour_type == 3) /* palette */
4665 init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
4666
4667 /* Time for a few errors; these are in various optional chunks, the
4668 * standard tests test the standard chunks pretty well.
4669 */
4670# define exception__prev exception_prev_1
4671# define exception__env exception_env_1
4672 Try
4673 {
Matt Sarett9b1fe632015-11-25 10:21:17 -05004674 gnu_volatile(exception__prev)
4675
Chris Craikb50c2172013-07-29 15:28:30 -07004676 /* Expect this to throw: */
4677 ps->expect_error = !error_test[test].warning;
4678 ps->expect_warning = error_test[test].warning;
4679 ps->saw_warning = 0;
4680 error_test[test].fn(pp, pi);
4681
4682 /* Normally the error is only detected here: */
4683 png_write_info(pp, pi);
4684
4685 /* And handle the case where it was only a warning: */
4686 if (ps->expect_warning && ps->saw_warning)
4687 Throw ps;
4688
4689 /* If we get here there is a problem, we have success - no error or
4690 * no warning - when we shouldn't have success. Log an error.
4691 */
4692 store_log(ps, pp, error_test[test].msg, 1 /*error*/);
4693 }
4694
4695 Catch (fault)
Matt Sarett9b1fe632015-11-25 10:21:17 -05004696 { /* expected exit */
4697 }
Chris Craikb50c2172013-07-29 15:28:30 -07004698#undef exception__prev
4699#undef exception__env
4700
4701 /* And clear these flags */
Chris Craikb50c2172013-07-29 15:28:30 -07004702 ps->expect_warning = 0;
4703
Matt Sarett11466862016-02-19 13:41:30 -05004704 if (ps->expect_error)
4705 ps->expect_error = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07004706
4707 else
4708 {
Matt Sarett11466862016-02-19 13:41:30 -05004709 /* Now write the whole image, just to make sure that the detected, or
xNombred07bb0d2020-03-10 20:17:12 +01004710 * undetected, error has not created problems inside libpng. This
Matt Sarett11466862016-02-19 13:41:30 -05004711 * doesn't work if there was a png_error in png_write_info because that
4712 * can abort before PLTE was written.
4713 */
4714 if (png_get_rowbytes(pp, pi) !=
4715 transform_rowsize(pp, colour_type, bit_depth))
4716 png_error(pp, "row size incorrect");
Chris Craikb50c2172013-07-29 15:28:30 -07004717
Matt Sarett11466862016-02-19 13:41:30 -05004718 else
Chris Craikb50c2172013-07-29 15:28:30 -07004719 {
Matt Sarett11466862016-02-19 13:41:30 -05004720 int npasses = set_write_interlace_handling(pp, interlace_type);
4721 int pass;
Chris Craikb50c2172013-07-29 15:28:30 -07004722
Matt Sarett11466862016-02-19 13:41:30 -05004723 if (npasses != npasses_from_interlace_type(pp, interlace_type))
4724 png_error(pp, "write: png_set_interlace_handling failed");
4725
4726 for (pass=0; pass<npasses; ++pass)
Chris Craikb50c2172013-07-29 15:28:30 -07004727 {
Matt Sarett11466862016-02-19 13:41:30 -05004728 png_uint_32 y;
Chris Craikb50c2172013-07-29 15:28:30 -07004729
Matt Sarett11466862016-02-19 13:41:30 -05004730 for (y=0; y<h; ++y)
4731 {
4732 png_byte buffer[TRANSFORM_ROWMAX];
Matt Sarett06f10872016-01-04 12:56:20 -05004733
Matt Sarett11466862016-02-19 13:41:30 -05004734 transform_row(pp, buffer, colour_type, bit_depth, y);
4735
4736# if do_own_interlace
4737 /* If do_own_interlace *and* the image is interlaced we
4738 * need a reduced interlace row; this may be reduced to
4739 * empty.
Matt Sarett06f10872016-01-04 12:56:20 -05004740 */
Matt Sarett11466862016-02-19 13:41:30 -05004741 if (interlace_type == PNG_INTERLACE_ADAM7)
4742 {
4743 /* The row must not be written if it doesn't exist,
4744 * notice that there are two conditions here, either the
4745 * row isn't ever in the pass or the row would be but
4746 * isn't wide enough to contribute any pixels. In fact
4747 * the wPass test can be used to skip the whole y loop
4748 * in this case.
4749 */
4750 if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
4751 PNG_PASS_COLS(w, pass) > 0)
4752 interlace_row(buffer, buffer,
4753 bit_size(pp, colour_type, bit_depth), w, pass,
4754 0/*data always bigendian*/);
4755 else
4756 continue;
4757 }
4758# endif /* do_own_interlace */
Matt Sarett06f10872016-01-04 12:56:20 -05004759
Matt Sarett11466862016-02-19 13:41:30 -05004760 png_write_row(pp, buffer);
4761 }
Chris Craikb50c2172013-07-29 15:28:30 -07004762 }
Matt Sarett11466862016-02-19 13:41:30 -05004763 } /* image writing */
Chris Craikb50c2172013-07-29 15:28:30 -07004764
Matt Sarett11466862016-02-19 13:41:30 -05004765 png_write_end(pp, pi);
4766 }
Chris Craikb50c2172013-07-29 15:28:30 -07004767
4768 /* The following deletes the file that was just written. */
4769 store_write_reset(ps);
4770 }
4771
4772 Catch(fault)
4773 {
4774 store_write_reset(fault);
4775 }
4776}
4777
4778static int
Matt Sarett9b1fe632015-11-25 10:21:17 -05004779make_errors(png_modifier* const pm, png_byte const colour_type,
4780 int bdlo, int const bdhi)
Chris Craikb50c2172013-07-29 15:28:30 -07004781{
4782 for (; bdlo <= bdhi; ++bdlo)
4783 {
4784 int interlace_type;
4785
4786 for (interlace_type = PNG_INTERLACE_NONE;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304787 interlace_type < INTERLACE_LAST; ++interlace_type)
Chris Craikb50c2172013-07-29 15:28:30 -07004788 {
4789 unsigned int test;
4790 char name[FILE_NAME_SIZE];
4791
4792 standard_name(name, sizeof name, 0, colour_type, 1<<bdlo, 0,
Matt Sarett06f10872016-01-04 12:56:20 -05004793 interlace_type, 0, 0, do_own_interlace);
Chris Craikb50c2172013-07-29 15:28:30 -07004794
Matt Sarett9b1fe632015-11-25 10:21:17 -05004795 for (test=0; test<ARRAY_SIZE(error_test); ++test)
Chris Craikb50c2172013-07-29 15:28:30 -07004796 {
4797 make_error(&pm->this, colour_type, DEPTH(bdlo), interlace_type,
4798 test, name);
4799
4800 if (fail(pm))
4801 return 0;
4802 }
4803 }
4804 }
4805
4806 return 1; /* keep going */
4807}
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304808#endif /* PNG_WARNINGS_SUPPORTED */
Chris Craikb50c2172013-07-29 15:28:30 -07004809
4810static void
4811perform_error_test(png_modifier *pm)
4812{
4813#ifdef PNG_WARNINGS_SUPPORTED /* else there are no cases that work! */
4814 /* Need to do this here because we just write in this test. */
4815 safecat(pm->this.test, sizeof pm->this.test, 0, "error test");
4816
4817 if (!make_errors(pm, 0, 0, WRITE_BDHI))
4818 return;
4819
4820 if (!make_errors(pm, 2, 3, WRITE_BDHI))
4821 return;
4822
4823 if (!make_errors(pm, 3, 0, 3))
4824 return;
4825
4826 if (!make_errors(pm, 4, 3, WRITE_BDHI))
4827 return;
4828
4829 if (!make_errors(pm, 6, 3, WRITE_BDHI))
4830 return;
4831#else
4832 UNUSED(pm)
4833#endif
4834}
4835
4836/* This is just to validate the internal PNG formatting code - if this fails
4837 * then the warning messages the library outputs will probably be garbage.
4838 */
4839static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05004840perform_formatting_test(png_store *ps)
Chris Craikb50c2172013-07-29 15:28:30 -07004841{
4842#ifdef PNG_TIME_RFC1123_SUPPORTED
4843 /* The handle into the formatting code is the RFC1123 support; this test does
4844 * nothing if that is compiled out.
4845 */
4846 context(ps, fault);
4847
4848 Try
4849 {
4850 png_const_charp correct = "29 Aug 2079 13:53:60 +0000";
4851 png_const_charp result;
4852# if PNG_LIBPNG_VER >= 10600
4853 char timestring[29];
4854# endif
4855 png_structp pp;
4856 png_time pt;
4857
4858 pp = set_store_for_write(ps, NULL, "libpng formatting test");
4859
4860 if (pp == NULL)
4861 Throw ps;
4862
4863
4864 /* Arbitrary settings: */
4865 pt.year = 2079;
4866 pt.month = 8;
4867 pt.day = 29;
4868 pt.hour = 13;
4869 pt.minute = 53;
4870 pt.second = 60; /* a leap second */
4871
4872# if PNG_LIBPNG_VER < 10600
4873 result = png_convert_to_rfc1123(pp, &pt);
4874# else
4875 if (png_convert_to_rfc1123_buffer(timestring, &pt))
4876 result = timestring;
4877
4878 else
4879 result = NULL;
4880# endif
4881
4882 if (result == NULL)
4883 png_error(pp, "png_convert_to_rfc1123 failed");
4884
4885 if (strcmp(result, correct) != 0)
4886 {
4887 size_t pos = 0;
4888 char msg[128];
4889
4890 pos = safecat(msg, sizeof msg, pos, "png_convert_to_rfc1123(");
4891 pos = safecat(msg, sizeof msg, pos, correct);
4892 pos = safecat(msg, sizeof msg, pos, ") returned: '");
4893 pos = safecat(msg, sizeof msg, pos, result);
4894 pos = safecat(msg, sizeof msg, pos, "'");
4895
4896 png_error(pp, msg);
4897 }
4898
4899 store_write_reset(ps);
4900 }
4901
4902 Catch(fault)
4903 {
4904 store_write_reset(fault);
4905 }
4906#else
4907 UNUSED(ps)
4908#endif
4909}
4910
4911#ifdef PNG_READ_SUPPORTED
4912/* Because we want to use the same code in both the progressive reader and the
4913 * sequential reader it is necessary to deal with the fact that the progressive
4914 * reader callbacks only have one parameter (png_get_progressive_ptr()), so this
4915 * must contain all the test parameters and all the local variables directly
4916 * accessible to the sequential reader implementation.
4917 *
4918 * The technique adopted is to reinvent part of what Dijkstra termed a
4919 * 'display'; an array of pointers to the stack frames of enclosing functions so
4920 * that a nested function definition can access the local (C auto) variables of
4921 * the functions that contain its definition. In fact C provides the first
4922 * pointer (the local variables - the stack frame pointer) and the last (the
4923 * global variables - the BCPL global vector typically implemented as global
4924 * addresses), this code requires one more pointer to make the display - the
4925 * local variables (and function call parameters) of the function that actually
4926 * invokes either the progressive or sequential reader.
4927 *
4928 * Perhaps confusingly this technique is confounded with classes - the
4929 * 'standard_display' defined here is sub-classed as the 'gamma_display' below.
4930 * A gamma_display is a standard_display, taking advantage of the ANSI-C
4931 * requirement that the pointer to the first member of a structure must be the
4932 * same as the pointer to the structure. This allows us to reuse standard_
4933 * functions in the gamma test code; something that could not be done with
4934 * nested functions!
4935 */
4936typedef struct standard_display
4937{
4938 png_store* ps; /* Test parameters (passed to the function) */
4939 png_byte colour_type;
4940 png_byte bit_depth;
4941 png_byte red_sBIT; /* Input data sBIT values. */
4942 png_byte green_sBIT;
4943 png_byte blue_sBIT;
4944 png_byte alpha_sBIT;
Matt Sarett9b1fe632015-11-25 10:21:17 -05004945 png_byte interlace_type;
4946 png_byte filler; /* Output has a filler */
Chris Craikb50c2172013-07-29 15:28:30 -07004947 png_uint_32 id; /* Calculated file ID */
4948 png_uint_32 w; /* Width of image */
4949 png_uint_32 h; /* Height of image */
4950 int npasses; /* Number of interlaced passes */
4951 png_uint_32 pixel_size; /* Width of one pixel in bits */
4952 png_uint_32 bit_width; /* Width of output row in bits */
4953 size_t cbRow; /* Bytes in a row of the output image */
4954 int do_interlace; /* Do interlacing internally */
Matt Sarett06f10872016-01-04 12:56:20 -05004955 int littleendian; /* App (row) data is little endian */
Chris Craikb50c2172013-07-29 15:28:30 -07004956 int is_transparent; /* Transparency information was present. */
Matt Sarett9b1fe632015-11-25 10:21:17 -05004957 int has_tRNS; /* color type GRAY or RGB with a tRNS chunk. */
Chris Craikb50c2172013-07-29 15:28:30 -07004958 int speed; /* Doing a speed test */
4959 int use_update_info;/* Call update_info, not start_image */
4960 struct
4961 {
4962 png_uint_16 red;
4963 png_uint_16 green;
4964 png_uint_16 blue;
4965 } transparent; /* The transparent color, if set. */
4966 int npalette; /* Number of entries in the palette. */
4967 store_palette
4968 palette;
4969} standard_display;
4970
4971static void
4972standard_display_init(standard_display *dp, png_store* ps, png_uint_32 id,
4973 int do_interlace, int use_update_info)
4974{
4975 memset(dp, 0, sizeof *dp);
4976
4977 dp->ps = ps;
4978 dp->colour_type = COL_FROM_ID(id);
4979 dp->bit_depth = DEPTH_FROM_ID(id);
4980 if (dp->bit_depth < 1 || dp->bit_depth > 16)
4981 internal_error(ps, "internal: bad bit depth");
4982 if (dp->colour_type == 3)
4983 dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = 8;
4984 else
4985 dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT =
4986 dp->bit_depth;
4987 dp->interlace_type = INTERLACE_FROM_ID(id);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05304988 check_interlace_type(dp->interlace_type);
Chris Craikb50c2172013-07-29 15:28:30 -07004989 dp->id = id;
4990 /* All the rest are filled in after the read_info: */
4991 dp->w = 0;
4992 dp->h = 0;
4993 dp->npasses = 0;
4994 dp->pixel_size = 0;
4995 dp->bit_width = 0;
4996 dp->cbRow = 0;
4997 dp->do_interlace = do_interlace;
Matt Sarett06f10872016-01-04 12:56:20 -05004998 dp->littleendian = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07004999 dp->is_transparent = 0;
5000 dp->speed = ps->speed;
5001 dp->use_update_info = use_update_info;
5002 dp->npalette = 0;
5003 /* Preset the transparent color to black: */
5004 memset(&dp->transparent, 0, sizeof dp->transparent);
xNombred07bb0d2020-03-10 20:17:12 +01005005 /* Preset the palette to full intensity/opaque throughout: */
Chris Craikb50c2172013-07-29 15:28:30 -07005006 memset(dp->palette, 0xff, sizeof dp->palette);
5007}
5008
5009/* Initialize the palette fields - this must be done later because the palette
5010 * comes from the particular png_store_file that is selected.
5011 */
5012static void
5013standard_palette_init(standard_display *dp)
5014{
5015 store_palette_entry *palette = store_current_palette(dp->ps, &dp->npalette);
5016
5017 /* The remaining entries remain white/opaque. */
5018 if (dp->npalette > 0)
5019 {
5020 int i = dp->npalette;
5021 memcpy(dp->palette, palette, i * sizeof *palette);
5022
5023 /* Check for a non-opaque palette entry: */
5024 while (--i >= 0)
5025 if (palette[i].alpha < 255)
5026 break;
5027
5028# ifdef __GNUC__
5029 /* GCC can't handle the more obviously optimizable version. */
5030 if (i >= 0)
5031 dp->is_transparent = 1;
5032 else
5033 dp->is_transparent = 0;
5034# else
5035 dp->is_transparent = (i >= 0);
5036# endif
5037 }
5038}
5039
5040/* Utility to read the palette from the PNG file and convert it into
5041 * store_palette format. This returns 1 if there is any transparency in the
5042 * palette (it does not check for a transparent colour in the non-palette case.)
5043 */
5044static int
5045read_palette(store_palette palette, int *npalette, png_const_structp pp,
5046 png_infop pi)
5047{
5048 png_colorp pal;
5049 png_bytep trans_alpha;
5050 int num;
5051
5052 pal = 0;
5053 *npalette = -1;
5054
5055 if (png_get_PLTE(pp, pi, &pal, npalette) & PNG_INFO_PLTE)
5056 {
5057 int i = *npalette;
5058
5059 if (i <= 0 || i > 256)
5060 png_error(pp, "validate: invalid PLTE count");
5061
5062 while (--i >= 0)
5063 {
5064 palette[i].red = pal[i].red;
5065 palette[i].green = pal[i].green;
5066 palette[i].blue = pal[i].blue;
5067 }
5068
5069 /* Mark the remainder of the entries with a flag value (other than
5070 * white/opaque which is the flag value stored above.)
5071 */
5072 memset(palette + *npalette, 126, (256-*npalette) * sizeof *palette);
5073 }
5074
5075 else /* !png_get_PLTE */
5076 {
5077 if (*npalette != (-1))
5078 png_error(pp, "validate: invalid PLTE result");
5079 /* But there is no palette, so record this: */
5080 *npalette = 0;
5081 memset(palette, 113, sizeof (store_palette));
5082 }
5083
5084 trans_alpha = 0;
5085 num = 2; /* force error below */
5086 if ((png_get_tRNS(pp, pi, &trans_alpha, &num, 0) & PNG_INFO_tRNS) != 0 &&
5087 (trans_alpha != NULL || num != 1/*returns 1 for a transparent color*/) &&
5088 /* Oops, if a palette tRNS gets expanded png_read_update_info (at least so
5089 * far as 1.5.4) does not remove the trans_alpha pointer, only num_trans,
5090 * so in the above call we get a success, we get a pointer (who knows what
5091 * to) and we get num_trans == 0:
5092 */
5093 !(trans_alpha != NULL && num == 0)) /* TODO: fix this in libpng. */
5094 {
5095 int i;
5096
5097 /* Any of these are crash-worthy - given the implementation of
5098 * png_get_tRNS up to 1.5 an app won't crash if it just checks the
5099 * result above and fails to check that the variables it passed have
5100 * actually been filled in! Note that if the app were to pass the
5101 * last, png_color_16p, variable too it couldn't rely on this.
5102 */
5103 if (trans_alpha == NULL || num <= 0 || num > 256 || num > *npalette)
5104 png_error(pp, "validate: unexpected png_get_tRNS (palette) result");
5105
5106 for (i=0; i<num; ++i)
5107 palette[i].alpha = trans_alpha[i];
5108
5109 for (num=*npalette; i<num; ++i)
5110 palette[i].alpha = 255;
5111
5112 for (; i<256; ++i)
5113 palette[i].alpha = 33; /* flag value */
5114
5115 return 1; /* transparency */
5116 }
5117
5118 else
5119 {
5120 /* No palette transparency - just set the alpha channel to opaque. */
5121 int i;
5122
5123 for (i=0, num=*npalette; i<num; ++i)
5124 palette[i].alpha = 255;
5125
5126 for (; i<256; ++i)
5127 palette[i].alpha = 55; /* flag value */
5128
5129 return 0; /* no transparency */
5130 }
5131}
5132
5133/* Utility to validate the palette if it should not have changed (the
5134 * non-transform case).
5135 */
5136static void
5137standard_palette_validate(standard_display *dp, png_const_structp pp,
5138 png_infop pi)
5139{
5140 int npalette;
5141 store_palette palette;
5142
5143 if (read_palette(palette, &npalette, pp, pi) != dp->is_transparent)
5144 png_error(pp, "validate: palette transparency changed");
5145
5146 if (npalette != dp->npalette)
5147 {
5148 size_t pos = 0;
5149 char msg[64];
5150
5151 pos = safecat(msg, sizeof msg, pos, "validate: palette size changed: ");
5152 pos = safecatn(msg, sizeof msg, pos, dp->npalette);
5153 pos = safecat(msg, sizeof msg, pos, " -> ");
5154 pos = safecatn(msg, sizeof msg, pos, npalette);
5155 png_error(pp, msg);
5156 }
5157
5158 {
5159 int i = npalette; /* npalette is aliased */
5160
5161 while (--i >= 0)
5162 if (palette[i].red != dp->palette[i].red ||
5163 palette[i].green != dp->palette[i].green ||
5164 palette[i].blue != dp->palette[i].blue ||
5165 palette[i].alpha != dp->palette[i].alpha)
5166 png_error(pp, "validate: PLTE or tRNS chunk changed");
5167 }
5168}
5169
5170/* By passing a 'standard_display' the progressive callbacks can be used
5171 * directly by the sequential code, the functions suffixed "_imp" are the
5172 * implementations, the functions without the suffix are the callbacks.
5173 *
5174 * The code for the info callback is split into two because this callback calls
5175 * png_read_update_info or png_start_read_image and what gets called depends on
5176 * whether the info needs updating (we want to test both calls in pngvalid.)
5177 */
5178static void
5179standard_info_part1(standard_display *dp, png_structp pp, png_infop pi)
5180{
5181 if (png_get_bit_depth(pp, pi) != dp->bit_depth)
5182 png_error(pp, "validate: bit depth changed");
5183
5184 if (png_get_color_type(pp, pi) != dp->colour_type)
5185 png_error(pp, "validate: color type changed");
5186
5187 if (png_get_filter_type(pp, pi) != PNG_FILTER_TYPE_BASE)
5188 png_error(pp, "validate: filter type changed");
5189
5190 if (png_get_interlace_type(pp, pi) != dp->interlace_type)
5191 png_error(pp, "validate: interlacing changed");
5192
5193 if (png_get_compression_type(pp, pi) != PNG_COMPRESSION_TYPE_BASE)
5194 png_error(pp, "validate: compression type changed");
5195
5196 dp->w = png_get_image_width(pp, pi);
5197
5198 if (dp->w != standard_width(pp, dp->id))
5199 png_error(pp, "validate: image width changed");
5200
5201 dp->h = png_get_image_height(pp, pi);
5202
5203 if (dp->h != standard_height(pp, dp->id))
5204 png_error(pp, "validate: image height changed");
5205
5206 /* Record (but don't check at present) the input sBIT according to the colour
5207 * type information.
5208 */
5209 {
5210 png_color_8p sBIT = 0;
5211
5212 if (png_get_sBIT(pp, pi, &sBIT) & PNG_INFO_sBIT)
5213 {
5214 int sBIT_invalid = 0;
5215
5216 if (sBIT == 0)
5217 png_error(pp, "validate: unexpected png_get_sBIT result");
5218
5219 if (dp->colour_type & PNG_COLOR_MASK_COLOR)
5220 {
5221 if (sBIT->red == 0 || sBIT->red > dp->bit_depth)
5222 sBIT_invalid = 1;
5223 else
5224 dp->red_sBIT = sBIT->red;
5225
5226 if (sBIT->green == 0 || sBIT->green > dp->bit_depth)
5227 sBIT_invalid = 1;
5228 else
5229 dp->green_sBIT = sBIT->green;
5230
5231 if (sBIT->blue == 0 || sBIT->blue > dp->bit_depth)
5232 sBIT_invalid = 1;
5233 else
5234 dp->blue_sBIT = sBIT->blue;
5235 }
5236
5237 else /* !COLOR */
5238 {
5239 if (sBIT->gray == 0 || sBIT->gray > dp->bit_depth)
5240 sBIT_invalid = 1;
5241 else
5242 dp->blue_sBIT = dp->green_sBIT = dp->red_sBIT = sBIT->gray;
5243 }
5244
5245 /* All 8 bits in tRNS for a palette image are significant - see the
5246 * spec.
5247 */
5248 if (dp->colour_type & PNG_COLOR_MASK_ALPHA)
5249 {
5250 if (sBIT->alpha == 0 || sBIT->alpha > dp->bit_depth)
5251 sBIT_invalid = 1;
5252 else
5253 dp->alpha_sBIT = sBIT->alpha;
5254 }
5255
5256 if (sBIT_invalid)
5257 png_error(pp, "validate: sBIT value out of range");
5258 }
5259 }
5260
5261 /* Important: this is validating the value *before* any transforms have been
5262 * put in place. It doesn't matter for the standard tests, where there are
5263 * no transforms, but it does for other tests where rowbytes may change after
5264 * png_read_update_info.
5265 */
5266 if (png_get_rowbytes(pp, pi) != standard_rowsize(pp, dp->id))
5267 png_error(pp, "validate: row size changed");
5268
5269 /* Validate the colour type 3 palette (this can be present on other color
5270 * types.)
5271 */
5272 standard_palette_validate(dp, pp, pi);
5273
xNombred07bb0d2020-03-10 20:17:12 +01005274 /* In any case always check for a transparent color (notice that the
Chris Craikb50c2172013-07-29 15:28:30 -07005275 * colour type 3 case must not give a successful return on the get_tRNS call
5276 * with these arguments!)
5277 */
5278 {
5279 png_color_16p trans_color = 0;
5280
5281 if (png_get_tRNS(pp, pi, 0, 0, &trans_color) & PNG_INFO_tRNS)
5282 {
5283 if (trans_color == 0)
5284 png_error(pp, "validate: unexpected png_get_tRNS (color) result");
5285
5286 switch (dp->colour_type)
5287 {
5288 case 0:
5289 dp->transparent.red = dp->transparent.green = dp->transparent.blue =
5290 trans_color->gray;
Matt Sarett9b1fe632015-11-25 10:21:17 -05005291 dp->has_tRNS = 1;
Chris Craikb50c2172013-07-29 15:28:30 -07005292 break;
5293
5294 case 2:
5295 dp->transparent.red = trans_color->red;
5296 dp->transparent.green = trans_color->green;
5297 dp->transparent.blue = trans_color->blue;
Matt Sarett9b1fe632015-11-25 10:21:17 -05005298 dp->has_tRNS = 1;
Chris Craikb50c2172013-07-29 15:28:30 -07005299 break;
5300
5301 case 3:
5302 /* Not expected because it should result in the array case
5303 * above.
5304 */
5305 png_error(pp, "validate: unexpected png_get_tRNS result");
5306 break;
5307
5308 default:
5309 png_error(pp, "validate: invalid tRNS chunk with alpha image");
5310 }
5311 }
5312 }
5313
5314 /* Read the number of passes - expected to match the value used when
5315 * creating the image (interlaced or not). This has the side effect of
5316 * turning on interlace handling (if do_interlace is not set.)
5317 */
5318 dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type);
Matt Sarett06f10872016-01-04 12:56:20 -05005319 if (!dp->do_interlace)
5320 {
5321# ifdef PNG_READ_INTERLACING_SUPPORTED
5322 if (dp->npasses != png_set_interlace_handling(pp))
5323 png_error(pp, "validate: file changed interlace type");
5324# else /* !READ_INTERLACING */
5325 /* This should never happen: the relevant tests (!do_interlace) should
5326 * not be run.
5327 */
5328 if (dp->npasses > 1)
5329 png_error(pp, "validate: no libpng interlace support");
5330# endif /* !READ_INTERLACING */
5331 }
Chris Craikb50c2172013-07-29 15:28:30 -07005332
5333 /* Caller calls png_read_update_info or png_start_read_image now, then calls
5334 * part2.
5335 */
5336}
5337
5338/* This must be called *after* the png_read_update_info call to get the correct
5339 * 'rowbytes' value, otherwise png_get_rowbytes will refer to the untransformed
5340 * image.
5341 */
5342static void
5343standard_info_part2(standard_display *dp, png_const_structp pp,
5344 png_const_infop pi, int nImages)
5345{
5346 /* Record cbRow now that it can be found. */
Matt Sarett9b1fe632015-11-25 10:21:17 -05005347 {
5348 png_byte ct = png_get_color_type(pp, pi);
5349 png_byte bd = png_get_bit_depth(pp, pi);
5350
5351 if (bd >= 8 && (ct == PNG_COLOR_TYPE_RGB || ct == PNG_COLOR_TYPE_GRAY) &&
5352 dp->filler)
5353 ct |= 4; /* handle filler as faked alpha channel */
5354
5355 dp->pixel_size = bit_size(pp, ct, bd);
5356 }
Chris Craikb50c2172013-07-29 15:28:30 -07005357 dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
5358 dp->cbRow = png_get_rowbytes(pp, pi);
5359
5360 /* Validate the rowbytes here again. */
5361 if (dp->cbRow != (dp->bit_width+7)/8)
5362 png_error(pp, "bad png_get_rowbytes calculation");
5363
5364 /* Then ensure there is enough space for the output image(s). */
5365 store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
5366}
5367
5368static void
5369standard_info_imp(standard_display *dp, png_structp pp, png_infop pi,
5370 int nImages)
5371{
5372 /* Note that the validation routine has the side effect of turning on
5373 * interlace handling in the subsequent code.
5374 */
5375 standard_info_part1(dp, pp, pi);
5376
5377 /* And the info callback has to call this (or png_read_update_info - see
5378 * below in the png_modifier code for that variant.
5379 */
5380 if (dp->use_update_info)
5381 {
5382 /* For debugging the effect of multiple calls: */
5383 int i = dp->use_update_info;
5384 while (i-- > 0)
5385 png_read_update_info(pp, pi);
5386 }
5387
5388 else
5389 png_start_read_image(pp);
5390
5391 /* Validate the height, width and rowbytes plus ensure that sufficient buffer
5392 * exists for decoding the image.
5393 */
5394 standard_info_part2(dp, pp, pi, nImages);
5395}
5396
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305397static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07005398standard_info(png_structp pp, png_infop pi)
5399{
5400 standard_display *dp = voidcast(standard_display*,
5401 png_get_progressive_ptr(pp));
5402
5403 /* Call with nImages==1 because the progressive reader can only produce one
5404 * image.
5405 */
5406 standard_info_imp(dp, pp, pi, 1 /*only one image*/);
5407}
5408
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305409static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07005410progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass)
5411{
5412 png_const_structp pp = ppIn;
Matt Sarett9b1fe632015-11-25 10:21:17 -05005413 const standard_display *dp = voidcast(standard_display*,
Chris Craikb50c2172013-07-29 15:28:30 -07005414 png_get_progressive_ptr(pp));
5415
5416 /* When handling interlacing some rows will be absent in each pass, the
5417 * callback still gets called, but with a NULL pointer. This is checked
5418 * in the 'else' clause below. We need our own 'cbRow', but we can't call
5419 * png_get_rowbytes because we got no info structure.
5420 */
5421 if (new_row != NULL)
5422 {
5423 png_bytep row;
5424
5425 /* In the case where the reader doesn't do the interlace it gives
5426 * us the y in the sub-image:
5427 */
5428 if (dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7)
5429 {
5430#ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED
5431 /* Use this opportunity to validate the png 'current' APIs: */
5432 if (y != png_get_current_row_number(pp))
5433 png_error(pp, "png_get_current_row_number is broken");
5434
5435 if (pass != png_get_current_pass_number(pp))
5436 png_error(pp, "png_get_current_pass_number is broken");
Matt Sarett06f10872016-01-04 12:56:20 -05005437#endif /* USER_TRANSFORM_INFO */
Chris Craikb50c2172013-07-29 15:28:30 -07005438
5439 y = PNG_ROW_FROM_PASS_ROW(y, pass);
5440 }
5441
5442 /* Validate this just in case. */
5443 if (y >= dp->h)
5444 png_error(pp, "invalid y to progressive row callback");
5445
5446 row = store_image_row(dp->ps, pp, 0, y);
5447
Chris Craikb50c2172013-07-29 15:28:30 -07005448 /* Combine the new row into the old: */
Matt Sarett06f10872016-01-04 12:56:20 -05005449#ifdef PNG_READ_INTERLACING_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07005450 if (dp->do_interlace)
Matt Sarett06f10872016-01-04 12:56:20 -05005451#endif /* READ_INTERLACING */
Chris Craikb50c2172013-07-29 15:28:30 -07005452 {
5453 if (dp->interlace_type == PNG_INTERLACE_ADAM7)
Matt Sarett06f10872016-01-04 12:56:20 -05005454 deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass,
5455 dp->littleendian);
Chris Craikb50c2172013-07-29 15:28:30 -07005456 else
Matt Sarett06f10872016-01-04 12:56:20 -05005457 row_copy(row, new_row, dp->pixel_size * dp->w, dp->littleendian);
Chris Craikb50c2172013-07-29 15:28:30 -07005458 }
Matt Sarett06f10872016-01-04 12:56:20 -05005459#ifdef PNG_READ_INTERLACING_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07005460 else
5461 png_progressive_combine_row(pp, row, new_row);
Matt Sarett06f10872016-01-04 12:56:20 -05005462#endif /* PNG_READ_INTERLACING_SUPPORTED */
Chris Craikb50c2172013-07-29 15:28:30 -07005463 }
5464
Chris Craikb50c2172013-07-29 15:28:30 -07005465 else if (dp->interlace_type == PNG_INTERLACE_ADAM7 &&
5466 PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
5467 PNG_PASS_COLS(dp->w, pass) > 0)
5468 png_error(pp, "missing row in progressive de-interlacing");
Chris Craikb50c2172013-07-29 15:28:30 -07005469}
5470
5471static void
5472sequential_row(standard_display *dp, png_structp pp, png_infop pi,
xNombred07bb0d2020-03-10 20:17:12 +01005473 int iImage, int iDisplay)
Chris Craikb50c2172013-07-29 15:28:30 -07005474{
xNombred07bb0d2020-03-10 20:17:12 +01005475 int npasses = dp->npasses;
5476 int do_interlace = dp->do_interlace &&
Chris Craikb50c2172013-07-29 15:28:30 -07005477 dp->interlace_type == PNG_INTERLACE_ADAM7;
xNombred07bb0d2020-03-10 20:17:12 +01005478 png_uint_32 height = standard_height(pp, dp->id);
5479 png_uint_32 width = standard_width(pp, dp->id);
5480 const png_store* ps = dp->ps;
Chris Craikb50c2172013-07-29 15:28:30 -07005481 int pass;
5482
5483 for (pass=0; pass<npasses; ++pass)
5484 {
5485 png_uint_32 y;
5486 png_uint_32 wPass = PNG_PASS_COLS(width, pass);
5487
5488 for (y=0; y<height; ++y)
5489 {
5490 if (do_interlace)
5491 {
5492 /* wPass may be zero or this row may not be in this pass.
5493 * png_read_row must not be called in either case.
5494 */
5495 if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass))
5496 {
5497 /* Read the row into a pair of temporary buffers, then do the
5498 * merge here into the output rows.
5499 */
5500 png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX];
5501
5502 /* The following aids (to some extent) error detection - we can
5503 * see where png_read_row wrote. Use opposite values in row and
5504 * display to make this easier. Don't use 0xff (which is used in
5505 * the image write code to fill unused bits) or 0 (which is a
5506 * likely value to overwrite unused bits with).
5507 */
5508 memset(row, 0xc5, sizeof row);
5509 memset(display, 0x5c, sizeof display);
5510
5511 png_read_row(pp, row, display);
5512
5513 if (iImage >= 0)
5514 deinterlace_row(store_image_row(ps, pp, iImage, y), row,
Matt Sarett06f10872016-01-04 12:56:20 -05005515 dp->pixel_size, dp->w, pass, dp->littleendian);
Chris Craikb50c2172013-07-29 15:28:30 -07005516
5517 if (iDisplay >= 0)
5518 deinterlace_row(store_image_row(ps, pp, iDisplay, y), display,
Matt Sarett06f10872016-01-04 12:56:20 -05005519 dp->pixel_size, dp->w, pass, dp->littleendian);
Chris Craikb50c2172013-07-29 15:28:30 -07005520 }
5521 }
5522 else
5523 png_read_row(pp,
5524 iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL,
5525 iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL);
5526 }
5527 }
5528
5529 /* And finish the read operation (only really necessary if the caller wants
5530 * to find additional data in png_info from chunks after the last IDAT.)
5531 */
5532 png_read_end(pp, pi);
5533}
5534
5535#ifdef PNG_TEXT_SUPPORTED
5536static void
5537standard_check_text(png_const_structp pp, png_const_textp tp,
5538 png_const_charp keyword, png_const_charp text)
5539{
5540 char msg[1024];
5541 size_t pos = safecat(msg, sizeof msg, 0, "text: ");
5542 size_t ok;
5543
5544 pos = safecat(msg, sizeof msg, pos, keyword);
5545 pos = safecat(msg, sizeof msg, pos, ": ");
5546 ok = pos;
5547
5548 if (tp->compression != TEXT_COMPRESSION)
5549 {
5550 char buf[64];
5551
5552 sprintf(buf, "compression [%d->%d], ", TEXT_COMPRESSION,
5553 tp->compression);
5554 pos = safecat(msg, sizeof msg, pos, buf);
5555 }
5556
5557 if (tp->key == NULL || strcmp(tp->key, keyword) != 0)
5558 {
5559 pos = safecat(msg, sizeof msg, pos, "keyword \"");
5560 if (tp->key != NULL)
5561 {
5562 pos = safecat(msg, sizeof msg, pos, tp->key);
5563 pos = safecat(msg, sizeof msg, pos, "\", ");
5564 }
5565
5566 else
5567 pos = safecat(msg, sizeof msg, pos, "null, ");
5568 }
5569
5570 if (tp->text == NULL)
5571 pos = safecat(msg, sizeof msg, pos, "text lost, ");
5572
5573 else
5574 {
5575 if (tp->text_length != strlen(text))
5576 {
5577 char buf[64];
5578 sprintf(buf, "text length changed[%lu->%lu], ",
5579 (unsigned long)strlen(text), (unsigned long)tp->text_length);
5580 pos = safecat(msg, sizeof msg, pos, buf);
5581 }
5582
5583 if (strcmp(tp->text, text) != 0)
5584 {
5585 pos = safecat(msg, sizeof msg, pos, "text becomes \"");
5586 pos = safecat(msg, sizeof msg, pos, tp->text);
5587 pos = safecat(msg, sizeof msg, pos, "\" (was \"");
5588 pos = safecat(msg, sizeof msg, pos, text);
5589 pos = safecat(msg, sizeof msg, pos, "\"), ");
5590 }
5591 }
5592
5593 if (tp->itxt_length != 0)
5594 pos = safecat(msg, sizeof msg, pos, "iTXt length set, ");
5595
5596 if (tp->lang != NULL)
5597 {
5598 pos = safecat(msg, sizeof msg, pos, "iTXt language \"");
5599 pos = safecat(msg, sizeof msg, pos, tp->lang);
5600 pos = safecat(msg, sizeof msg, pos, "\", ");
5601 }
5602
5603 if (tp->lang_key != NULL)
5604 {
5605 pos = safecat(msg, sizeof msg, pos, "iTXt keyword \"");
5606 pos = safecat(msg, sizeof msg, pos, tp->lang_key);
5607 pos = safecat(msg, sizeof msg, pos, "\", ");
5608 }
5609
5610 if (pos > ok)
5611 {
5612 msg[pos-2] = '\0'; /* Remove the ", " at the end */
5613 png_error(pp, msg);
5614 }
5615}
5616
5617static void
5618standard_text_validate(standard_display *dp, png_const_structp pp,
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305619 png_infop pi, int check_end)
Chris Craikb50c2172013-07-29 15:28:30 -07005620{
5621 png_textp tp = NULL;
5622 png_uint_32 num_text = png_get_text(pp, pi, &tp, NULL);
5623
5624 if (num_text == 2 && tp != NULL)
5625 {
5626 standard_check_text(pp, tp, "image name", dp->ps->current->name);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305627
5628 /* This exists because prior to 1.5.18 the progressive reader left the
5629 * png_struct z_stream unreset at the end of the image, so subsequent
5630 * attempts to use it simply returns Z_STREAM_END.
5631 */
5632 if (check_end)
5633 standard_check_text(pp, tp+1, "end marker", "end");
Chris Craikb50c2172013-07-29 15:28:30 -07005634 }
5635
5636 else
5637 {
5638 char msg[64];
5639
5640 sprintf(msg, "expected two text items, got %lu",
5641 (unsigned long)num_text);
5642 png_error(pp, msg);
5643 }
5644}
5645#else
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305646# define standard_text_validate(dp,pp,pi,check_end) ((void)0)
Chris Craikb50c2172013-07-29 15:28:30 -07005647#endif
5648
5649static void
5650standard_row_validate(standard_display *dp, png_const_structp pp,
5651 int iImage, int iDisplay, png_uint_32 y)
5652{
5653 int where;
5654 png_byte std[STANDARD_ROWMAX];
5655
5656 /* The row must be pre-initialized to the magic number here for the size
5657 * tests to pass:
5658 */
5659 memset(std, 178, sizeof std);
5660 standard_row(pp, std, dp->id, y);
5661
5662 /* At the end both the 'row' and 'display' arrays should end up identical.
5663 * In earlier passes 'row' will be partially filled in, with only the pixels
5664 * that have been read so far, but 'display' will have those pixels
5665 * replicated to fill the unread pixels while reading an interlaced image.
Chris Craikb50c2172013-07-29 15:28:30 -07005666 */
5667 if (iImage >= 0 &&
5668 (where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y),
5669 dp->bit_width)) != 0)
5670 {
5671 char msg[64];
5672 sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x",
5673 (unsigned long)y, where-1, std[where-1],
5674 store_image_row(dp->ps, pp, iImage, y)[where-1]);
5675 png_error(pp, msg);
5676 }
5677
Chris Craikb50c2172013-07-29 15:28:30 -07005678 if (iDisplay >= 0 &&
5679 (where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y),
5680 dp->bit_width)) != 0)
5681 {
5682 char msg[64];
Matt Sarett06f10872016-01-04 12:56:20 -05005683 sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x",
Chris Craikb50c2172013-07-29 15:28:30 -07005684 (unsigned long)y, where-1, std[where-1],
5685 store_image_row(dp->ps, pp, iDisplay, y)[where-1]);
5686 png_error(pp, msg);
5687 }
5688}
5689
5690static void
5691standard_image_validate(standard_display *dp, png_const_structp pp, int iImage,
5692 int iDisplay)
5693{
5694 png_uint_32 y;
5695
5696 if (iImage >= 0)
5697 store_image_check(dp->ps, pp, iImage);
5698
5699 if (iDisplay >= 0)
5700 store_image_check(dp->ps, pp, iDisplay);
5701
5702 for (y=0; y<dp->h; ++y)
5703 standard_row_validate(dp, pp, iImage, iDisplay, y);
5704
5705 /* This avoids false positives if the validation code is never called! */
5706 dp->ps->validated = 1;
5707}
5708
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305709static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07005710standard_end(png_structp ppIn, png_infop pi)
5711{
5712 png_const_structp pp = ppIn;
5713 standard_display *dp = voidcast(standard_display*,
5714 png_get_progressive_ptr(pp));
5715
5716 UNUSED(pi)
5717
5718 /* Validate the image - progressive reading only produces one variant for
5719 * interlaced images.
5720 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305721 standard_text_validate(dp, pp, pi,
5722 PNG_LIBPNG_VER >= 10518/*check_end: see comments above*/);
Chris Craikb50c2172013-07-29 15:28:30 -07005723 standard_image_validate(dp, pp, 0, -1);
5724}
5725
5726/* A single test run checking the standard image to ensure it is not damaged. */
5727static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05005728standard_test(png_store* const psIn, png_uint_32 const id,
Chris Craikb50c2172013-07-29 15:28:30 -07005729 int do_interlace, int use_update_info)
5730{
5731 standard_display d;
5732 context(psIn, fault);
5733
5734 /* Set up the display (stack frame) variables from the arguments to the
5735 * function and initialize the locals that are filled in later.
5736 */
5737 standard_display_init(&d, psIn, id, do_interlace, use_update_info);
5738
5739 /* Everything is protected by a Try/Catch. The functions called also
5740 * typically have local Try/Catch blocks.
5741 */
5742 Try
5743 {
5744 png_structp pp;
5745 png_infop pi;
5746
5747 /* Get a png_struct for reading the image. This will throw an error if it
5748 * fails, so we don't need to check the result.
5749 */
5750 pp = set_store_for_read(d.ps, &pi, d.id,
5751 d.do_interlace ? (d.ps->progressive ?
5752 "pngvalid progressive deinterlacer" :
5753 "pngvalid sequential deinterlacer") : (d.ps->progressive ?
5754 "progressive reader" : "sequential reader"));
5755
5756 /* Initialize the palette correctly from the png_store_file. */
5757 standard_palette_init(&d);
5758
5759 /* Introduce the correct read function. */
5760 if (d.ps->progressive)
5761 {
5762 png_set_progressive_read_fn(pp, &d, standard_info, progressive_row,
5763 standard_end);
5764
5765 /* Now feed data into the reader until we reach the end: */
5766 store_progressive_read(d.ps, pp, pi);
5767 }
5768 else
5769 {
5770 /* Note that this takes the store, not the display. */
5771 png_set_read_fn(pp, d.ps, store_read);
5772
5773 /* Check the header values: */
5774 png_read_info(pp, pi);
5775
5776 /* The code tests both versions of the images that the sequential
5777 * reader can produce.
5778 */
5779 standard_info_imp(&d, pp, pi, 2 /*images*/);
5780
5781 /* Need the total bytes in the image below; we can't get to this point
5782 * unless the PNG file values have been checked against the expected
5783 * values.
5784 */
5785 {
5786 sequential_row(&d, pp, pi, 0, 1);
5787
5788 /* After the last pass loop over the rows again to check that the
5789 * image is correct.
5790 */
5791 if (!d.speed)
5792 {
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305793 standard_text_validate(&d, pp, pi, 1/*check_end*/);
Chris Craikb50c2172013-07-29 15:28:30 -07005794 standard_image_validate(&d, pp, 0, 1);
5795 }
5796 else
5797 d.ps->validated = 1;
5798 }
5799 }
5800
5801 /* Check for validation. */
5802 if (!d.ps->validated)
5803 png_error(pp, "image read failed silently");
5804
5805 /* Successful completion. */
5806 }
5807
5808 Catch(fault)
5809 d.ps = fault; /* make sure this hasn't been clobbered. */
5810
5811 /* In either case clean up the store. */
5812 store_read_reset(d.ps);
5813}
5814
5815static int
Matt Sarett9b1fe632015-11-25 10:21:17 -05005816test_standard(png_modifier* const pm, png_byte const colour_type,
5817 int bdlo, int const bdhi)
Chris Craikb50c2172013-07-29 15:28:30 -07005818{
5819 for (; bdlo <= bdhi; ++bdlo)
5820 {
5821 int interlace_type;
5822
5823 for (interlace_type = PNG_INTERLACE_NONE;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305824 interlace_type < INTERLACE_LAST; ++interlace_type)
Chris Craikb50c2172013-07-29 15:28:30 -07005825 {
5826 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
Matt Sarett06f10872016-01-04 12:56:20 -05005827 interlace_type, 0, 0, 0), do_read_interlace, pm->use_update_info);
Chris Craikb50c2172013-07-29 15:28:30 -07005828
5829 if (fail(pm))
5830 return 0;
5831 }
5832 }
5833
5834 return 1; /* keep going */
5835}
5836
5837static void
5838perform_standard_test(png_modifier *pm)
5839{
5840 /* Test each colour type over the valid range of bit depths (expressed as
5841 * log2(bit_depth) in turn, stop as soon as any error is detected.
5842 */
5843 if (!test_standard(pm, 0, 0, READ_BDHI))
5844 return;
5845
5846 if (!test_standard(pm, 2, 3, READ_BDHI))
5847 return;
5848
5849 if (!test_standard(pm, 3, 0, 3))
5850 return;
5851
5852 if (!test_standard(pm, 4, 3, READ_BDHI))
5853 return;
5854
5855 if (!test_standard(pm, 6, 3, READ_BDHI))
5856 return;
5857}
5858
5859
5860/********************************** SIZE TESTS ********************************/
5861static int
Matt Sarett9b1fe632015-11-25 10:21:17 -05005862test_size(png_modifier* const pm, png_byte const colour_type,
5863 int bdlo, int const bdhi)
Chris Craikb50c2172013-07-29 15:28:30 -07005864{
5865 /* Run the tests on each combination.
5866 *
5867 * NOTE: on my 32 bit x86 each of the following blocks takes
5868 * a total of 3.5 seconds if done across every combo of bit depth
5869 * width and height. This is a waste of time in practice, hence the
5870 * hinc and winc stuff:
5871 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05005872 static const png_byte hinc[] = {1, 3, 11, 1, 5};
5873 static const png_byte winc[] = {1, 9, 5, 7, 1};
xNombred07bb0d2020-03-10 20:17:12 +01005874 int save_bdlo = bdlo;
Matt Sarett9b1fe632015-11-25 10:21:17 -05005875
Chris Craikb50c2172013-07-29 15:28:30 -07005876 for (; bdlo <= bdhi; ++bdlo)
5877 {
5878 png_uint_32 h, w;
5879
5880 for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo])
5881 {
5882 /* First test all the 'size' images against the sequential
5883 * reader using libpng to deinterlace (where required.) This
5884 * validates the write side of libpng. There are four possibilities
5885 * to validate.
5886 */
5887 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5888 PNG_INTERLACE_NONE, w, h, 0), 0/*do_interlace*/,
5889 pm->use_update_info);
5890
5891 if (fail(pm))
5892 return 0;
5893
5894 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5895 PNG_INTERLACE_NONE, w, h, 1), 0/*do_interlace*/,
5896 pm->use_update_info);
5897
5898 if (fail(pm))
5899 return 0;
5900
Chris Craikb50c2172013-07-29 15:28:30 -07005901 /* Now validate the interlaced read side - do_interlace true,
5902 * in the progressive case this does actually make a difference
5903 * to the code used in the non-interlaced case too.
5904 */
5905 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5906 PNG_INTERLACE_NONE, w, h, 0), 1/*do_interlace*/,
5907 pm->use_update_info);
5908
5909 if (fail(pm))
5910 return 0;
5911
Matt Sarett9b1fe632015-11-25 10:21:17 -05005912# if CAN_WRITE_INTERLACE
5913 /* Validate the pngvalid code itself: */
5914 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5915 PNG_INTERLACE_ADAM7, w, h, 1), 1/*do_interlace*/,
5916 pm->use_update_info);
5917
5918 if (fail(pm))
5919 return 0;
5920# endif
5921 }
5922 }
5923
5924 /* Now do the tests of libpng interlace handling, after we have made sure
5925 * that the pngvalid version works:
5926 */
5927 for (bdlo = save_bdlo; bdlo <= bdhi; ++bdlo)
5928 {
5929 png_uint_32 h, w;
5930
5931 for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo])
5932 {
Matt Sarett06f10872016-01-04 12:56:20 -05005933# ifdef PNG_READ_INTERLACING_SUPPORTED
Matt Sarett9b1fe632015-11-25 10:21:17 -05005934 /* Test with pngvalid generated interlaced images first; we have
5935 * already verify these are ok (unless pngvalid has self-consistent
5936 * read/write errors, which is unlikely), so this detects errors in the
5937 * read side first:
5938 */
5939# if CAN_WRITE_INTERLACE
5940 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5941 PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/,
5942 pm->use_update_info);
5943
5944 if (fail(pm))
5945 return 0;
5946# endif
Matt Sarett06f10872016-01-04 12:56:20 -05005947# endif /* READ_INTERLACING */
Matt Sarett9b1fe632015-11-25 10:21:17 -05005948
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305949# ifdef PNG_WRITE_INTERLACING_SUPPORTED
Matt Sarett9b1fe632015-11-25 10:21:17 -05005950 /* Test the libpng write side against the pngvalid read side: */
Chris Craikb50c2172013-07-29 15:28:30 -07005951 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5952 PNG_INTERLACE_ADAM7, w, h, 0), 1/*do_interlace*/,
5953 pm->use_update_info);
5954
5955 if (fail(pm))
5956 return 0;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05305957# endif
Matt Sarett9b1fe632015-11-25 10:21:17 -05005958
Matt Sarett06f10872016-01-04 12:56:20 -05005959# ifdef PNG_READ_INTERLACING_SUPPORTED
Matt Sarett9b1fe632015-11-25 10:21:17 -05005960# ifdef PNG_WRITE_INTERLACING_SUPPORTED
5961 /* Test both together: */
5962 standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
5963 PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/,
5964 pm->use_update_info);
5965
5966 if (fail(pm))
5967 return 0;
5968# endif
Matt Sarett06f10872016-01-04 12:56:20 -05005969# endif /* READ_INTERLACING */
Chris Craikb50c2172013-07-29 15:28:30 -07005970 }
5971 }
5972
5973 return 1; /* keep going */
5974}
5975
5976static void
5977perform_size_test(png_modifier *pm)
5978{
5979 /* Test each colour type over the valid range of bit depths (expressed as
5980 * log2(bit_depth) in turn, stop as soon as any error is detected.
5981 */
5982 if (!test_size(pm, 0, 0, READ_BDHI))
5983 return;
5984
5985 if (!test_size(pm, 2, 3, READ_BDHI))
5986 return;
5987
5988 /* For the moment don't do the palette test - it's a waste of time when
5989 * compared to the grayscale test.
5990 */
5991#if 0
5992 if (!test_size(pm, 3, 0, 3))
5993 return;
5994#endif
5995
5996 if (!test_size(pm, 4, 3, READ_BDHI))
5997 return;
5998
5999 if (!test_size(pm, 6, 3, READ_BDHI))
6000 return;
6001}
6002
6003
6004/******************************* TRANSFORM TESTS ******************************/
6005#ifdef PNG_READ_TRANSFORMS_SUPPORTED
6006/* A set of tests to validate libpng image transforms. The possibilities here
6007 * are legion because the transforms can be combined in a combinatorial
6008 * fashion. To deal with this some measure of restraint is required, otherwise
6009 * the tests would take forever.
6010 */
6011typedef struct image_pixel
6012{
6013 /* A local (pngvalid) representation of a PNG pixel, in all its
6014 * various forms.
6015 */
6016 unsigned int red, green, blue, alpha; /* For non-palette images. */
6017 unsigned int palette_index; /* For a palette image. */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006018 png_byte colour_type; /* As in the spec. */
6019 png_byte bit_depth; /* Defines bit size in row */
6020 png_byte sample_depth; /* Scale of samples */
6021 unsigned int have_tRNS :1; /* tRNS chunk may need processing */
6022 unsigned int swap_rgb :1; /* RGB swapped to BGR */
6023 unsigned int alpha_first :1; /* Alpha at start, not end */
6024 unsigned int alpha_inverted :1; /* Alpha channel inverted */
6025 unsigned int mono_inverted :1; /* Gray channel inverted */
6026 unsigned int swap16 :1; /* Byte swap 16-bit components */
6027 unsigned int littleendian :1; /* High bits on right */
6028 unsigned int sig_bits :1; /* Pixel shifted (sig bits only) */
Chris Craikb50c2172013-07-29 15:28:30 -07006029
6030 /* For checking the code calculates double precision floating point values
6031 * along with an error value, accumulated from the transforms. Because an
6032 * sBIT setting allows larger error bounds (indeed, by the spec, apparently
6033 * up to just less than +/-1 in the scaled value) the *lowest* sBIT for each
6034 * channel is stored. This sBIT value is folded in to the stored error value
6035 * at the end of the application of the transforms to the pixel.
Matt Sarett9b1fe632015-11-25 10:21:17 -05006036 *
6037 * If sig_bits is set above the red, green, blue and alpha values have been
6038 * scaled so they only contain the significant bits of the component values.
Chris Craikb50c2172013-07-29 15:28:30 -07006039 */
6040 double redf, greenf, bluef, alphaf;
6041 double rede, greene, bluee, alphae;
6042 png_byte red_sBIT, green_sBIT, blue_sBIT, alpha_sBIT;
6043} image_pixel;
6044
6045/* Shared utility function, see below. */
6046static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05006047image_pixel_setf(image_pixel *this, unsigned int rMax, unsigned int gMax,
6048 unsigned int bMax, unsigned int aMax)
Chris Craikb50c2172013-07-29 15:28:30 -07006049{
Matt Sarett9b1fe632015-11-25 10:21:17 -05006050 this->redf = this->red / (double)rMax;
6051 this->greenf = this->green / (double)gMax;
6052 this->bluef = this->blue / (double)bMax;
6053 this->alphaf = this->alpha / (double)aMax;
Chris Craikb50c2172013-07-29 15:28:30 -07006054
Matt Sarett9b1fe632015-11-25 10:21:17 -05006055 if (this->red < rMax)
Chris Craikb50c2172013-07-29 15:28:30 -07006056 this->rede = this->redf * DBL_EPSILON;
6057 else
6058 this->rede = 0;
Matt Sarett9b1fe632015-11-25 10:21:17 -05006059 if (this->green < gMax)
Chris Craikb50c2172013-07-29 15:28:30 -07006060 this->greene = this->greenf * DBL_EPSILON;
6061 else
6062 this->greene = 0;
Matt Sarett9b1fe632015-11-25 10:21:17 -05006063 if (this->blue < bMax)
Chris Craikb50c2172013-07-29 15:28:30 -07006064 this->bluee = this->bluef * DBL_EPSILON;
6065 else
6066 this->bluee = 0;
Matt Sarett9b1fe632015-11-25 10:21:17 -05006067 if (this->alpha < aMax)
Chris Craikb50c2172013-07-29 15:28:30 -07006068 this->alphae = this->alphaf * DBL_EPSILON;
6069 else
6070 this->alphae = 0;
6071}
6072
6073/* Initialize the structure for the next pixel - call this before doing any
6074 * transforms and call it for each pixel since all the fields may need to be
6075 * reset.
6076 */
6077static void
6078image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type,
Matt Sarett9b1fe632015-11-25 10:21:17 -05006079 png_byte bit_depth, png_uint_32 x, store_palette palette,
6080 const image_pixel *format /*from pngvalid transform of input*/)
Chris Craikb50c2172013-07-29 15:28:30 -07006081{
xNombred07bb0d2020-03-10 20:17:12 +01006082 png_byte sample_depth =
6083 (png_byte)(colour_type == PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth);
6084 unsigned int max = (1U<<sample_depth)-1;
6085 int swap16 = (format != 0 && format->swap16);
6086 int littleendian = (format != 0 && format->littleendian);
6087 int sig_bits = (format != 0 && format->sig_bits);
Chris Craikb50c2172013-07-29 15:28:30 -07006088
6089 /* Initially just set everything to the same number and the alpha to opaque.
6090 * Note that this currently assumes a simple palette where entry x has colour
6091 * rgb(x,x,x)!
6092 */
6093 this->palette_index = this->red = this->green = this->blue =
Matt Sarett9b1fe632015-11-25 10:21:17 -05006094 sample(row, colour_type, bit_depth, x, 0, swap16, littleendian);
Chris Craikb50c2172013-07-29 15:28:30 -07006095 this->alpha = max;
6096 this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT =
6097 sample_depth;
6098
6099 /* Then override as appropriate: */
6100 if (colour_type == 3) /* palette */
6101 {
6102 /* This permits the caller to default to the sample value. */
6103 if (palette != 0)
6104 {
xNombred07bb0d2020-03-10 20:17:12 +01006105 unsigned int i = this->palette_index;
Chris Craikb50c2172013-07-29 15:28:30 -07006106
6107 this->red = palette[i].red;
6108 this->green = palette[i].green;
6109 this->blue = palette[i].blue;
6110 this->alpha = palette[i].alpha;
6111 }
6112 }
6113
6114 else /* not palette */
6115 {
6116 unsigned int i = 0;
6117
Matt Sarett9b1fe632015-11-25 10:21:17 -05006118 if ((colour_type & 4) != 0 && format != 0 && format->alpha_first)
6119 {
6120 this->alpha = this->red;
6121 /* This handles the gray case for 'AG' pixels */
6122 this->palette_index = this->red = this->green = this->blue =
6123 sample(row, colour_type, bit_depth, x, 1, swap16, littleendian);
6124 i = 1;
6125 }
6126
Chris Craikb50c2172013-07-29 15:28:30 -07006127 if (colour_type & 2)
6128 {
Matt Sarett9b1fe632015-11-25 10:21:17 -05006129 /* Green is second for both BGR and RGB: */
6130 this->green = sample(row, colour_type, bit_depth, x, ++i, swap16,
6131 littleendian);
6132
6133 if (format != 0 && format->swap_rgb) /* BGR */
6134 this->red = sample(row, colour_type, bit_depth, x, ++i, swap16,
6135 littleendian);
6136 else
6137 this->blue = sample(row, colour_type, bit_depth, x, ++i, swap16,
6138 littleendian);
Chris Craikb50c2172013-07-29 15:28:30 -07006139 }
Matt Sarett9b1fe632015-11-25 10:21:17 -05006140
6141 else /* grayscale */ if (format != 0 && format->mono_inverted)
6142 this->red = this->green = this->blue = this->red ^ max;
6143
6144 if ((colour_type & 4) != 0) /* alpha */
6145 {
6146 if (format == 0 || !format->alpha_first)
6147 this->alpha = sample(row, colour_type, bit_depth, x, ++i, swap16,
6148 littleendian);
6149
6150 if (format != 0 && format->alpha_inverted)
6151 this->alpha ^= max;
6152 }
Chris Craikb50c2172013-07-29 15:28:30 -07006153 }
6154
6155 /* Calculate the scaled values, these are simply the values divided by
6156 * 'max' and the error is initialized to the double precision epsilon value
6157 * from the header file.
6158 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006159 image_pixel_setf(this,
6160 sig_bits ? (1U << format->red_sBIT)-1 : max,
6161 sig_bits ? (1U << format->green_sBIT)-1 : max,
6162 sig_bits ? (1U << format->blue_sBIT)-1 : max,
6163 sig_bits ? (1U << format->alpha_sBIT)-1 : max);
Chris Craikb50c2172013-07-29 15:28:30 -07006164
6165 /* Store the input information for use in the transforms - these will
6166 * modify the information.
6167 */
6168 this->colour_type = colour_type;
6169 this->bit_depth = bit_depth;
6170 this->sample_depth = sample_depth;
6171 this->have_tRNS = 0;
Matt Sarett9b1fe632015-11-25 10:21:17 -05006172 this->swap_rgb = 0;
6173 this->alpha_first = 0;
6174 this->alpha_inverted = 0;
6175 this->mono_inverted = 0;
6176 this->swap16 = 0;
6177 this->littleendian = 0;
6178 this->sig_bits = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07006179}
6180
Matt Sarett9b1fe632015-11-25 10:21:17 -05006181#if defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_GRAY_TO_RGB_SUPPORTED\
6182 || defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_EXPAND_16_SUPPORTED\
6183 || defined PNG_READ_BACKGROUND_SUPPORTED
Chris Craikb50c2172013-07-29 15:28:30 -07006184/* Convert a palette image to an rgb image. This necessarily converts the tRNS
6185 * chunk at the same time, because the tRNS will be in palette form. The way
6186 * palette validation works means that the original palette is never updated,
6187 * instead the image_pixel value from the row contains the RGB of the
6188 * corresponding palette entry and *this* is updated. Consequently this routine
6189 * only needs to change the colour type information.
6190 */
6191static void
6192image_pixel_convert_PLTE(image_pixel *this)
6193{
6194 if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
6195 {
6196 if (this->have_tRNS)
6197 {
6198 this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
6199 this->have_tRNS = 0;
6200 }
6201 else
6202 this->colour_type = PNG_COLOR_TYPE_RGB;
6203
6204 /* The bit depth of the row changes at this point too (notice that this is
6205 * the row format, not the sample depth, which is separate.)
6206 */
6207 this->bit_depth = 8;
6208 }
6209}
6210
6211/* Add an alpha channel; this will import the tRNS information because tRNS is
6212 * not valid in an alpha image. The bit depth will invariably be set to at
Matt Sarett9b1fe632015-11-25 10:21:17 -05006213 * least 8 prior to 1.7.0. Palette images will be converted to alpha (using
6214 * the above API). With png_set_background the alpha channel is never expanded
6215 * but this routine is used by pngvalid to simplify code; 'for_background'
6216 * records this.
Chris Craikb50c2172013-07-29 15:28:30 -07006217 */
6218static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05006219image_pixel_add_alpha(image_pixel *this, const standard_display *display,
6220 int for_background)
Chris Craikb50c2172013-07-29 15:28:30 -07006221{
6222 if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
6223 image_pixel_convert_PLTE(this);
6224
6225 if ((this->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
6226 {
6227 if (this->colour_type == PNG_COLOR_TYPE_GRAY)
6228 {
Matt Sarett9b1fe632015-11-25 10:21:17 -05006229# if PNG_LIBPNG_VER < 10700
6230 if (!for_background && this->bit_depth < 8)
6231 this->bit_depth = this->sample_depth = 8;
6232# endif
Chris Craikb50c2172013-07-29 15:28:30 -07006233
6234 if (this->have_tRNS)
6235 {
Matt Sarett9b1fe632015-11-25 10:21:17 -05006236 /* After 1.7 the expansion of bit depth only happens if there is a
6237 * tRNS chunk to expand at this point.
6238 */
6239# if PNG_LIBPNG_VER >= 10700
6240 if (!for_background && this->bit_depth < 8)
6241 this->bit_depth = this->sample_depth = 8;
6242# endif
6243
Chris Craikb50c2172013-07-29 15:28:30 -07006244 this->have_tRNS = 0;
6245
6246 /* Check the input, original, channel value here against the
6247 * original tRNS gray chunk valie.
6248 */
6249 if (this->red == display->transparent.red)
6250 this->alphaf = 0;
6251 else
6252 this->alphaf = 1;
6253 }
6254 else
6255 this->alphaf = 1;
6256
6257 this->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
6258 }
6259
6260 else if (this->colour_type == PNG_COLOR_TYPE_RGB)
6261 {
6262 if (this->have_tRNS)
6263 {
6264 this->have_tRNS = 0;
6265
6266 /* Again, check the exact input values, not the current transformed
6267 * value!
6268 */
6269 if (this->red == display->transparent.red &&
6270 this->green == display->transparent.green &&
6271 this->blue == display->transparent.blue)
6272 this->alphaf = 0;
6273 else
6274 this->alphaf = 1;
Chris Craikb50c2172013-07-29 15:28:30 -07006275 }
Matt Sarett9b1fe632015-11-25 10:21:17 -05006276 else
6277 this->alphaf = 1;
6278
6279 this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
Chris Craikb50c2172013-07-29 15:28:30 -07006280 }
6281
6282 /* The error in the alpha is zero and the sBIT value comes from the
6283 * original sBIT data (actually it will always be the original bit depth).
6284 */
6285 this->alphae = 0;
6286 this->alpha_sBIT = display->alpha_sBIT;
6287 }
6288}
Matt Sarett9b1fe632015-11-25 10:21:17 -05006289#endif /* transforms that need image_pixel_add_alpha */
Chris Craikb50c2172013-07-29 15:28:30 -07006290
6291struct transform_display;
6292typedef struct image_transform
6293{
6294 /* The name of this transform: a string. */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006295 const char *name;
Chris Craikb50c2172013-07-29 15:28:30 -07006296
6297 /* Each transform can be disabled from the command line: */
6298 int enable;
6299
6300 /* The global list of transforms; read only. */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006301 struct image_transform *const list;
Chris Craikb50c2172013-07-29 15:28:30 -07006302
6303 /* The global count of the number of times this transform has been set on an
6304 * image.
6305 */
6306 unsigned int global_use;
6307
6308 /* The local count of the number of times this transform has been set. */
6309 unsigned int local_use;
6310
6311 /* The next transform in the list, each transform must call its own next
6312 * transform after it has processed the pixel successfully.
6313 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006314 const struct image_transform *next;
Chris Craikb50c2172013-07-29 15:28:30 -07006315
6316 /* A single transform for the image, expressed as a series of function
6317 * callbacks and some space for values.
6318 *
6319 * First a callback to add any required modifications to the png_modifier;
6320 * this gets called just before the modifier is set up for read.
6321 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006322 void (*ini)(const struct image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006323 struct transform_display *that);
6324
6325 /* And a callback to set the transform on the current png_read_struct:
6326 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006327 void (*set)(const struct image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006328 struct transform_display *that, png_structp pp, png_infop pi);
6329
6330 /* Then a transform that takes an input pixel in one PNG format or another
6331 * and modifies it by a pngvalid implementation of the transform (thus
6332 * duplicating the libpng intent without, we hope, duplicating the bugs
6333 * in the libpng implementation!) The png_structp is solely to allow error
6334 * reporting via png_error and png_warning.
6335 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006336 void (*mod)(const struct image_transform *this, image_pixel *that,
6337 png_const_structp pp, const struct transform_display *display);
Chris Craikb50c2172013-07-29 15:28:30 -07006338
6339 /* Add this transform to the list and return true if the transform is
6340 * meaningful for this colour type and bit depth - if false then the
6341 * transform should have no effect on the image so there's not a lot of
6342 * point running it.
6343 */
6344 int (*add)(struct image_transform *this,
Matt Sarett9b1fe632015-11-25 10:21:17 -05006345 const struct image_transform **that, png_byte colour_type,
Chris Craikb50c2172013-07-29 15:28:30 -07006346 png_byte bit_depth);
6347} image_transform;
6348
6349typedef struct transform_display
6350{
6351 standard_display this;
6352
6353 /* Parameters */
6354 png_modifier* pm;
Matt Sarett9b1fe632015-11-25 10:21:17 -05006355 const image_transform* transform_list;
Matt Sarett06f10872016-01-04 12:56:20 -05006356 unsigned int max_gamma_8;
Chris Craikb50c2172013-07-29 15:28:30 -07006357
6358 /* Local variables */
6359 png_byte output_colour_type;
6360 png_byte output_bit_depth;
Matt Sarett9b1fe632015-11-25 10:21:17 -05006361 png_byte unpacked;
Chris Craikb50c2172013-07-29 15:28:30 -07006362
6363 /* Modifications (not necessarily used.) */
6364 gama_modification gama_mod;
6365 chrm_modification chrm_mod;
6366 srgb_modification srgb_mod;
6367} transform_display;
6368
6369/* Set sRGB, cHRM and gAMA transforms as required by the current encoding. */
6370static void
6371transform_set_encoding(transform_display *this)
6372{
6373 /* Set up the png_modifier '_current' fields then use these to determine how
6374 * to add appropriate chunks.
6375 */
6376 png_modifier *pm = this->pm;
6377
6378 modifier_set_encoding(pm);
6379
6380 if (modifier_color_encoding_is_set(pm))
6381 {
6382 if (modifier_color_encoding_is_sRGB(pm))
6383 srgb_modification_init(&this->srgb_mod, pm, PNG_sRGB_INTENT_ABSOLUTE);
6384
6385 else
6386 {
6387 /* Set gAMA and cHRM separately. */
6388 gama_modification_init(&this->gama_mod, pm, pm->current_gamma);
6389
6390 if (pm->current_encoding != 0)
6391 chrm_modification_init(&this->chrm_mod, pm, pm->current_encoding);
6392 }
6393 }
6394}
6395
6396/* Three functions to end the list: */
6397static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05006398image_transform_ini_end(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006399 transform_display *that)
6400{
6401 UNUSED(this)
6402 UNUSED(that)
6403}
6404
6405static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05006406image_transform_set_end(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07006407 transform_display *that, png_structp pp, png_infop pi)
6408{
6409 UNUSED(this)
6410 UNUSED(that)
6411 UNUSED(pp)
6412 UNUSED(pi)
6413}
6414
6415/* At the end of the list recalculate the output image pixel value from the
6416 * double precision values set up by the preceding 'mod' calls:
6417 */
6418static unsigned int
6419sample_scale(double sample_value, unsigned int scale)
6420{
6421 sample_value = floor(sample_value * scale + .5);
6422
6423 /* Return NaN as 0: */
6424 if (!(sample_value > 0))
6425 sample_value = 0;
6426 else if (sample_value > scale)
6427 sample_value = scale;
6428
6429 return (unsigned int)sample_value;
6430}
6431
6432static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05006433image_transform_mod_end(const image_transform *this, image_pixel *that,
6434 png_const_structp pp, const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07006435{
xNombred07bb0d2020-03-10 20:17:12 +01006436 unsigned int scale = (1U<<that->sample_depth)-1;
6437 int sig_bits = that->sig_bits;
Chris Craikb50c2172013-07-29 15:28:30 -07006438
6439 UNUSED(this)
6440 UNUSED(pp)
6441 UNUSED(display)
6442
6443 /* At the end recalculate the digitized red green and blue values according
6444 * to the current sample_depth of the pixel.
6445 *
6446 * The sample value is simply scaled to the maximum, checking for over
6447 * and underflow (which can both happen for some image transforms,
6448 * including simple size scaling, though libpng doesn't do that at present.
6449 */
6450 that->red = sample_scale(that->redf, scale);
6451
Matt Sarett9b1fe632015-11-25 10:21:17 -05006452 /* This is a bit bogus; really the above calculation should use the red_sBIT
6453 * value, not sample_depth, but because libpng does png_set_shift by just
6454 * shifting the bits we get errors if we don't do it the same way.
6455 */
6456 if (sig_bits && that->red_sBIT < that->sample_depth)
6457 that->red >>= that->sample_depth - that->red_sBIT;
6458
Chris Craikb50c2172013-07-29 15:28:30 -07006459 /* The error value is increased, at the end, according to the lowest sBIT
6460 * value seen. Common sense tells us that the intermediate integer
6461 * representations are no more accurate than +/- 0.5 in the integral values,
6462 * the sBIT allows the implementation to be worse than this. In addition the
6463 * PNG specification actually permits any error within the range (-1..+1),
6464 * but that is ignored here. Instead the final digitized value is compared,
6465 * below to the digitized value of the error limits - this has the net effect
6466 * of allowing (almost) +/-1 in the output value. It's difficult to see how
6467 * any algorithm that digitizes intermediate results can be more accurate.
6468 */
6469 that->rede += 1./(2*((1U<<that->red_sBIT)-1));
6470
6471 if (that->colour_type & PNG_COLOR_MASK_COLOR)
6472 {
6473 that->green = sample_scale(that->greenf, scale);
Matt Sarett9b1fe632015-11-25 10:21:17 -05006474 if (sig_bits && that->green_sBIT < that->sample_depth)
6475 that->green >>= that->sample_depth - that->green_sBIT;
6476
Chris Craikb50c2172013-07-29 15:28:30 -07006477 that->blue = sample_scale(that->bluef, scale);
Matt Sarett9b1fe632015-11-25 10:21:17 -05006478 if (sig_bits && that->blue_sBIT < that->sample_depth)
6479 that->blue >>= that->sample_depth - that->blue_sBIT;
6480
Chris Craikb50c2172013-07-29 15:28:30 -07006481 that->greene += 1./(2*((1U<<that->green_sBIT)-1));
6482 that->bluee += 1./(2*((1U<<that->blue_sBIT)-1));
6483 }
6484 else
6485 {
6486 that->blue = that->green = that->red;
6487 that->bluef = that->greenf = that->redf;
6488 that->bluee = that->greene = that->rede;
6489 }
6490
6491 if ((that->colour_type & PNG_COLOR_MASK_ALPHA) ||
6492 that->colour_type == PNG_COLOR_TYPE_PALETTE)
6493 {
6494 that->alpha = sample_scale(that->alphaf, scale);
6495 that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1));
6496 }
6497 else
6498 {
6499 that->alpha = scale; /* opaque */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006500 that->alphaf = 1; /* Override this. */
Chris Craikb50c2172013-07-29 15:28:30 -07006501 that->alphae = 0; /* It's exact ;-) */
6502 }
Matt Sarett9b1fe632015-11-25 10:21:17 -05006503
6504 if (sig_bits && that->alpha_sBIT < that->sample_depth)
6505 that->alpha >>= that->sample_depth - that->alpha_sBIT;
Chris Craikb50c2172013-07-29 15:28:30 -07006506}
6507
6508/* Static 'end' structure: */
6509static image_transform image_transform_end =
6510{
6511 "(end)", /* name */
6512 1, /* enable */
6513 0, /* list */
6514 0, /* global_use */
6515 0, /* local_use */
6516 0, /* next */
6517 image_transform_ini_end,
6518 image_transform_set_end,
6519 image_transform_mod_end,
6520 0 /* never called, I want it to crash if it is! */
6521};
6522
6523/* Reader callbacks and implementations, where they differ from the standard
6524 * ones.
6525 */
6526static void
6527transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id,
Matt Sarett9b1fe632015-11-25 10:21:17 -05006528 const image_transform *transform_list)
Chris Craikb50c2172013-07-29 15:28:30 -07006529{
6530 memset(dp, 0, sizeof *dp);
6531
6532 /* Standard fields */
Matt Sarett06f10872016-01-04 12:56:20 -05006533 standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
Chris Craikb50c2172013-07-29 15:28:30 -07006534 pm->use_update_info);
6535
6536 /* Parameter fields */
6537 dp->pm = pm;
6538 dp->transform_list = transform_list;
Matt Sarett06f10872016-01-04 12:56:20 -05006539 dp->max_gamma_8 = 16;
Chris Craikb50c2172013-07-29 15:28:30 -07006540
6541 /* Local variable fields */
6542 dp->output_colour_type = 255; /* invalid */
6543 dp->output_bit_depth = 255; /* invalid */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006544 dp->unpacked = 0; /* not unpacked */
Chris Craikb50c2172013-07-29 15:28:30 -07006545}
6546
6547static void
6548transform_info_imp(transform_display *dp, png_structp pp, png_infop pi)
6549{
6550 /* Reuse the standard stuff as appropriate. */
6551 standard_info_part1(&dp->this, pp, pi);
6552
6553 /* Now set the list of transforms. */
6554 dp->transform_list->set(dp->transform_list, dp, pp, pi);
6555
6556 /* Update the info structure for these transforms: */
6557 {
6558 int i = dp->this.use_update_info;
6559 /* Always do one call, even if use_update_info is 0. */
6560 do
6561 png_read_update_info(pp, pi);
6562 while (--i > 0);
6563 }
6564
6565 /* And get the output information into the standard_display */
6566 standard_info_part2(&dp->this, pp, pi, 1/*images*/);
6567
6568 /* Plus the extra stuff we need for the transform tests: */
6569 dp->output_colour_type = png_get_color_type(pp, pi);
6570 dp->output_bit_depth = png_get_bit_depth(pp, pi);
6571
Matt Sarett9b1fe632015-11-25 10:21:17 -05006572 /* If png_set_filler is in action then fake the output color type to include
6573 * an alpha channel where appropriate.
6574 */
6575 if (dp->output_bit_depth >= 8 &&
6576 (dp->output_colour_type == PNG_COLOR_TYPE_RGB ||
6577 dp->output_colour_type == PNG_COLOR_TYPE_GRAY) && dp->this.filler)
6578 dp->output_colour_type |= 4;
6579
Chris Craikb50c2172013-07-29 15:28:30 -07006580 /* Validate the combination of colour type and bit depth that we are getting
6581 * out of libpng; the semantics of something not in the PNG spec are, at
6582 * best, unclear.
6583 */
6584 switch (dp->output_colour_type)
6585 {
6586 case PNG_COLOR_TYPE_PALETTE:
6587 if (dp->output_bit_depth > 8) goto error;
Leon Scroggins III3cc83ac2017-10-06 11:02:56 -04006588 /* FALLTHROUGH */
Chris Craikb50c2172013-07-29 15:28:30 -07006589 case PNG_COLOR_TYPE_GRAY:
6590 if (dp->output_bit_depth == 1 || dp->output_bit_depth == 2 ||
6591 dp->output_bit_depth == 4)
6592 break;
Leon Scroggins III3cc83ac2017-10-06 11:02:56 -04006593 /* FALLTHROUGH */
Chris Craikb50c2172013-07-29 15:28:30 -07006594 default:
6595 if (dp->output_bit_depth == 8 || dp->output_bit_depth == 16)
6596 break;
Leon Scroggins III3cc83ac2017-10-06 11:02:56 -04006597 /* FALLTHROUGH */
Chris Craikb50c2172013-07-29 15:28:30 -07006598 error:
6599 {
6600 char message[128];
6601 size_t pos;
6602
6603 pos = safecat(message, sizeof message, 0,
6604 "invalid final bit depth: colour type(");
6605 pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
6606 pos = safecat(message, sizeof message, pos, ") with bit depth: ");
6607 pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
6608
6609 png_error(pp, message);
6610 }
6611 }
6612
6613 /* Use a test pixel to check that the output agrees with what we expect -
Matt Sarett9b1fe632015-11-25 10:21:17 -05006614 * this avoids running the whole test if the output is unexpected. This also
6615 * checks for internal errors.
Chris Craikb50c2172013-07-29 15:28:30 -07006616 */
6617 {
6618 image_pixel test_pixel;
6619
6620 memset(&test_pixel, 0, sizeof test_pixel);
6621 test_pixel.colour_type = dp->this.colour_type; /* input */
6622 test_pixel.bit_depth = dp->this.bit_depth;
6623 if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
6624 test_pixel.sample_depth = 8;
6625 else
6626 test_pixel.sample_depth = test_pixel.bit_depth;
6627 /* Don't need sBIT here, but it must be set to non-zero to avoid
6628 * arithmetic overflows.
6629 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006630 test_pixel.have_tRNS = dp->this.is_transparent != 0;
Chris Craikb50c2172013-07-29 15:28:30 -07006631 test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT =
6632 test_pixel.alpha_sBIT = test_pixel.sample_depth;
6633
6634 dp->transform_list->mod(dp->transform_list, &test_pixel, pp, dp);
6635
6636 if (test_pixel.colour_type != dp->output_colour_type)
6637 {
6638 char message[128];
6639 size_t pos = safecat(message, sizeof message, 0, "colour type ");
6640
6641 pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
6642 pos = safecat(message, sizeof message, pos, " expected ");
6643 pos = safecatn(message, sizeof message, pos, test_pixel.colour_type);
6644
6645 png_error(pp, message);
6646 }
6647
6648 if (test_pixel.bit_depth != dp->output_bit_depth)
6649 {
6650 char message[128];
6651 size_t pos = safecat(message, sizeof message, 0, "bit depth ");
6652
6653 pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
6654 pos = safecat(message, sizeof message, pos, " expected ");
6655 pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
6656
6657 png_error(pp, message);
6658 }
6659
6660 /* If both bit depth and colour type are correct check the sample depth.
Chris Craikb50c2172013-07-29 15:28:30 -07006661 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006662 if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE &&
6663 test_pixel.sample_depth != 8) /* oops - internal error! */
6664 png_error(pp, "pngvalid: internal: palette sample depth not 8");
6665 else if (dp->unpacked && test_pixel.bit_depth != 8)
6666 png_error(pp, "pngvalid: internal: bad unpacked pixel depth");
6667 else if (!dp->unpacked && test_pixel.colour_type != PNG_COLOR_TYPE_PALETTE
6668 && test_pixel.bit_depth != test_pixel.sample_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07006669 {
6670 char message[128];
6671 size_t pos = safecat(message, sizeof message, 0,
6672 "internal: sample depth ");
6673
Matt Sarett9b1fe632015-11-25 10:21:17 -05006674 /* Because unless something has set 'unpacked' or the image is palette
6675 * mapped we expect the transform to keep sample depth and bit depth
6676 * the same.
6677 */
6678 pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth);
6679 pos = safecat(message, sizeof message, pos, " expected ");
6680 pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
6681
6682 png_error(pp, message);
6683 }
6684 else if (test_pixel.bit_depth != dp->output_bit_depth)
6685 {
6686 /* This could be a libpng error too; libpng has not produced what we
6687 * expect for the output bit depth.
6688 */
6689 char message[128];
6690 size_t pos = safecat(message, sizeof message, 0,
6691 "internal: bit depth ");
6692
Chris Craikb50c2172013-07-29 15:28:30 -07006693 pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
6694 pos = safecat(message, sizeof message, pos, " expected ");
Matt Sarett9b1fe632015-11-25 10:21:17 -05006695 pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
Chris Craikb50c2172013-07-29 15:28:30 -07006696
6697 png_error(pp, message);
6698 }
6699 }
6700}
6701
Sireesh Tripurarib478e662014-05-09 15:15:10 +05306702static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07006703transform_info(png_structp pp, png_infop pi)
6704{
6705 transform_info_imp(voidcast(transform_display*, png_get_progressive_ptr(pp)),
6706 pp, pi);
6707}
6708
6709static void
6710transform_range_check(png_const_structp pp, unsigned int r, unsigned int g,
6711 unsigned int b, unsigned int a, unsigned int in_digitized, double in,
6712 unsigned int out, png_byte sample_depth, double err, double limit,
Matt Sarett9b1fe632015-11-25 10:21:17 -05006713 const char *name, double digitization_error)
Chris Craikb50c2172013-07-29 15:28:30 -07006714{
6715 /* Compare the scaled, digitzed, values of our local calculation (in+-err)
6716 * with the digitized values libpng produced; 'sample_depth' is the actual
6717 * digitization depth of the libpng output colors (the bit depth except for
6718 * palette images where it is always 8.) The check on 'err' is to detect
6719 * internal errors in pngvalid itself.
6720 */
6721 unsigned int max = (1U<<sample_depth)-1;
6722 double in_min = ceil((in-err)*max - digitization_error);
6723 double in_max = floor((in+err)*max + digitization_error);
Matt Sarett11466862016-02-19 13:41:30 -05006724 if (debugonly(err > limit ||) !(out >= in_min && out <= in_max))
Chris Craikb50c2172013-07-29 15:28:30 -07006725 {
6726 char message[256];
6727 size_t pos;
6728
6729 pos = safecat(message, sizeof message, 0, name);
6730 pos = safecat(message, sizeof message, pos, " output value error: rgba(");
6731 pos = safecatn(message, sizeof message, pos, r);
6732 pos = safecat(message, sizeof message, pos, ",");
6733 pos = safecatn(message, sizeof message, pos, g);
6734 pos = safecat(message, sizeof message, pos, ",");
6735 pos = safecatn(message, sizeof message, pos, b);
6736 pos = safecat(message, sizeof message, pos, ",");
6737 pos = safecatn(message, sizeof message, pos, a);
6738 pos = safecat(message, sizeof message, pos, "): ");
6739 pos = safecatn(message, sizeof message, pos, out);
6740 pos = safecat(message, sizeof message, pos, " expected: ");
6741 pos = safecatn(message, sizeof message, pos, in_digitized);
6742 pos = safecat(message, sizeof message, pos, " (");
6743 pos = safecatd(message, sizeof message, pos, (in-err)*max, 3);
6744 pos = safecat(message, sizeof message, pos, "..");
6745 pos = safecatd(message, sizeof message, pos, (in+err)*max, 3);
6746 pos = safecat(message, sizeof message, pos, ")");
6747
6748 png_error(pp, message);
6749 }
Matt Sarett11466862016-02-19 13:41:30 -05006750
6751 UNUSED(limit)
Chris Craikb50c2172013-07-29 15:28:30 -07006752}
6753
6754static void
6755transform_image_validate(transform_display *dp, png_const_structp pp,
6756 png_infop pi)
6757{
6758 /* Constants for the loop below: */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006759 const png_store* const ps = dp->this.ps;
xNombred07bb0d2020-03-10 20:17:12 +01006760 png_byte in_ct = dp->this.colour_type;
6761 png_byte in_bd = dp->this.bit_depth;
6762 png_uint_32 w = dp->this.w;
6763 png_uint_32 h = dp->this.h;
6764 png_byte out_ct = dp->output_colour_type;
6765 png_byte out_bd = dp->output_bit_depth;
6766 png_byte sample_depth =
6767 (png_byte)(out_ct == PNG_COLOR_TYPE_PALETTE ? 8 : out_bd);
6768 png_byte red_sBIT = dp->this.red_sBIT;
6769 png_byte green_sBIT = dp->this.green_sBIT;
6770 png_byte blue_sBIT = dp->this.blue_sBIT;
6771 png_byte alpha_sBIT = dp->this.alpha_sBIT;
6772 int have_tRNS = dp->this.is_transparent;
Chris Craikb50c2172013-07-29 15:28:30 -07006773 double digitization_error;
6774
6775 store_palette out_palette;
6776 png_uint_32 y;
6777
6778 UNUSED(pi)
6779
6780 /* Check for row overwrite errors */
6781 store_image_check(dp->this.ps, pp, 0);
6782
6783 /* Read the palette corresponding to the output if the output colour type
xNombred07bb0d2020-03-10 20:17:12 +01006784 * indicates a palette, otherwise set out_palette to garbage.
Chris Craikb50c2172013-07-29 15:28:30 -07006785 */
6786 if (out_ct == PNG_COLOR_TYPE_PALETTE)
6787 {
6788 /* Validate that the palette count itself has not changed - this is not
6789 * expected.
6790 */
6791 int npalette = (-1);
6792
6793 (void)read_palette(out_palette, &npalette, pp, pi);
6794 if (npalette != dp->this.npalette)
6795 png_error(pp, "unexpected change in palette size");
6796
6797 digitization_error = .5;
6798 }
6799 else
6800 {
6801 png_byte in_sample_depth;
6802
6803 memset(out_palette, 0x5e, sizeof out_palette);
6804
Sireesh Tripurarib478e662014-05-09 15:15:10 +05306805 /* use-input-precision means assume that if the input has 8 bit (or less)
6806 * samples and the output has 16 bit samples the calculations will be done
6807 * with 8 bit precision, not 16.
Chris Craikb50c2172013-07-29 15:28:30 -07006808 */
6809 if (in_ct == PNG_COLOR_TYPE_PALETTE || in_bd < 16)
6810 in_sample_depth = 8;
6811 else
6812 in_sample_depth = in_bd;
6813
6814 if (sample_depth != 16 || in_sample_depth > 8 ||
6815 !dp->pm->calculations_use_input_precision)
6816 digitization_error = .5;
6817
Sireesh Tripurarib478e662014-05-09 15:15:10 +05306818 /* Else calculations are at 8 bit precision, and the output actually
6819 * consists of scaled 8-bit values, so scale .5 in 8 bits to the 16 bits:
Chris Craikb50c2172013-07-29 15:28:30 -07006820 */
6821 else
6822 digitization_error = .5 * 257;
6823 }
6824
6825 for (y=0; y<h; ++y)
6826 {
Matt Sarett9b1fe632015-11-25 10:21:17 -05006827 png_const_bytep const pRow = store_image_row(ps, pp, 0, y);
Chris Craikb50c2172013-07-29 15:28:30 -07006828 png_uint_32 x;
6829
6830 /* The original, standard, row pre-transforms. */
6831 png_byte std[STANDARD_ROWMAX];
6832
6833 transform_row(pp, std, in_ct, in_bd, y);
6834
6835 /* Go through each original pixel transforming it and comparing with what
6836 * libpng did to the same pixel.
6837 */
6838 for (x=0; x<w; ++x)
6839 {
6840 image_pixel in_pixel, out_pixel;
6841 unsigned int r, g, b, a;
6842
6843 /* Find out what we think the pixel should be: */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006844 image_pixel_init(&in_pixel, std, in_ct, in_bd, x, dp->this.palette,
6845 NULL);
Chris Craikb50c2172013-07-29 15:28:30 -07006846
6847 in_pixel.red_sBIT = red_sBIT;
6848 in_pixel.green_sBIT = green_sBIT;
6849 in_pixel.blue_sBIT = blue_sBIT;
6850 in_pixel.alpha_sBIT = alpha_sBIT;
Matt Sarett9b1fe632015-11-25 10:21:17 -05006851 in_pixel.have_tRNS = have_tRNS != 0;
Chris Craikb50c2172013-07-29 15:28:30 -07006852
6853 /* For error detection, below. */
6854 r = in_pixel.red;
6855 g = in_pixel.green;
6856 b = in_pixel.blue;
6857 a = in_pixel.alpha;
6858
Matt Sarett9b1fe632015-11-25 10:21:17 -05006859 /* This applies the transforms to the input data, including output
6860 * format operations which must be used when reading the output
6861 * pixel that libpng produces.
6862 */
Chris Craikb50c2172013-07-29 15:28:30 -07006863 dp->transform_list->mod(dp->transform_list, &in_pixel, pp, dp);
6864
6865 /* Read the output pixel and compare it to what we got, we don't
Matt Sarett9b1fe632015-11-25 10:21:17 -05006866 * use the error field here, so no need to update sBIT. in_pixel
6867 * says whether we expect libpng to change the output format.
Chris Craikb50c2172013-07-29 15:28:30 -07006868 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05006869 image_pixel_init(&out_pixel, pRow, out_ct, out_bd, x, out_palette,
6870 &in_pixel);
Chris Craikb50c2172013-07-29 15:28:30 -07006871
6872 /* We don't expect changes to the index here even if the bit depth is
6873 * changed.
6874 */
6875 if (in_ct == PNG_COLOR_TYPE_PALETTE &&
6876 out_ct == PNG_COLOR_TYPE_PALETTE)
6877 {
6878 if (in_pixel.palette_index != out_pixel.palette_index)
6879 png_error(pp, "unexpected transformed palette index");
6880 }
6881
6882 /* Check the colours for palette images too - in fact the palette could
6883 * be separately verified itself in most cases.
6884 */
6885 if (in_pixel.red != out_pixel.red)
6886 transform_range_check(pp, r, g, b, a, in_pixel.red, in_pixel.redf,
6887 out_pixel.red, sample_depth, in_pixel.rede,
6888 dp->pm->limit + 1./(2*((1U<<in_pixel.red_sBIT)-1)), "red/gray",
6889 digitization_error);
6890
6891 if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
6892 in_pixel.green != out_pixel.green)
6893 transform_range_check(pp, r, g, b, a, in_pixel.green,
6894 in_pixel.greenf, out_pixel.green, sample_depth, in_pixel.greene,
6895 dp->pm->limit + 1./(2*((1U<<in_pixel.green_sBIT)-1)), "green",
6896 digitization_error);
6897
6898 if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
6899 in_pixel.blue != out_pixel.blue)
6900 transform_range_check(pp, r, g, b, a, in_pixel.blue, in_pixel.bluef,
6901 out_pixel.blue, sample_depth, in_pixel.bluee,
6902 dp->pm->limit + 1./(2*((1U<<in_pixel.blue_sBIT)-1)), "blue",
6903 digitization_error);
6904
6905 if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0 &&
6906 in_pixel.alpha != out_pixel.alpha)
6907 transform_range_check(pp, r, g, b, a, in_pixel.alpha,
6908 in_pixel.alphaf, out_pixel.alpha, sample_depth, in_pixel.alphae,
6909 dp->pm->limit + 1./(2*((1U<<in_pixel.alpha_sBIT)-1)), "alpha",
6910 digitization_error);
6911 } /* pixel (x) loop */
6912 } /* row (y) loop */
6913
6914 /* Record that something was actually checked to avoid a false positive. */
6915 dp->this.ps->validated = 1;
6916}
6917
Sireesh Tripurarib478e662014-05-09 15:15:10 +05306918static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07006919transform_end(png_structp ppIn, png_infop pi)
6920{
6921 png_const_structp pp = ppIn;
6922 transform_display *dp = voidcast(transform_display*,
6923 png_get_progressive_ptr(pp));
6924
6925 if (!dp->this.speed)
6926 transform_image_validate(dp, pp, pi);
6927 else
6928 dp->this.ps->validated = 1;
6929}
6930
6931/* A single test run. */
6932static void
xNombred07bb0d2020-03-10 20:17:12 +01006933transform_test(png_modifier *pmIn, png_uint_32 idIn,
Matt Sarett9b1fe632015-11-25 10:21:17 -05006934 const image_transform* transform_listIn, const char * const name)
Chris Craikb50c2172013-07-29 15:28:30 -07006935{
6936 transform_display d;
6937 context(&pmIn->this, fault);
6938
6939 transform_display_init(&d, pmIn, idIn, transform_listIn);
6940
6941 Try
6942 {
6943 size_t pos = 0;
6944 png_structp pp;
6945 png_infop pi;
6946 char full_name[256];
6947
6948 /* Make sure the encoding fields are correct and enter the required
6949 * modifications.
6950 */
6951 transform_set_encoding(&d);
6952
6953 /* Add any modifications required by the transform list. */
6954 d.transform_list->ini(d.transform_list, &d);
6955
6956 /* Add the color space information, if any, to the name. */
6957 pos = safecat(full_name, sizeof full_name, pos, name);
6958 pos = safecat_current_encoding(full_name, sizeof full_name, pos, d.pm);
6959
6960 /* Get a png_struct for reading the image. */
6961 pp = set_modifier_for_read(d.pm, &pi, d.this.id, full_name);
6962 standard_palette_init(&d.this);
6963
6964# if 0
6965 /* Logging (debugging only) */
6966 {
6967 char buffer[256];
6968
6969 (void)store_message(&d.pm->this, pp, buffer, sizeof buffer, 0,
6970 "running test");
6971
6972 fprintf(stderr, "%s\n", buffer);
6973 }
6974# endif
6975
6976 /* Introduce the correct read function. */
6977 if (d.pm->this.progressive)
6978 {
6979 /* Share the row function with the standard implementation. */
6980 png_set_progressive_read_fn(pp, &d, transform_info, progressive_row,
6981 transform_end);
6982
6983 /* Now feed data into the reader until we reach the end: */
6984 modifier_progressive_read(d.pm, pp, pi);
6985 }
6986 else
6987 {
6988 /* modifier_read expects a png_modifier* */
6989 png_set_read_fn(pp, d.pm, modifier_read);
6990
6991 /* Check the header values: */
6992 png_read_info(pp, pi);
6993
6994 /* Process the 'info' requirements. Only one image is generated */
6995 transform_info_imp(&d, pp, pi);
6996
6997 sequential_row(&d.this, pp, pi, -1, 0);
6998
6999 if (!d.this.speed)
7000 transform_image_validate(&d, pp, pi);
7001 else
7002 d.this.ps->validated = 1;
7003 }
7004
7005 modifier_reset(d.pm);
7006 }
7007
7008 Catch(fault)
7009 {
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307010 modifier_reset(voidcast(png_modifier*,(void*)fault));
Chris Craikb50c2172013-07-29 15:28:30 -07007011 }
7012}
7013
7014/* The transforms: */
7015#define ITSTRUCT(name) image_transform_##name
7016#define ITDATA(name) image_transform_data_##name
7017#define image_transform_ini image_transform_default_ini
7018#define IT(name)\
7019static image_transform ITSTRUCT(name) =\
7020{\
7021 #name,\
7022 1, /*enable*/\
7023 &PT, /*list*/\
7024 0, /*global_use*/\
7025 0, /*local_use*/\
7026 0, /*next*/\
7027 image_transform_ini,\
7028 image_transform_png_set_##name##_set,\
7029 image_transform_png_set_##name##_mod,\
7030 image_transform_png_set_##name##_add\
7031}
7032#define PT ITSTRUCT(end) /* stores the previous transform */
7033
7034/* To save code: */
Matt Sarett9b1fe632015-11-25 10:21:17 -05007035extern void image_transform_default_ini(const image_transform *this,
7036 transform_display *that); /* silence GCC warnings */
7037
7038void /* private, but almost always needed */
7039image_transform_default_ini(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007040 transform_display *that)
7041{
7042 this->next->ini(this->next, that);
7043}
7044
7045#ifdef PNG_READ_BACKGROUND_SUPPORTED
7046static int
7047image_transform_default_add(image_transform *this,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007048 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07007049{
7050 UNUSED(colour_type)
7051 UNUSED(bit_depth)
7052
7053 this->next = *that;
7054 *that = this;
7055
7056 return 1;
7057}
7058#endif
7059
7060#ifdef PNG_READ_EXPAND_SUPPORTED
7061/* png_set_palette_to_rgb */
7062static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007063image_transform_png_set_palette_to_rgb_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007064 transform_display *that, png_structp pp, png_infop pi)
7065{
7066 png_set_palette_to_rgb(pp);
7067 this->next->set(this->next, that, pp, pi);
7068}
7069
7070static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007071image_transform_png_set_palette_to_rgb_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007072 image_pixel *that, png_const_structp pp,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007073 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07007074{
7075 if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
7076 image_pixel_convert_PLTE(that);
7077
7078 this->next->mod(this->next, that, pp, display);
7079}
7080
7081static int
7082image_transform_png_set_palette_to_rgb_add(image_transform *this,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007083 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07007084{
7085 UNUSED(bit_depth)
7086
7087 this->next = *that;
7088 *that = this;
7089
7090 return colour_type == PNG_COLOR_TYPE_PALETTE;
7091}
7092
7093IT(palette_to_rgb);
7094#undef PT
7095#define PT ITSTRUCT(palette_to_rgb)
7096#endif /* PNG_READ_EXPAND_SUPPORTED */
7097
7098#ifdef PNG_READ_EXPAND_SUPPORTED
7099/* png_set_tRNS_to_alpha */
7100static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007101image_transform_png_set_tRNS_to_alpha_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007102 transform_display *that, png_structp pp, png_infop pi)
7103{
7104 png_set_tRNS_to_alpha(pp);
Matt Sarett9b1fe632015-11-25 10:21:17 -05007105
7106 /* If there was a tRNS chunk that would get expanded and add an alpha
7107 * channel is_transparent must be updated:
7108 */
7109 if (that->this.has_tRNS)
7110 that->this.is_transparent = 1;
7111
Chris Craikb50c2172013-07-29 15:28:30 -07007112 this->next->set(this->next, that, pp, pi);
7113}
7114
7115static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007116image_transform_png_set_tRNS_to_alpha_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007117 image_pixel *that, png_const_structp pp,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007118 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07007119{
Matt Sarett9b1fe632015-11-25 10:21:17 -05007120#if PNG_LIBPNG_VER < 10700
Chris Craikb50c2172013-07-29 15:28:30 -07007121 /* LIBPNG BUG: this always forces palette images to RGB. */
7122 if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
7123 image_pixel_convert_PLTE(that);
Matt Sarett9b1fe632015-11-25 10:21:17 -05007124#endif
Chris Craikb50c2172013-07-29 15:28:30 -07007125
7126 /* This effectively does an 'expand' only if there is some transparency to
7127 * convert to an alpha channel.
7128 */
7129 if (that->have_tRNS)
Matt Sarett9b1fe632015-11-25 10:21:17 -05007130# if PNG_LIBPNG_VER >= 10700
7131 if (that->colour_type != PNG_COLOR_TYPE_PALETTE &&
7132 (that->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
7133# endif
7134 image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007135
Matt Sarett9b1fe632015-11-25 10:21:17 -05007136#if PNG_LIBPNG_VER < 10700
Chris Craikb50c2172013-07-29 15:28:30 -07007137 /* LIBPNG BUG: otherwise libpng still expands to 8 bits! */
7138 else
7139 {
7140 if (that->bit_depth < 8)
7141 that->bit_depth =8;
7142 if (that->sample_depth < 8)
7143 that->sample_depth = 8;
7144 }
Matt Sarett9b1fe632015-11-25 10:21:17 -05007145#endif
Chris Craikb50c2172013-07-29 15:28:30 -07007146
7147 this->next->mod(this->next, that, pp, display);
7148}
7149
7150static int
7151image_transform_png_set_tRNS_to_alpha_add(image_transform *this,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007152 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07007153{
7154 UNUSED(bit_depth)
7155
7156 this->next = *that;
7157 *that = this;
7158
7159 /* We don't know yet whether there will be a tRNS chunk, but we know that
7160 * this transformation should do nothing if there already is an alpha
Matt Sarett9b1fe632015-11-25 10:21:17 -05007161 * channel. In addition, after the bug fix in 1.7.0, there is no longer
7162 * any action on a palette image.
Chris Craikb50c2172013-07-29 15:28:30 -07007163 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05007164 return
7165# if PNG_LIBPNG_VER >= 10700
7166 colour_type != PNG_COLOR_TYPE_PALETTE &&
7167# endif
7168 (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
Chris Craikb50c2172013-07-29 15:28:30 -07007169}
7170
7171IT(tRNS_to_alpha);
7172#undef PT
7173#define PT ITSTRUCT(tRNS_to_alpha)
7174#endif /* PNG_READ_EXPAND_SUPPORTED */
7175
7176#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
7177/* png_set_gray_to_rgb */
7178static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007179image_transform_png_set_gray_to_rgb_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007180 transform_display *that, png_structp pp, png_infop pi)
7181{
7182 png_set_gray_to_rgb(pp);
Matt Sarett9b1fe632015-11-25 10:21:17 -05007183 /* NOTE: this doesn't result in tRNS expansion. */
Chris Craikb50c2172013-07-29 15:28:30 -07007184 this->next->set(this->next, that, pp, pi);
7185}
7186
7187static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007188image_transform_png_set_gray_to_rgb_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007189 image_pixel *that, png_const_structp pp,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007190 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07007191{
7192 /* NOTE: we can actually pend the tRNS processing at this point because we
7193 * can correctly recognize the original pixel value even though we have
7194 * mapped the one gray channel to the three RGB ones, but in fact libpng
7195 * doesn't do this, so we don't either.
7196 */
7197 if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS)
Matt Sarett9b1fe632015-11-25 10:21:17 -05007198 image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007199
7200 /* Simply expand the bit depth and alter the colour type as required. */
7201 if (that->colour_type == PNG_COLOR_TYPE_GRAY)
7202 {
7203 /* RGB images have a bit depth at least equal to '8' */
7204 if (that->bit_depth < 8)
7205 that->sample_depth = that->bit_depth = 8;
7206
7207 /* And just changing the colour type works here because the green and blue
7208 * channels are being maintained in lock-step with the red/gray:
7209 */
7210 that->colour_type = PNG_COLOR_TYPE_RGB;
7211 }
7212
7213 else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
7214 that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
7215
7216 this->next->mod(this->next, that, pp, display);
7217}
7218
7219static int
7220image_transform_png_set_gray_to_rgb_add(image_transform *this,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007221 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07007222{
7223 UNUSED(bit_depth)
7224
7225 this->next = *that;
7226 *that = this;
7227
7228 return (colour_type & PNG_COLOR_MASK_COLOR) == 0;
7229}
7230
7231IT(gray_to_rgb);
7232#undef PT
7233#define PT ITSTRUCT(gray_to_rgb)
7234#endif /* PNG_READ_GRAY_TO_RGB_SUPPORTED */
7235
7236#ifdef PNG_READ_EXPAND_SUPPORTED
7237/* png_set_expand */
7238static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007239image_transform_png_set_expand_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007240 transform_display *that, png_structp pp, png_infop pi)
7241{
7242 png_set_expand(pp);
Matt Sarett9b1fe632015-11-25 10:21:17 -05007243
7244 if (that->this.has_tRNS)
7245 that->this.is_transparent = 1;
7246
Chris Craikb50c2172013-07-29 15:28:30 -07007247 this->next->set(this->next, that, pp, pi);
7248}
7249
7250static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007251image_transform_png_set_expand_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007252 image_pixel *that, png_const_structp pp,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007253 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07007254{
7255 /* The general expand case depends on what the colour type is: */
7256 if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
7257 image_pixel_convert_PLTE(that);
7258 else if (that->bit_depth < 8) /* grayscale */
7259 that->sample_depth = that->bit_depth = 8;
7260
7261 if (that->have_tRNS)
Matt Sarett9b1fe632015-11-25 10:21:17 -05007262 image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007263
7264 this->next->mod(this->next, that, pp, display);
7265}
7266
7267static int
7268image_transform_png_set_expand_add(image_transform *this,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007269 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07007270{
7271 UNUSED(bit_depth)
7272
7273 this->next = *that;
7274 *that = this;
7275
7276 /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit
7277 * depth is at least 8 already.
7278 */
7279 return (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
7280}
7281
7282IT(expand);
7283#undef PT
7284#define PT ITSTRUCT(expand)
7285#endif /* PNG_READ_EXPAND_SUPPORTED */
7286
7287#ifdef PNG_READ_EXPAND_SUPPORTED
7288/* png_set_expand_gray_1_2_4_to_8
Matt Sarett9b1fe632015-11-25 10:21:17 -05007289 * Pre 1.7.0 LIBPNG BUG: this just does an 'expand'
Chris Craikb50c2172013-07-29 15:28:30 -07007290 */
7291static void
7292image_transform_png_set_expand_gray_1_2_4_to_8_set(
Matt Sarett9b1fe632015-11-25 10:21:17 -05007293 const image_transform *this, transform_display *that, png_structp pp,
Chris Craikb50c2172013-07-29 15:28:30 -07007294 png_infop pi)
7295{
7296 png_set_expand_gray_1_2_4_to_8(pp);
Matt Sarett9b1fe632015-11-25 10:21:17 -05007297 /* NOTE: don't expect this to expand tRNS */
Chris Craikb50c2172013-07-29 15:28:30 -07007298 this->next->set(this->next, that, pp, pi);
7299}
7300
7301static void
7302image_transform_png_set_expand_gray_1_2_4_to_8_mod(
Matt Sarett9b1fe632015-11-25 10:21:17 -05007303 const image_transform *this, image_pixel *that, png_const_structp pp,
7304 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07007305{
Matt Sarett9b1fe632015-11-25 10:21:17 -05007306#if PNG_LIBPNG_VER < 10700
Chris Craikb50c2172013-07-29 15:28:30 -07007307 image_transform_png_set_expand_mod(this, that, pp, display);
Matt Sarett9b1fe632015-11-25 10:21:17 -05007308#else
7309 /* Only expand grayscale of bit depth less than 8: */
7310 if (that->colour_type == PNG_COLOR_TYPE_GRAY &&
7311 that->bit_depth < 8)
7312 that->sample_depth = that->bit_depth = 8;
7313
7314 this->next->mod(this->next, that, pp, display);
7315#endif /* 1.7 or later */
Chris Craikb50c2172013-07-29 15:28:30 -07007316}
7317
7318static int
7319image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007320 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07007321{
Matt Sarett9b1fe632015-11-25 10:21:17 -05007322#if PNG_LIBPNG_VER < 10700
Chris Craikb50c2172013-07-29 15:28:30 -07007323 return image_transform_png_set_expand_add(this, that, colour_type,
7324 bit_depth);
Matt Sarett9b1fe632015-11-25 10:21:17 -05007325#else
7326 UNUSED(bit_depth)
7327
7328 this->next = *that;
7329 *that = this;
7330
7331 /* This should do nothing unless the color type is gray and the bit depth is
7332 * less than 8:
7333 */
7334 return colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8;
7335#endif /* 1.7 or later */
Chris Craikb50c2172013-07-29 15:28:30 -07007336}
7337
7338IT(expand_gray_1_2_4_to_8);
7339#undef PT
7340#define PT ITSTRUCT(expand_gray_1_2_4_to_8)
7341#endif /* PNG_READ_EXPAND_SUPPORTED */
7342
7343#ifdef PNG_READ_EXPAND_16_SUPPORTED
7344/* png_set_expand_16 */
7345static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007346image_transform_png_set_expand_16_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007347 transform_display *that, png_structp pp, png_infop pi)
7348{
7349 png_set_expand_16(pp);
Matt Sarett9b1fe632015-11-25 10:21:17 -05007350
7351 /* NOTE: prior to 1.7 libpng does SET_EXPAND as well, so tRNS is expanded. */
7352# if PNG_LIBPNG_VER < 10700
7353 if (that->this.has_tRNS)
7354 that->this.is_transparent = 1;
7355# endif
7356
Chris Craikb50c2172013-07-29 15:28:30 -07007357 this->next->set(this->next, that, pp, pi);
7358}
7359
7360static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007361image_transform_png_set_expand_16_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007362 image_pixel *that, png_const_structp pp,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007363 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07007364{
7365 /* Expect expand_16 to expand everything to 16 bits as a result of also
7366 * causing 'expand' to happen.
7367 */
7368 if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
7369 image_pixel_convert_PLTE(that);
7370
7371 if (that->have_tRNS)
Matt Sarett9b1fe632015-11-25 10:21:17 -05007372 image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007373
7374 if (that->bit_depth < 16)
7375 that->sample_depth = that->bit_depth = 16;
7376
7377 this->next->mod(this->next, that, pp, display);
7378}
7379
7380static int
7381image_transform_png_set_expand_16_add(image_transform *this,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007382 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07007383{
7384 UNUSED(colour_type)
7385
7386 this->next = *that;
7387 *that = this;
7388
7389 /* expand_16 does something unless the bit depth is already 16. */
7390 return bit_depth < 16;
7391}
7392
7393IT(expand_16);
7394#undef PT
7395#define PT ITSTRUCT(expand_16)
7396#endif /* PNG_READ_EXPAND_16_SUPPORTED */
7397
7398#ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED /* API added in 1.5.4 */
7399/* png_set_scale_16 */
7400static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007401image_transform_png_set_scale_16_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007402 transform_display *that, png_structp pp, png_infop pi)
7403{
7404 png_set_scale_16(pp);
Matt Sarett06f10872016-01-04 12:56:20 -05007405# if PNG_LIBPNG_VER < 10700
7406 /* libpng will limit the gamma table size: */
7407 that->max_gamma_8 = PNG_MAX_GAMMA_8;
7408# endif
Chris Craikb50c2172013-07-29 15:28:30 -07007409 this->next->set(this->next, that, pp, pi);
7410}
7411
7412static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007413image_transform_png_set_scale_16_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007414 image_pixel *that, png_const_structp pp,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007415 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07007416{
7417 if (that->bit_depth == 16)
7418 {
7419 that->sample_depth = that->bit_depth = 8;
7420 if (that->red_sBIT > 8) that->red_sBIT = 8;
7421 if (that->green_sBIT > 8) that->green_sBIT = 8;
7422 if (that->blue_sBIT > 8) that->blue_sBIT = 8;
7423 if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
7424 }
7425
7426 this->next->mod(this->next, that, pp, display);
7427}
7428
7429static int
7430image_transform_png_set_scale_16_add(image_transform *this,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007431 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07007432{
7433 UNUSED(colour_type)
7434
7435 this->next = *that;
7436 *that = this;
7437
7438 return bit_depth > 8;
7439}
7440
7441IT(scale_16);
7442#undef PT
7443#define PT ITSTRUCT(scale_16)
7444#endif /* PNG_READ_SCALE_16_TO_8_SUPPORTED (1.5.4 on) */
7445
7446#ifdef PNG_READ_16_TO_8_SUPPORTED /* the default before 1.5.4 */
7447/* png_set_strip_16 */
7448static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007449image_transform_png_set_strip_16_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007450 transform_display *that, png_structp pp, png_infop pi)
7451{
7452 png_set_strip_16(pp);
Matt Sarett06f10872016-01-04 12:56:20 -05007453# if PNG_LIBPNG_VER < 10700
7454 /* libpng will limit the gamma table size: */
7455 that->max_gamma_8 = PNG_MAX_GAMMA_8;
7456# endif
Chris Craikb50c2172013-07-29 15:28:30 -07007457 this->next->set(this->next, that, pp, pi);
7458}
7459
7460static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007461image_transform_png_set_strip_16_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007462 image_pixel *that, png_const_structp pp,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007463 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07007464{
7465 if (that->bit_depth == 16)
7466 {
7467 that->sample_depth = that->bit_depth = 8;
7468 if (that->red_sBIT > 8) that->red_sBIT = 8;
7469 if (that->green_sBIT > 8) that->green_sBIT = 8;
7470 if (that->blue_sBIT > 8) that->blue_sBIT = 8;
7471 if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
7472
7473 /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
7474 * configuration option is set. From 1.5.4 the flag is never set and the
7475 * 'scale' API (above) must be used.
7476 */
7477# ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
7478# if PNG_LIBPNG_VER >= 10504
7479# error PNG_READ_ACCURATE_SCALE should not be set
7480# endif
7481
7482 /* The strip 16 algorithm drops the low 8 bits rather than calculating
7483 * 1/257, so we need to adjust the permitted errors appropriately:
7484 * Notice that this is only relevant prior to the addition of the
7485 * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
7486 */
7487 {
Matt Sarett9b1fe632015-11-25 10:21:17 -05007488 const double d = (255-128.5)/65535;
Chris Craikb50c2172013-07-29 15:28:30 -07007489 that->rede += d;
7490 that->greene += d;
7491 that->bluee += d;
7492 that->alphae += d;
7493 }
7494# endif
7495 }
7496
7497 this->next->mod(this->next, that, pp, display);
7498}
7499
7500static int
7501image_transform_png_set_strip_16_add(image_transform *this,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007502 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07007503{
7504 UNUSED(colour_type)
7505
7506 this->next = *that;
7507 *that = this;
7508
7509 return bit_depth > 8;
7510}
7511
7512IT(strip_16);
7513#undef PT
7514#define PT ITSTRUCT(strip_16)
7515#endif /* PNG_READ_16_TO_8_SUPPORTED */
7516
7517#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
7518/* png_set_strip_alpha */
7519static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007520image_transform_png_set_strip_alpha_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007521 transform_display *that, png_structp pp, png_infop pi)
7522{
7523 png_set_strip_alpha(pp);
7524 this->next->set(this->next, that, pp, pi);
7525}
7526
7527static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007528image_transform_png_set_strip_alpha_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007529 image_pixel *that, png_const_structp pp,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007530 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07007531{
7532 if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
7533 that->colour_type = PNG_COLOR_TYPE_GRAY;
7534 else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
7535 that->colour_type = PNG_COLOR_TYPE_RGB;
7536
7537 that->have_tRNS = 0;
7538 that->alphaf = 1;
7539
7540 this->next->mod(this->next, that, pp, display);
7541}
7542
7543static int
7544image_transform_png_set_strip_alpha_add(image_transform *this,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007545 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07007546{
7547 UNUSED(bit_depth)
7548
7549 this->next = *that;
7550 *that = this;
7551
7552 return (colour_type & PNG_COLOR_MASK_ALPHA) != 0;
7553}
7554
7555IT(strip_alpha);
7556#undef PT
7557#define PT ITSTRUCT(strip_alpha)
7558#endif /* PNG_READ_STRIP_ALPHA_SUPPORTED */
7559
7560#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
7561/* png_set_rgb_to_gray(png_structp, int err_action, double red, double green)
7562 * png_set_rgb_to_gray_fixed(png_structp, int err_action, png_fixed_point red,
7563 * png_fixed_point green)
7564 * png_get_rgb_to_gray_status
7565 *
Matt Sarett9b1fe632015-11-25 10:21:17 -05007566 * The 'default' test here uses values known to be used inside libpng prior to
7567 * 1.7.0:
Chris Craikb50c2172013-07-29 15:28:30 -07007568 *
7569 * red: 6968
7570 * green: 23434
7571 * blue: 2366
7572 *
7573 * These values are being retained for compatibility, along with the somewhat
7574 * broken truncation calculation in the fast-and-inaccurate code path. Older
7575 * versions of libpng will fail the accuracy tests below because they use the
7576 * truncation algorithm everywhere.
7577 */
7578#define data ITDATA(rgb_to_gray)
7579static struct
7580{
7581 double gamma; /* File gamma to use in processing */
7582
7583 /* The following are the parameters for png_set_rgb_to_gray: */
7584# ifdef PNG_FLOATING_POINT_SUPPORTED
7585 double red_to_set;
7586 double green_to_set;
7587# else
7588 png_fixed_point red_to_set;
7589 png_fixed_point green_to_set;
7590# endif
7591
7592 /* The actual coefficients: */
7593 double red_coefficient;
7594 double green_coefficient;
7595 double blue_coefficient;
7596
7597 /* Set if the coeefficients have been overridden. */
7598 int coefficients_overridden;
7599} data;
7600
7601#undef image_transform_ini
7602#define image_transform_ini image_transform_png_set_rgb_to_gray_ini
7603static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007604image_transform_png_set_rgb_to_gray_ini(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007605 transform_display *that)
7606{
7607 png_modifier *pm = that->pm;
Matt Sarett9b1fe632015-11-25 10:21:17 -05007608 const color_encoding *e = pm->current_encoding;
Chris Craikb50c2172013-07-29 15:28:30 -07007609
7610 UNUSED(this)
7611
7612 /* Since we check the encoding this flag must be set: */
7613 pm->test_uses_encoding = 1;
7614
7615 /* If 'e' is not NULL chromaticity information is present and either a cHRM
7616 * or an sRGB chunk will be inserted.
7617 */
7618 if (e != 0)
7619 {
7620 /* Coefficients come from the encoding, but may need to be normalized to a
7621 * white point Y of 1.0
7622 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05007623 const double whiteY = e->red.Y + e->green.Y + e->blue.Y;
Chris Craikb50c2172013-07-29 15:28:30 -07007624
7625 data.red_coefficient = e->red.Y;
7626 data.green_coefficient = e->green.Y;
7627 data.blue_coefficient = e->blue.Y;
7628
7629 if (whiteY != 1)
7630 {
7631 data.red_coefficient /= whiteY;
7632 data.green_coefficient /= whiteY;
7633 data.blue_coefficient /= whiteY;
7634 }
7635 }
7636
7637 else
7638 {
7639 /* The default (built in) coeffcients, as above: */
Matt Sarett9b1fe632015-11-25 10:21:17 -05007640# if PNG_LIBPNG_VER < 10700
7641 data.red_coefficient = 6968 / 32768.;
7642 data.green_coefficient = 23434 / 32768.;
7643 data.blue_coefficient = 2366 / 32768.;
7644# else
7645 data.red_coefficient = .2126;
7646 data.green_coefficient = .7152;
7647 data.blue_coefficient = .0722;
7648# endif
Chris Craikb50c2172013-07-29 15:28:30 -07007649 }
7650
7651 data.gamma = pm->current_gamma;
7652
7653 /* If not set then the calculations assume linear encoding (implicitly): */
7654 if (data.gamma == 0)
7655 data.gamma = 1;
7656
7657 /* The arguments to png_set_rgb_to_gray can override the coefficients implied
7658 * by the color space encoding. If doing exhaustive checks do the override
7659 * in each case, otherwise do it randomly.
7660 */
7661 if (pm->test_exhaustive)
7662 {
7663 /* First time in coefficients_overridden is 0, the following sets it to 1,
7664 * so repeat if it is set. If a test fails this may mean we subsequently
7665 * skip a non-override test, ignore that.
7666 */
7667 data.coefficients_overridden = !data.coefficients_overridden;
7668 pm->repeat = data.coefficients_overridden != 0;
7669 }
7670
7671 else
7672 data.coefficients_overridden = random_choice();
7673
7674 if (data.coefficients_overridden)
7675 {
7676 /* These values override the color encoding defaults, simply use random
7677 * numbers.
7678 */
7679 png_uint_32 ru;
7680 double total;
7681
Alex Naidis7a055fd2016-10-01 12:23:07 +02007682 ru = random_u32();
Chris Craikb50c2172013-07-29 15:28:30 -07007683 data.green_coefficient = total = (ru & 0xffff) / 65535.;
7684 ru >>= 16;
7685 data.red_coefficient = (1 - total) * (ru & 0xffff) / 65535.;
7686 total += data.red_coefficient;
7687 data.blue_coefficient = 1 - total;
7688
7689# ifdef PNG_FLOATING_POINT_SUPPORTED
7690 data.red_to_set = data.red_coefficient;
7691 data.green_to_set = data.green_coefficient;
7692# else
7693 data.red_to_set = fix(data.red_coefficient);
7694 data.green_to_set = fix(data.green_coefficient);
7695# endif
7696
7697 /* The following just changes the error messages: */
7698 pm->encoding_ignored = 1;
7699 }
7700
7701 else
7702 {
7703 data.red_to_set = -1;
7704 data.green_to_set = -1;
7705 }
7706
7707 /* Adjust the error limit in the png_modifier because of the larger errors
7708 * produced in the digitization during the gamma handling.
7709 */
7710 if (data.gamma != 1) /* Use gamma tables */
7711 {
7712 if (that->this.bit_depth == 16 || pm->assume_16_bit_calculations)
7713 {
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307714 /* The computations have the form:
7715 *
7716 * r * rc + g * gc + b * bc
7717 *
7718 * Each component of which is +/-1/65535 from the gamma_to_1 table
7719 * lookup, resulting in a base error of +/-6. The gamma_from_1
7720 * conversion adds another +/-2 in the 16-bit case and
7721 * +/-(1<<(15-PNG_MAX_GAMMA_8)) in the 8-bit case.
Chris Craikb50c2172013-07-29 15:28:30 -07007722 */
Matt Sarett06f10872016-01-04 12:56:20 -05007723# if PNG_LIBPNG_VER < 10700
7724 if (that->this.bit_depth < 16)
7725 that->max_gamma_8 = PNG_MAX_GAMMA_8;
7726# endif
7727 that->pm->limit += pow(
7728 (that->this.bit_depth == 16 || that->max_gamma_8 > 14 ?
7729 8. :
7730 6. + (1<<(15-that->max_gamma_8))
7731 )/65535, data.gamma);
Chris Craikb50c2172013-07-29 15:28:30 -07007732 }
7733
7734 else
7735 {
7736 /* Rounding to 8 bits in the linear space causes massive errors which
7737 * will trigger the error check in transform_range_check. Fix that
7738 * here by taking the gamma encoding into account.
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307739 *
7740 * When DIGITIZE is set because a pre-1.7 version of libpng is being
7741 * tested allow a bigger slack.
7742 *
Matt Sarett11466862016-02-19 13:41:30 -05007743 * NOTE: this number only affects the internal limit check in pngvalid,
7744 * it has no effect on the limits applied to the libpng values.
Chris Craikb50c2172013-07-29 15:28:30 -07007745 */
Leon Scroggins III3cc83ac2017-10-06 11:02:56 -04007746#if DIGITIZE
7747 that->pm->limit += pow( 2.0/255, data.gamma);
7748#else
7749 that->pm->limit += pow( 1.0/255, data.gamma);
7750#endif
Chris Craikb50c2172013-07-29 15:28:30 -07007751 }
7752 }
7753
7754 else
7755 {
7756 /* With no gamma correction a large error comes from the truncation of the
7757 * calculation in the 8 bit case, allow for that here.
7758 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307759 if (that->this.bit_depth != 16 && !pm->assume_16_bit_calculations)
Chris Craikb50c2172013-07-29 15:28:30 -07007760 that->pm->limit += 4E-3;
7761 }
7762}
7763
7764static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007765image_transform_png_set_rgb_to_gray_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007766 transform_display *that, png_structp pp, png_infop pi)
7767{
xNombred07bb0d2020-03-10 20:17:12 +01007768 int error_action = 1; /* no error, no defines in png.h */
Chris Craikb50c2172013-07-29 15:28:30 -07007769
7770# ifdef PNG_FLOATING_POINT_SUPPORTED
7771 png_set_rgb_to_gray(pp, error_action, data.red_to_set, data.green_to_set);
7772# else
7773 png_set_rgb_to_gray_fixed(pp, error_action, data.red_to_set,
7774 data.green_to_set);
7775# endif
7776
7777# ifdef PNG_READ_cHRM_SUPPORTED
7778 if (that->pm->current_encoding != 0)
7779 {
7780 /* We have an encoding so a cHRM chunk may have been set; if so then
7781 * check that the libpng APIs give the correct (X,Y,Z) values within
7782 * some margin of error for the round trip through the chromaticity
7783 * form.
7784 */
7785# ifdef PNG_FLOATING_POINT_SUPPORTED
7786# define API_function png_get_cHRM_XYZ
7787# define API_form "FP"
7788# define API_type double
7789# define API_cvt(x) (x)
7790# else
7791# define API_function png_get_cHRM_XYZ_fixed
7792# define API_form "fixed"
7793# define API_type png_fixed_point
7794# define API_cvt(x) ((double)(x)/PNG_FP_1)
7795# endif
7796
7797 API_type rX, gX, bX;
7798 API_type rY, gY, bY;
7799 API_type rZ, gZ, bZ;
7800
7801 if ((API_function(pp, pi, &rX, &rY, &rZ, &gX, &gY, &gZ, &bX, &bY, &bZ)
7802 & PNG_INFO_cHRM) != 0)
7803 {
7804 double maxe;
Matt Sarett9b1fe632015-11-25 10:21:17 -05007805 const char *el;
Chris Craikb50c2172013-07-29 15:28:30 -07007806 color_encoding e, o;
7807
7808 /* Expect libpng to return a normalized result, but the original
7809 * color space encoding may not be normalized.
7810 */
7811 modifier_current_encoding(that->pm, &o);
7812 normalize_color_encoding(&o);
7813
7814 /* Sanity check the pngvalid code - the coefficients should match
7815 * the normalized Y values of the encoding unless they were
7816 * overridden.
7817 */
7818 if (data.red_to_set == -1 && data.green_to_set == -1 &&
7819 (fabs(o.red.Y - data.red_coefficient) > DBL_EPSILON ||
7820 fabs(o.green.Y - data.green_coefficient) > DBL_EPSILON ||
7821 fabs(o.blue.Y - data.blue_coefficient) > DBL_EPSILON))
7822 png_error(pp, "internal pngvalid cHRM coefficient error");
7823
7824 /* Generate a colour space encoding. */
7825 e.gamma = o.gamma; /* not used */
7826 e.red.X = API_cvt(rX);
7827 e.red.Y = API_cvt(rY);
7828 e.red.Z = API_cvt(rZ);
7829 e.green.X = API_cvt(gX);
7830 e.green.Y = API_cvt(gY);
7831 e.green.Z = API_cvt(gZ);
7832 e.blue.X = API_cvt(bX);
7833 e.blue.Y = API_cvt(bY);
7834 e.blue.Z = API_cvt(bZ);
7835
7836 /* This should match the original one from the png_modifier, within
7837 * the range permitted by the libpng fixed point representation.
7838 */
7839 maxe = 0;
7840 el = "-"; /* Set to element name with error */
7841
7842# define CHECK(col,x)\
7843 {\
7844 double err = fabs(o.col.x - e.col.x);\
7845 if (err > maxe)\
7846 {\
7847 maxe = err;\
7848 el = #col "(" #x ")";\
7849 }\
7850 }
7851
7852 CHECK(red,X)
7853 CHECK(red,Y)
7854 CHECK(red,Z)
7855 CHECK(green,X)
7856 CHECK(green,Y)
7857 CHECK(green,Z)
7858 CHECK(blue,X)
7859 CHECK(blue,Y)
7860 CHECK(blue,Z)
7861
7862 /* Here in both fixed and floating cases to check the values read
7863 * from the cHRm chunk. PNG uses fixed point in the cHRM chunk, so
7864 * we can't expect better than +/-.5E-5 on the result, allow 1E-5.
7865 */
7866 if (maxe >= 1E-5)
7867 {
7868 size_t pos = 0;
7869 char buffer[256];
7870
7871 pos = safecat(buffer, sizeof buffer, pos, API_form);
7872 pos = safecat(buffer, sizeof buffer, pos, " cHRM ");
7873 pos = safecat(buffer, sizeof buffer, pos, el);
7874 pos = safecat(buffer, sizeof buffer, pos, " error: ");
7875 pos = safecatd(buffer, sizeof buffer, pos, maxe, 7);
7876 pos = safecat(buffer, sizeof buffer, pos, " ");
7877 /* Print the color space without the gamma value: */
7878 pos = safecat_color_encoding(buffer, sizeof buffer, pos, &o, 0);
7879 pos = safecat(buffer, sizeof buffer, pos, " -> ");
7880 pos = safecat_color_encoding(buffer, sizeof buffer, pos, &e, 0);
7881
7882 png_error(pp, buffer);
7883 }
7884 }
7885 }
7886# endif /* READ_cHRM */
7887
7888 this->next->set(this->next, that, pp, pi);
7889}
7890
7891static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05007892image_transform_png_set_rgb_to_gray_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07007893 image_pixel *that, png_const_structp pp,
Matt Sarett9b1fe632015-11-25 10:21:17 -05007894 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07007895{
7896 if ((that->colour_type & PNG_COLOR_MASK_COLOR) != 0)
7897 {
7898 double gray, err;
7899
Matt Sarett9b1fe632015-11-25 10:21:17 -05007900# if PNG_LIBPNG_VER < 10700
7901 if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
7902 image_pixel_convert_PLTE(that);
7903# endif
Chris Craikb50c2172013-07-29 15:28:30 -07007904
7905 /* Image now has RGB channels... */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307906# if DIGITIZE
Chris Craikb50c2172013-07-29 15:28:30 -07007907 {
Matt Sarett11466862016-02-19 13:41:30 -05007908 png_modifier *pm = display->pm;
xNombred07bb0d2020-03-10 20:17:12 +01007909 unsigned int sample_depth = that->sample_depth;
7910 unsigned int calc_depth = (pm->assume_16_bit_calculations ? 16 :
Sireesh Tripurarib478e662014-05-09 15:15:10 +05307911 sample_depth);
xNombred07bb0d2020-03-10 20:17:12 +01007912 unsigned int gamma_depth =
Matt Sarett06f10872016-01-04 12:56:20 -05007913 (sample_depth == 16 ?
7914 display->max_gamma_8 :
7915 (pm->assume_16_bit_calculations ?
7916 display->max_gamma_8 :
7917 sample_depth));
Chris Craikb50c2172013-07-29 15:28:30 -07007918 int isgray;
7919 double r, g, b;
7920 double rlo, rhi, glo, ghi, blo, bhi, graylo, grayhi;
7921
7922 /* Do this using interval arithmetic, otherwise it is too difficult to
7923 * handle the errors correctly.
7924 *
7925 * To handle the gamma correction work out the upper and lower bounds
7926 * of the digitized value. Assume rounding here - normally the values
7927 * will be identical after this operation if there is only one
7928 * transform, feel free to delete the png_error checks on this below in
7929 * the future (this is just me trying to ensure it works!)
Matt Sarett9b1fe632015-11-25 10:21:17 -05007930 *
7931 * Interval arithmetic is exact, but to implement it it must be
7932 * possible to control the floating point implementation rounding mode.
7933 * This cannot be done in ANSI-C, so instead I reduce the 'lo' values
7934 * by DBL_EPSILON and increase the 'hi' values by the same.
Chris Craikb50c2172013-07-29 15:28:30 -07007935 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05007936# define DD(v,d,r) (digitize(v*(1-DBL_EPSILON), d, r) * (1-DBL_EPSILON))
7937# define DU(v,d,r) (digitize(v*(1+DBL_EPSILON), d, r) * (1+DBL_EPSILON))
7938
Chris Craikb50c2172013-07-29 15:28:30 -07007939 r = rlo = rhi = that->redf;
7940 rlo -= that->rede;
Matt Sarett9b1fe632015-11-25 10:21:17 -05007941 rlo = DD(rlo, calc_depth, 1/*round*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007942 rhi += that->rede;
Matt Sarett9b1fe632015-11-25 10:21:17 -05007943 rhi = DU(rhi, calc_depth, 1/*round*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007944
7945 g = glo = ghi = that->greenf;
7946 glo -= that->greene;
Matt Sarett9b1fe632015-11-25 10:21:17 -05007947 glo = DD(glo, calc_depth, 1/*round*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007948 ghi += that->greene;
Matt Sarett9b1fe632015-11-25 10:21:17 -05007949 ghi = DU(ghi, calc_depth, 1/*round*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007950
7951 b = blo = bhi = that->bluef;
7952 blo -= that->bluee;
Matt Sarett9b1fe632015-11-25 10:21:17 -05007953 blo = DD(blo, calc_depth, 1/*round*/);
Matt Sarett06f10872016-01-04 12:56:20 -05007954 bhi += that->bluee;
Matt Sarett9b1fe632015-11-25 10:21:17 -05007955 bhi = DU(bhi, calc_depth, 1/*round*/);
Chris Craikb50c2172013-07-29 15:28:30 -07007956
7957 isgray = r==g && g==b;
7958
7959 if (data.gamma != 1)
7960 {
Matt Sarett9b1fe632015-11-25 10:21:17 -05007961 const double power = 1/data.gamma;
7962 const double abse = .5/(sample_depth == 16 ? 65535 : 255);
Chris Craikb50c2172013-07-29 15:28:30 -07007963
Matt Sarett9b1fe632015-11-25 10:21:17 -05007964 /* If a gamma calculation is done it is done using lookup tables of
7965 * precision gamma_depth, so the already digitized value above may
7966 * need to be further digitized here.
Chris Craikb50c2172013-07-29 15:28:30 -07007967 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05007968 if (gamma_depth != calc_depth)
7969 {
7970 rlo = DD(rlo, gamma_depth, 0/*truncate*/);
7971 rhi = DU(rhi, gamma_depth, 0/*truncate*/);
7972 glo = DD(glo, gamma_depth, 0/*truncate*/);
7973 ghi = DU(ghi, gamma_depth, 0/*truncate*/);
7974 blo = DD(blo, gamma_depth, 0/*truncate*/);
7975 bhi = DU(bhi, gamma_depth, 0/*truncate*/);
7976 }
7977
7978 /* 'abse' is the error in the gamma table calculation itself. */
Chris Craikb50c2172013-07-29 15:28:30 -07007979 r = pow(r, power);
Matt Sarett9b1fe632015-11-25 10:21:17 -05007980 rlo = DD(pow(rlo, power)-abse, calc_depth, 1);
7981 rhi = DU(pow(rhi, power)+abse, calc_depth, 1);
Chris Craikb50c2172013-07-29 15:28:30 -07007982
7983 g = pow(g, power);
Matt Sarett9b1fe632015-11-25 10:21:17 -05007984 glo = DD(pow(glo, power)-abse, calc_depth, 1);
7985 ghi = DU(pow(ghi, power)+abse, calc_depth, 1);
Chris Craikb50c2172013-07-29 15:28:30 -07007986
7987 b = pow(b, power);
Matt Sarett9b1fe632015-11-25 10:21:17 -05007988 blo = DD(pow(blo, power)-abse, calc_depth, 1);
7989 bhi = DU(pow(bhi, power)+abse, calc_depth, 1);
Chris Craikb50c2172013-07-29 15:28:30 -07007990 }
7991
7992 /* Now calculate the actual gray values. Although the error in the
7993 * coefficients depends on whether they were specified on the command
7994 * line (in which case truncation to 15 bits happened) or not (rounding
xNombred07bb0d2020-03-10 20:17:12 +01007995 * was used) the maximum error in an individual coefficient is always
Matt Sarett9b1fe632015-11-25 10:21:17 -05007996 * 2/32768, because even in the rounding case the requirement that
Chris Craikb50c2172013-07-29 15:28:30 -07007997 * coefficients add up to 32768 can cause a larger rounding error.
7998 *
7999 * The only time when rounding doesn't occur in 1.5.5 and later is when
8000 * the non-gamma code path is used for less than 16 bit data.
8001 */
8002 gray = r * data.red_coefficient + g * data.green_coefficient +
8003 b * data.blue_coefficient;
8004
8005 {
xNombred07bb0d2020-03-10 20:17:12 +01008006 int do_round = data.gamma != 1 || calc_depth == 16;
Matt Sarett9b1fe632015-11-25 10:21:17 -05008007 const double ce = 2. / 32768;
Chris Craikb50c2172013-07-29 15:28:30 -07008008
Matt Sarett9b1fe632015-11-25 10:21:17 -05008009 graylo = DD(rlo * (data.red_coefficient-ce) +
Chris Craikb50c2172013-07-29 15:28:30 -07008010 glo * (data.green_coefficient-ce) +
Matt Sarett9b1fe632015-11-25 10:21:17 -05008011 blo * (data.blue_coefficient-ce), calc_depth, do_round);
8012 if (graylo > gray) /* always accept the right answer */
8013 graylo = gray;
Chris Craikb50c2172013-07-29 15:28:30 -07008014
Matt Sarett9b1fe632015-11-25 10:21:17 -05008015 grayhi = DU(rhi * (data.red_coefficient+ce) +
Chris Craikb50c2172013-07-29 15:28:30 -07008016 ghi * (data.green_coefficient+ce) +
Matt Sarett9b1fe632015-11-25 10:21:17 -05008017 bhi * (data.blue_coefficient+ce), calc_depth, do_round);
8018 if (grayhi < gray)
8019 grayhi = gray;
Chris Craikb50c2172013-07-29 15:28:30 -07008020 }
8021
8022 /* And invert the gamma. */
8023 if (data.gamma != 1)
8024 {
Matt Sarett9b1fe632015-11-25 10:21:17 -05008025 const double power = data.gamma;
8026
8027 /* And this happens yet again, shifting the values once more. */
8028 if (gamma_depth != sample_depth)
8029 {
8030 rlo = DD(rlo, gamma_depth, 0/*truncate*/);
8031 rhi = DU(rhi, gamma_depth, 0/*truncate*/);
8032 glo = DD(glo, gamma_depth, 0/*truncate*/);
8033 ghi = DU(ghi, gamma_depth, 0/*truncate*/);
8034 blo = DD(blo, gamma_depth, 0/*truncate*/);
8035 bhi = DU(bhi, gamma_depth, 0/*truncate*/);
8036 }
Chris Craikb50c2172013-07-29 15:28:30 -07008037
8038 gray = pow(gray, power);
Matt Sarett9b1fe632015-11-25 10:21:17 -05008039 graylo = DD(pow(graylo, power), sample_depth, 1);
8040 grayhi = DU(pow(grayhi, power), sample_depth, 1);
Chris Craikb50c2172013-07-29 15:28:30 -07008041 }
8042
Matt Sarett9b1fe632015-11-25 10:21:17 -05008043# undef DD
8044# undef DU
8045
Chris Craikb50c2172013-07-29 15:28:30 -07008046 /* Now the error can be calculated.
8047 *
8048 * If r==g==b because there is no overall gamma correction libpng
8049 * currently preserves the original value.
8050 */
8051 if (isgray)
8052 err = (that->rede + that->greene + that->bluee)/3;
8053
8054 else
8055 {
8056 err = fabs(grayhi-gray);
Matt Sarett11466862016-02-19 13:41:30 -05008057
Chris Craikb50c2172013-07-29 15:28:30 -07008058 if (fabs(gray - graylo) > err)
8059 err = fabs(graylo-gray);
8060
Matt Sarett11466862016-02-19 13:41:30 -05008061#if !RELEASE_BUILD
Chris Craikb50c2172013-07-29 15:28:30 -07008062 /* Check that this worked: */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308063 if (err > pm->limit)
Chris Craikb50c2172013-07-29 15:28:30 -07008064 {
8065 size_t pos = 0;
8066 char buffer[128];
8067
8068 pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
8069 pos = safecatd(buffer, sizeof buffer, pos, err, 6);
8070 pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308071 pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
Matt Sarett11466862016-02-19 13:41:30 -05008072 png_warning(pp, buffer);
8073 pm->limit = err;
Chris Craikb50c2172013-07-29 15:28:30 -07008074 }
Matt Sarett11466862016-02-19 13:41:30 -05008075#endif /* !RELEASE_BUILD */
Chris Craikb50c2172013-07-29 15:28:30 -07008076 }
8077 }
Matt Sarett11466862016-02-19 13:41:30 -05008078# else /* !DIGITIZE */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308079 {
8080 double r = that->redf;
8081 double re = that->rede;
8082 double g = that->greenf;
8083 double ge = that->greene;
8084 double b = that->bluef;
8085 double be = that->bluee;
8086
Matt Sarett9b1fe632015-11-25 10:21:17 -05008087# if PNG_LIBPNG_VER < 10700
8088 /* The true gray case involves no math in earlier versions (not
8089 * true, there was some if gamma correction was happening too.)
8090 */
8091 if (r == g && r == b)
8092 {
8093 gray = r;
8094 err = re;
8095 if (err < ge) err = ge;
8096 if (err < be) err = be;
8097 }
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308098
Matt Sarett9b1fe632015-11-25 10:21:17 -05008099 else
8100# endif /* before 1.7 */
8101 if (data.gamma == 1)
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308102 {
8103 /* There is no need to do the conversions to and from linear space,
8104 * so the calculation should be a lot more accurate. There is a
Matt Sarett9b1fe632015-11-25 10:21:17 -05008105 * built in error in the coefficients because they only have 15 bits
8106 * and are adjusted to make sure they add up to 32768. This
8107 * involves a integer calculation with truncation of the form:
8108 *
8109 * ((int)(coefficient * 100000) * 32768)/100000
8110 *
8111 * This is done to the red and green coefficients (the ones
8112 * provided to the API) then blue is calculated from them so the
8113 * result adds up to 32768. In the worst case this can result in
8114 * a -1 error in red and green and a +2 error in blue. Consequently
8115 * the worst case in the calculation below is 2/32768 error.
8116 *
8117 * TODO: consider fixing this in libpng by rounding the calculation
8118 * limiting the error to 1/32768.
8119 *
8120 * Handling this by adding 2/32768 here avoids needing to increase
8121 * the global error limits to take this into account.)
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308122 */
8123 gray = r * data.red_coefficient + g * data.green_coefficient +
8124 b * data.blue_coefficient;
8125 err = re * data.red_coefficient + ge * data.green_coefficient +
Matt Sarett9b1fe632015-11-25 10:21:17 -05008126 be * data.blue_coefficient + 2./32768 + gray * 5 * DBL_EPSILON;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308127 }
8128
8129 else
8130 {
8131 /* The calculation happens in linear space, and this produces much
8132 * wider errors in the encoded space. These are handled here by
8133 * factoring the errors in to the calculation. There are two table
8134 * lookups in the calculation and each introduces a quantization
8135 * error defined by the table size.
8136 */
Matt Sarett11466862016-02-19 13:41:30 -05008137 png_modifier *pm = display->pm;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308138 double in_qe = (that->sample_depth > 8 ? .5/65535 : .5/255);
8139 double out_qe = (that->sample_depth > 8 ? .5/65535 :
Matt Sarett06f10872016-01-04 12:56:20 -05008140 (pm->assume_16_bit_calculations ? .5/(1<<display->max_gamma_8) :
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308141 .5/255));
8142 double rhi, ghi, bhi, grayhi;
8143 double g1 = 1/data.gamma;
8144
8145 rhi = r + re + in_qe; if (rhi > 1) rhi = 1;
8146 r -= re + in_qe; if (r < 0) r = 0;
8147 ghi = g + ge + in_qe; if (ghi > 1) ghi = 1;
8148 g -= ge + in_qe; if (g < 0) g = 0;
8149 bhi = b + be + in_qe; if (bhi > 1) bhi = 1;
8150 b -= be + in_qe; if (b < 0) b = 0;
8151
8152 r = pow(r, g1)*(1-DBL_EPSILON); rhi = pow(rhi, g1)*(1+DBL_EPSILON);
8153 g = pow(g, g1)*(1-DBL_EPSILON); ghi = pow(ghi, g1)*(1+DBL_EPSILON);
8154 b = pow(b, g1)*(1-DBL_EPSILON); bhi = pow(bhi, g1)*(1+DBL_EPSILON);
8155
8156 /* Work out the lower and upper bounds for the gray value in the
8157 * encoded space, then work out an average and error. Remove the
8158 * previously added input quantization error at this point.
8159 */
8160 gray = r * data.red_coefficient + g * data.green_coefficient +
Matt Sarett9b1fe632015-11-25 10:21:17 -05008161 b * data.blue_coefficient - 2./32768 - out_qe;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308162 if (gray <= 0)
8163 gray = 0;
8164 else
8165 {
8166 gray *= (1 - 6 * DBL_EPSILON);
8167 gray = pow(gray, data.gamma) * (1-DBL_EPSILON);
8168 }
8169
8170 grayhi = rhi * data.red_coefficient + ghi * data.green_coefficient +
Matt Sarett9b1fe632015-11-25 10:21:17 -05008171 bhi * data.blue_coefficient + 2./32768 + out_qe;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308172 grayhi *= (1 + 6 * DBL_EPSILON);
8173 if (grayhi >= 1)
8174 grayhi = 1;
8175 else
8176 grayhi = pow(grayhi, data.gamma) * (1+DBL_EPSILON);
8177
8178 err = (grayhi - gray) / 2;
8179 gray = (grayhi + gray) / 2;
8180
8181 if (err <= in_qe)
8182 err = gray * DBL_EPSILON;
8183
8184 else
8185 err -= in_qe;
8186
Matt Sarett11466862016-02-19 13:41:30 -05008187#if !RELEASE_BUILD
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308188 /* Validate that the error is within limits (this has caused
8189 * problems before, it's much easier to detect them here.)
8190 */
8191 if (err > pm->limit)
8192 {
8193 size_t pos = 0;
8194 char buffer[128];
8195
8196 pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
8197 pos = safecatd(buffer, sizeof buffer, pos, err, 6);
8198 pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
8199 pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
Matt Sarett11466862016-02-19 13:41:30 -05008200 png_warning(pp, buffer);
8201 pm->limit = err;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308202 }
Matt Sarett11466862016-02-19 13:41:30 -05008203#endif /* !RELEASE_BUILD */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308204 }
8205 }
8206# endif /* !DIGITIZE */
Chris Craikb50c2172013-07-29 15:28:30 -07008207
8208 that->bluef = that->greenf = that->redf = gray;
8209 that->bluee = that->greene = that->rede = err;
8210
xNombred07bb0d2020-03-10 20:17:12 +01008211 /* The sBIT is the minimum of the three colour channel sBITs. */
Chris Craikb50c2172013-07-29 15:28:30 -07008212 if (that->red_sBIT > that->green_sBIT)
8213 that->red_sBIT = that->green_sBIT;
8214 if (that->red_sBIT > that->blue_sBIT)
8215 that->red_sBIT = that->blue_sBIT;
8216 that->blue_sBIT = that->green_sBIT = that->red_sBIT;
8217
8218 /* And remove the colour bit in the type: */
8219 if (that->colour_type == PNG_COLOR_TYPE_RGB)
8220 that->colour_type = PNG_COLOR_TYPE_GRAY;
8221 else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
8222 that->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
8223 }
8224
8225 this->next->mod(this->next, that, pp, display);
8226}
8227
8228static int
8229image_transform_png_set_rgb_to_gray_add(image_transform *this,
Matt Sarett9b1fe632015-11-25 10:21:17 -05008230 const image_transform **that, png_byte colour_type, png_byte bit_depth)
Chris Craikb50c2172013-07-29 15:28:30 -07008231{
8232 UNUSED(bit_depth)
8233
8234 this->next = *that;
8235 *that = this;
8236
8237 return (colour_type & PNG_COLOR_MASK_COLOR) != 0;
8238}
8239
8240#undef data
8241IT(rgb_to_gray);
8242#undef PT
8243#define PT ITSTRUCT(rgb_to_gray)
8244#undef image_transform_ini
8245#define image_transform_ini image_transform_default_ini
8246#endif /* PNG_READ_RGB_TO_GRAY_SUPPORTED */
8247
8248#ifdef PNG_READ_BACKGROUND_SUPPORTED
8249/* png_set_background(png_structp, png_const_color_16p background_color,
8250 * int background_gamma_code, int need_expand, double background_gamma)
8251 * png_set_background_fixed(png_structp, png_const_color_16p background_color,
8252 * int background_gamma_code, int need_expand,
8253 * png_fixed_point background_gamma)
8254 *
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308255 * This ignores the gamma (at present.)
Chris Craikb50c2172013-07-29 15:28:30 -07008256*/
8257#define data ITDATA(background)
8258static image_pixel data;
8259
8260static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05008261image_transform_png_set_background_set(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07008262 transform_display *that, png_structp pp, png_infop pi)
8263{
8264 png_byte colour_type, bit_depth;
8265 png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308266 int expand;
Chris Craikb50c2172013-07-29 15:28:30 -07008267 png_color_16 back;
8268
8269 /* We need a background colour, because we don't know exactly what transforms
8270 * have been set we have to supply the colour in the original file format and
8271 * so we need to know what that is! The background colour is stored in the
8272 * transform_display.
8273 */
Matt Sarett11466862016-02-19 13:41:30 -05008274 R8(random_bytes);
Chris Craikb50c2172013-07-29 15:28:30 -07008275
8276 /* Read the random value, for colour type 3 the background colour is actually
8277 * expressed as a 24bit rgb, not an index.
8278 */
8279 colour_type = that->this.colour_type;
8280 if (colour_type == 3)
8281 {
8282 colour_type = PNG_COLOR_TYPE_RGB;
8283 bit_depth = 8;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308284 expand = 0; /* passing in an RGB not a pixel index */
Chris Craikb50c2172013-07-29 15:28:30 -07008285 }
8286
8287 else
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308288 {
Matt Sarett9b1fe632015-11-25 10:21:17 -05008289 if (that->this.has_tRNS)
8290 that->this.is_transparent = 1;
8291
Chris Craikb50c2172013-07-29 15:28:30 -07008292 bit_depth = that->this.bit_depth;
Sireesh Tripurarib478e662014-05-09 15:15:10 +05308293 expand = 1;
8294 }
Chris Craikb50c2172013-07-29 15:28:30 -07008295
8296 image_pixel_init(&data, random_bytes, colour_type,
Matt Sarett9b1fe632015-11-25 10:21:17 -05008297 bit_depth, 0/*x*/, 0/*unused: palette*/, NULL/*format*/);
Chris Craikb50c2172013-07-29 15:28:30 -07008298
8299 /* Extract the background colour from this image_pixel, but make sure the
8300 * unused fields of 'back' are garbage.
8301 */
Matt Sarett11466862016-02-19 13:41:30 -05008302 R8(back);
Chris Craikb50c2172013-07-29 15:28:30 -07008303
8304 if (colour_type & PNG_COLOR_MASK_COLOR)
8305 {
8306 back.red = (png_uint_16)data.red;
8307 back.green = (png_uint_16)data.green;
8308 back.blue = (png_uint_16)data.blue;
8309 }
8310
8311 else
8312 back.gray = (png_uint_16)data.red;
8313
Alex Naidis7a055fd2016-10-01 12:23:07 +02008314#ifdef PNG_FLOATING_POINT_SUPPORTED
8315 png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
8316#else
8317 png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
8318#endif
Chris Craikb50c2172013-07-29 15:28:30 -07008319
8320 this->next->set(this->next, that, pp, pi);
8321}
8322
8323static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05008324image_transform_png_set_background_mod(const image_transform *this,
Chris Craikb50c2172013-07-29 15:28:30 -07008325 image_pixel *that, png_const_structp pp,
Matt Sarett9b1fe632015-11-25 10:21:17 -05008326 const transform_display *display)
Chris Craikb50c2172013-07-29 15:28:30 -07008327{
8328 /* Check for tRNS first: */
8329 if (that->have_tRNS && that->colour_type != PNG_COLOR_TYPE_PALETTE)
Matt Sarett9b1fe632015-11-25 10:21:17 -05008330 image_pixel_add_alpha(that, &display->this, 1/*for background*/);
Chris Craikb50c2172013-07-29 15:28:30 -07008331
8332 /* This is only necessary if the alpha value is less than 1. */
8333 if (that->alphaf < 1)
8334 {
8335 /* Now we do the background calculation without any gamma correction. */
8336 if (that->alphaf <= 0)
8337 {
8338 that->redf = data.redf;
8339 that->greenf = data.greenf;
8340 that->bluef = data.bluef;
8341
8342 that->rede = data.rede;
8343 that->greene = data.greene;
8344 that->bluee = data.bluee;
8345
8346 that->red_sBIT= data.red_sBIT;
8347 that->green_sBIT= data.green_sBIT;
8348 that->blue_sBIT= data.blue_sBIT;
8349 }
8350
8351 else /* 0 < alpha < 1 */
8352 {
8353 double alf = 1 - that->alphaf;
8354
8355 that->redf = that->redf * that->alphaf + data.redf * alf;
8356 that->rede = that->rede * that->alphaf + data.rede * alf +
8357 DBL_EPSILON;
8358 that->greenf = that->greenf * that->alphaf + data.greenf * alf;
8359 that->greene = that->greene * that->alphaf + data.greene * alf +
8360 DBL_EPSILON;
8361 that->bluef = that->bluef * that->alphaf + data.bluef * alf;
8362 that->bluee = that->bluee * that->alphaf + data.bluee * alf +
8363 DBL_EPSILON;
8364 }
8365
8366 /* Remove the alpha type and set the alpha (not in that order.) */
8367 that->alphaf = 1;
8368 that->alphae = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07008369 }
8370
Matt Sarett9b1fe632015-11-25 10:21:17 -05008371 if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
8372 that->colour_type = PNG_COLOR_TYPE_RGB;
8373 else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
8374 that->colour_type = PNG_COLOR_TYPE_GRAY;
8375 /* PNG_COLOR_TYPE_PALETTE is not changed */
8376
Chris Craikb50c2172013-07-29 15:28:30 -07008377 this->next->mod(this->next, that, pp, display);
8378}
8379
8380#define image_transform_png_set_background_add image_transform_default_add
8381
8382#undef data
8383IT(background);
8384#undef PT
8385#define PT ITSTRUCT(background)
8386#endif /* PNG_READ_BACKGROUND_SUPPORTED */
8387
Matt Sarett9b1fe632015-11-25 10:21:17 -05008388/* png_set_quantize(png_structp, png_colorp palette, int num_palette,
8389 * int maximum_colors, png_const_uint_16p histogram, int full_quantize)
8390 *
8391 * Very difficult to validate this!
8392 */
8393/*NOTE: TBD NYI */
8394
8395/* The data layout transforms are handled by swapping our own channel data,
8396 * necessarily these need to happen at the end of the transform list because the
8397 * semantic of the channels changes after these are executed. Some of these,
8398 * like set_shift and set_packing, can't be done at present because they change
8399 * the layout of the data at the sub-sample level so sample() won't get the
8400 * right answer.
8401 */
8402/* png_set_invert_alpha */
8403#ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
8404/* Invert the alpha channel
8405 *
8406 * png_set_invert_alpha(png_structrp png_ptr)
8407 */
8408static void
8409image_transform_png_set_invert_alpha_set(const image_transform *this,
8410 transform_display *that, png_structp pp, png_infop pi)
8411{
8412 png_set_invert_alpha(pp);
8413 this->next->set(this->next, that, pp, pi);
8414}
Chris Craikb50c2172013-07-29 15:28:30 -07008415
8416static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05008417image_transform_png_set_invert_alpha_mod(const image_transform *this,
8418 image_pixel *that, png_const_structp pp,
8419 const transform_display *display)
8420{
8421 if (that->colour_type & 4)
8422 that->alpha_inverted = 1;
8423
8424 this->next->mod(this->next, that, pp, display);
8425}
8426
8427static int
8428image_transform_png_set_invert_alpha_add(image_transform *this,
8429 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8430{
8431 UNUSED(bit_depth)
8432
8433 this->next = *that;
8434 *that = this;
8435
8436 /* Only has an effect on pixels with alpha: */
8437 return (colour_type & 4) != 0;
8438}
8439
8440IT(invert_alpha);
8441#undef PT
8442#define PT ITSTRUCT(invert_alpha)
8443
8444#endif /* PNG_READ_INVERT_ALPHA_SUPPORTED */
8445
8446/* png_set_bgr */
8447#ifdef PNG_READ_BGR_SUPPORTED
8448/* Swap R,G,B channels to order B,G,R.
8449 *
8450 * png_set_bgr(png_structrp png_ptr)
8451 *
8452 * This only has an effect on RGB and RGBA pixels.
8453 */
8454static void
8455image_transform_png_set_bgr_set(const image_transform *this,
8456 transform_display *that, png_structp pp, png_infop pi)
8457{
8458 png_set_bgr(pp);
8459 this->next->set(this->next, that, pp, pi);
8460}
8461
8462static void
8463image_transform_png_set_bgr_mod(const image_transform *this,
8464 image_pixel *that, png_const_structp pp,
8465 const transform_display *display)
8466{
8467 if (that->colour_type == PNG_COLOR_TYPE_RGB ||
8468 that->colour_type == PNG_COLOR_TYPE_RGBA)
8469 that->swap_rgb = 1;
8470
8471 this->next->mod(this->next, that, pp, display);
8472}
8473
8474static int
8475image_transform_png_set_bgr_add(image_transform *this,
8476 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8477{
8478 UNUSED(bit_depth)
8479
8480 this->next = *that;
8481 *that = this;
8482
8483 return colour_type == PNG_COLOR_TYPE_RGB ||
8484 colour_type == PNG_COLOR_TYPE_RGBA;
8485}
8486
8487IT(bgr);
8488#undef PT
8489#define PT ITSTRUCT(bgr)
8490
8491#endif /* PNG_READ_BGR_SUPPORTED */
8492
8493/* png_set_swap_alpha */
8494#ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
8495/* Put the alpha channel first.
8496 *
8497 * png_set_swap_alpha(png_structrp png_ptr)
8498 *
8499 * This only has an effect on GA and RGBA pixels.
8500 */
8501static void
8502image_transform_png_set_swap_alpha_set(const image_transform *this,
8503 transform_display *that, png_structp pp, png_infop pi)
8504{
8505 png_set_swap_alpha(pp);
8506 this->next->set(this->next, that, pp, pi);
8507}
8508
8509static void
8510image_transform_png_set_swap_alpha_mod(const image_transform *this,
8511 image_pixel *that, png_const_structp pp,
8512 const transform_display *display)
8513{
8514 if (that->colour_type == PNG_COLOR_TYPE_GA ||
8515 that->colour_type == PNG_COLOR_TYPE_RGBA)
8516 that->alpha_first = 1;
8517
8518 this->next->mod(this->next, that, pp, display);
8519}
8520
8521static int
8522image_transform_png_set_swap_alpha_add(image_transform *this,
8523 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8524{
8525 UNUSED(bit_depth)
8526
8527 this->next = *that;
8528 *that = this;
8529
8530 return colour_type == PNG_COLOR_TYPE_GA ||
8531 colour_type == PNG_COLOR_TYPE_RGBA;
8532}
8533
8534IT(swap_alpha);
8535#undef PT
8536#define PT ITSTRUCT(swap_alpha)
8537
8538#endif /* PNG_READ_SWAP_ALPHA_SUPPORTED */
8539
8540/* png_set_swap */
8541#ifdef PNG_READ_SWAP_SUPPORTED
8542/* Byte swap 16-bit components.
8543 *
8544 * png_set_swap(png_structrp png_ptr)
8545 */
8546static void
8547image_transform_png_set_swap_set(const image_transform *this,
8548 transform_display *that, png_structp pp, png_infop pi)
8549{
8550 png_set_swap(pp);
8551 this->next->set(this->next, that, pp, pi);
8552}
8553
8554static void
8555image_transform_png_set_swap_mod(const image_transform *this,
8556 image_pixel *that, png_const_structp pp,
8557 const transform_display *display)
8558{
8559 if (that->bit_depth == 16)
8560 that->swap16 = 1;
8561
8562 this->next->mod(this->next, that, pp, display);
8563}
8564
8565static int
8566image_transform_png_set_swap_add(image_transform *this,
8567 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8568{
8569 UNUSED(colour_type)
8570
8571 this->next = *that;
8572 *that = this;
8573
8574 return bit_depth == 16;
8575}
8576
8577IT(swap);
8578#undef PT
8579#define PT ITSTRUCT(swap)
8580
8581#endif /* PNG_READ_SWAP_SUPPORTED */
8582
8583#ifdef PNG_READ_FILLER_SUPPORTED
8584/* Add a filler byte to 8-bit Gray or 24-bit RGB images.
8585 *
8586 * png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags));
8587 *
8588 * Flags:
8589 *
8590 * PNG_FILLER_BEFORE
8591 * PNG_FILLER_AFTER
8592 */
8593#define data ITDATA(filler)
8594static struct
8595{
8596 png_uint_32 filler;
8597 int flags;
8598} data;
8599
8600static void
8601image_transform_png_set_filler_set(const image_transform *this,
8602 transform_display *that, png_structp pp, png_infop pi)
8603{
8604 /* Need a random choice for 'before' and 'after' as well as for the
8605 * filler. The 'filler' value has all 32 bits set, but only bit_depth
8606 * will be used. At this point we don't know bit_depth.
8607 */
Alex Naidis7a055fd2016-10-01 12:23:07 +02008608 data.filler = random_u32();
Matt Sarett9b1fe632015-11-25 10:21:17 -05008609 data.flags = random_choice();
8610
8611 png_set_filler(pp, data.filler, data.flags);
8612
8613 /* The standard display handling stuff also needs to know that
8614 * there is a filler, so set that here.
8615 */
8616 that->this.filler = 1;
8617
8618 this->next->set(this->next, that, pp, pi);
8619}
8620
8621static void
8622image_transform_png_set_filler_mod(const image_transform *this,
8623 image_pixel *that, png_const_structp pp,
8624 const transform_display *display)
8625{
8626 if (that->bit_depth >= 8 &&
8627 (that->colour_type == PNG_COLOR_TYPE_RGB ||
8628 that->colour_type == PNG_COLOR_TYPE_GRAY))
8629 {
xNombred07bb0d2020-03-10 20:17:12 +01008630 unsigned int max = (1U << that->bit_depth)-1;
Matt Sarett9b1fe632015-11-25 10:21:17 -05008631 that->alpha = data.filler & max;
8632 that->alphaf = ((double)that->alpha) / max;
8633 that->alphae = 0;
8634
8635 /* The filler has been stored in the alpha channel, we must record
8636 * that this has been done for the checking later on, the color
8637 * type is faked to have an alpha channel, but libpng won't report
8638 * this; the app has to know the extra channel is there and this
8639 * was recording in standard_display::filler above.
8640 */
8641 that->colour_type |= 4; /* alpha added */
8642 that->alpha_first = data.flags == PNG_FILLER_BEFORE;
8643 }
8644
8645 this->next->mod(this->next, that, pp, display);
8646}
8647
8648static int
8649image_transform_png_set_filler_add(image_transform *this,
8650 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8651{
8652 this->next = *that;
8653 *that = this;
8654
8655 return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
8656 colour_type == PNG_COLOR_TYPE_GRAY);
8657}
8658
8659#undef data
8660IT(filler);
8661#undef PT
8662#define PT ITSTRUCT(filler)
8663
8664/* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */
8665/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
8666#define data ITDATA(add_alpha)
8667static struct
8668{
8669 png_uint_32 filler;
8670 int flags;
8671} data;
8672
8673static void
8674image_transform_png_set_add_alpha_set(const image_transform *this,
8675 transform_display *that, png_structp pp, png_infop pi)
8676{
8677 /* Need a random choice for 'before' and 'after' as well as for the
8678 * filler. The 'filler' value has all 32 bits set, but only bit_depth
8679 * will be used. At this point we don't know bit_depth.
8680 */
Alex Naidis7a055fd2016-10-01 12:23:07 +02008681 data.filler = random_u32();
Matt Sarett9b1fe632015-11-25 10:21:17 -05008682 data.flags = random_choice();
8683
8684 png_set_add_alpha(pp, data.filler, data.flags);
8685 this->next->set(this->next, that, pp, pi);
8686}
8687
8688static void
8689image_transform_png_set_add_alpha_mod(const image_transform *this,
8690 image_pixel *that, png_const_structp pp,
8691 const transform_display *display)
8692{
8693 if (that->bit_depth >= 8 &&
8694 (that->colour_type == PNG_COLOR_TYPE_RGB ||
8695 that->colour_type == PNG_COLOR_TYPE_GRAY))
8696 {
xNombred07bb0d2020-03-10 20:17:12 +01008697 unsigned int max = (1U << that->bit_depth)-1;
Matt Sarett9b1fe632015-11-25 10:21:17 -05008698 that->alpha = data.filler & max;
8699 that->alphaf = ((double)that->alpha) / max;
8700 that->alphae = 0;
8701
8702 that->colour_type |= 4; /* alpha added */
8703 that->alpha_first = data.flags == PNG_FILLER_BEFORE;
8704 }
8705
8706 this->next->mod(this->next, that, pp, display);
8707}
8708
8709static int
8710image_transform_png_set_add_alpha_add(image_transform *this,
8711 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8712{
8713 this->next = *that;
8714 *that = this;
8715
8716 return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
8717 colour_type == PNG_COLOR_TYPE_GRAY);
8718}
8719
8720#undef data
8721IT(add_alpha);
8722#undef PT
8723#define PT ITSTRUCT(add_alpha)
8724
8725#endif /* PNG_READ_FILLER_SUPPORTED */
8726
8727/* png_set_packing */
8728#ifdef PNG_READ_PACK_SUPPORTED
8729/* Use 1 byte per pixel in 1, 2, or 4-bit depth files.
8730 *
8731 * png_set_packing(png_structrp png_ptr)
8732 *
8733 * This should only affect grayscale and palette images with less than 8 bits
8734 * per pixel.
8735 */
8736static void
8737image_transform_png_set_packing_set(const image_transform *this,
8738 transform_display *that, png_structp pp, png_infop pi)
8739{
8740 png_set_packing(pp);
8741 that->unpacked = 1;
8742 this->next->set(this->next, that, pp, pi);
8743}
8744
8745static void
8746image_transform_png_set_packing_mod(const image_transform *this,
8747 image_pixel *that, png_const_structp pp,
8748 const transform_display *display)
8749{
8750 /* The general expand case depends on what the colour type is,
8751 * low bit-depth pixel values are unpacked into bytes without
8752 * scaling, so sample_depth is not changed.
8753 */
8754 if (that->bit_depth < 8) /* grayscale or palette */
8755 that->bit_depth = 8;
8756
8757 this->next->mod(this->next, that, pp, display);
8758}
8759
8760static int
8761image_transform_png_set_packing_add(image_transform *this,
8762 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8763{
8764 UNUSED(colour_type)
8765
8766 this->next = *that;
8767 *that = this;
8768
8769 /* Nothing should happen unless the bit depth is less than 8: */
8770 return bit_depth < 8;
8771}
8772
8773IT(packing);
8774#undef PT
8775#define PT ITSTRUCT(packing)
8776
8777#endif /* PNG_READ_PACK_SUPPORTED */
8778
8779/* png_set_packswap */
8780#ifdef PNG_READ_PACKSWAP_SUPPORTED
8781/* Swap pixels packed into bytes; reverses the order on screen so that
8782 * the high order bits correspond to the rightmost pixels.
8783 *
8784 * png_set_packswap(png_structrp png_ptr)
8785 */
8786static void
8787image_transform_png_set_packswap_set(const image_transform *this,
8788 transform_display *that, png_structp pp, png_infop pi)
8789{
8790 png_set_packswap(pp);
Matt Sarett06f10872016-01-04 12:56:20 -05008791 that->this.littleendian = 1;
Matt Sarett9b1fe632015-11-25 10:21:17 -05008792 this->next->set(this->next, that, pp, pi);
8793}
8794
8795static void
8796image_transform_png_set_packswap_mod(const image_transform *this,
8797 image_pixel *that, png_const_structp pp,
8798 const transform_display *display)
8799{
8800 if (that->bit_depth < 8)
8801 that->littleendian = 1;
8802
8803 this->next->mod(this->next, that, pp, display);
8804}
8805
8806static int
8807image_transform_png_set_packswap_add(image_transform *this,
8808 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8809{
8810 UNUSED(colour_type)
8811
8812 this->next = *that;
8813 *that = this;
8814
8815 return bit_depth < 8;
8816}
8817
8818IT(packswap);
8819#undef PT
8820#define PT ITSTRUCT(packswap)
8821
8822#endif /* PNG_READ_PACKSWAP_SUPPORTED */
8823
8824
8825/* png_set_invert_mono */
8826#ifdef PNG_READ_INVERT_MONO_SUPPORTED
8827/* Invert the gray channel
8828 *
8829 * png_set_invert_mono(png_structrp png_ptr)
8830 */
8831static void
8832image_transform_png_set_invert_mono_set(const image_transform *this,
8833 transform_display *that, png_structp pp, png_infop pi)
8834{
8835 png_set_invert_mono(pp);
8836 this->next->set(this->next, that, pp, pi);
8837}
8838
8839static void
8840image_transform_png_set_invert_mono_mod(const image_transform *this,
8841 image_pixel *that, png_const_structp pp,
8842 const transform_display *display)
8843{
8844 if (that->colour_type & 4)
8845 that->mono_inverted = 1;
8846
8847 this->next->mod(this->next, that, pp, display);
8848}
8849
8850static int
8851image_transform_png_set_invert_mono_add(image_transform *this,
8852 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8853{
8854 UNUSED(bit_depth)
8855
8856 this->next = *that;
8857 *that = this;
8858
8859 /* Only has an effect on pixels with no colour: */
8860 return (colour_type & 2) == 0;
8861}
8862
8863IT(invert_mono);
8864#undef PT
8865#define PT ITSTRUCT(invert_mono)
8866
8867#endif /* PNG_READ_INVERT_MONO_SUPPORTED */
8868
8869#ifdef PNG_READ_SHIFT_SUPPORTED
8870/* png_set_shift(png_structp, png_const_color_8p true_bits)
8871 *
8872 * The output pixels will be shifted by the given true_bits
8873 * values.
8874 */
8875#define data ITDATA(shift)
8876static png_color_8 data;
8877
8878static void
8879image_transform_png_set_shift_set(const image_transform *this,
8880 transform_display *that, png_structp pp, png_infop pi)
8881{
8882 /* Get a random set of shifts. The shifts need to do something
8883 * to test the transform, so they are limited to the bit depth
8884 * of the input image. Notice that in the following the 'gray'
8885 * field is randomized independently. This acts as a check that
8886 * libpng does use the correct field.
8887 */
xNombred07bb0d2020-03-10 20:17:12 +01008888 unsigned int depth = that->this.bit_depth;
Matt Sarett9b1fe632015-11-25 10:21:17 -05008889
8890 data.red = (png_byte)/*SAFE*/(random_mod(depth)+1);
8891 data.green = (png_byte)/*SAFE*/(random_mod(depth)+1);
8892 data.blue = (png_byte)/*SAFE*/(random_mod(depth)+1);
8893 data.gray = (png_byte)/*SAFE*/(random_mod(depth)+1);
8894 data.alpha = (png_byte)/*SAFE*/(random_mod(depth)+1);
8895
8896 png_set_shift(pp, &data);
8897 this->next->set(this->next, that, pp, pi);
8898}
8899
8900static void
8901image_transform_png_set_shift_mod(const image_transform *this,
8902 image_pixel *that, png_const_structp pp,
8903 const transform_display *display)
8904{
8905 /* Copy the correct values into the sBIT fields, libpng does not do
8906 * anything to palette data:
8907 */
8908 if (that->colour_type != PNG_COLOR_TYPE_PALETTE)
8909 {
8910 that->sig_bits = 1;
8911
8912 /* The sBIT fields are reset to the values previously sent to
8913 * png_set_shift according to the colour type.
8914 * does.
8915 */
8916 if (that->colour_type & 2) /* RGB channels */
8917 {
8918 that->red_sBIT = data.red;
8919 that->green_sBIT = data.green;
8920 that->blue_sBIT = data.blue;
8921 }
8922
8923 else /* One grey channel */
8924 that->red_sBIT = that->green_sBIT = that->blue_sBIT = data.gray;
8925
8926 that->alpha_sBIT = data.alpha;
8927 }
8928
8929 this->next->mod(this->next, that, pp, display);
8930}
8931
8932static int
8933image_transform_png_set_shift_add(image_transform *this,
8934 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8935{
8936 UNUSED(bit_depth)
8937
8938 this->next = *that;
8939 *that = this;
8940
8941 return colour_type != PNG_COLOR_TYPE_PALETTE;
8942}
8943
8944IT(shift);
8945#undef PT
8946#define PT ITSTRUCT(shift)
8947
8948#endif /* PNG_READ_SHIFT_SUPPORTED */
8949
8950#ifdef THIS_IS_THE_PROFORMA
8951static void
8952image_transform_png_set_@_set(const image_transform *this,
8953 transform_display *that, png_structp pp, png_infop pi)
8954{
8955 png_set_@(pp);
8956 this->next->set(this->next, that, pp, pi);
8957}
8958
8959static void
8960image_transform_png_set_@_mod(const image_transform *this,
8961 image_pixel *that, png_const_structp pp,
8962 const transform_display *display)
8963{
8964 this->next->mod(this->next, that, pp, display);
8965}
8966
8967static int
8968image_transform_png_set_@_add(image_transform *this,
8969 const image_transform **that, png_byte colour_type, png_byte bit_depth)
8970{
8971 this->next = *that;
8972 *that = this;
8973
8974 return 1;
8975}
8976
8977IT(@);
8978#endif
8979
8980
8981/* This may just be 'end' if all the transforms are disabled! */
8982static image_transform *const image_transform_first = &PT;
8983
8984static void
8985transform_enable(const char *name)
Chris Craikb50c2172013-07-29 15:28:30 -07008986{
8987 /* Everything starts out enabled, so if we see an 'enable' disabled
8988 * everything else the first time round.
8989 */
8990 static int all_disabled = 0;
8991 int found_it = 0;
8992 image_transform *list = image_transform_first;
8993
8994 while (list != &image_transform_end)
8995 {
8996 if (strcmp(list->name, name) == 0)
8997 {
8998 list->enable = 1;
8999 found_it = 1;
9000 }
9001 else if (!all_disabled)
9002 list->enable = 0;
9003
9004 list = list->list;
9005 }
9006
9007 all_disabled = 1;
9008
9009 if (!found_it)
9010 {
9011 fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n",
9012 name);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309013 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -07009014 }
9015}
9016
9017static void
Matt Sarett9b1fe632015-11-25 10:21:17 -05009018transform_disable(const char *name)
Chris Craikb50c2172013-07-29 15:28:30 -07009019{
9020 image_transform *list = image_transform_first;
9021
9022 while (list != &image_transform_end)
9023 {
9024 if (strcmp(list->name, name) == 0)
9025 {
9026 list->enable = 0;
9027 return;
9028 }
9029
9030 list = list->list;
9031 }
9032
9033 fprintf(stderr, "pngvalid: --transform-disable=%s: unknown transform\n",
9034 name);
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309035 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -07009036}
9037
9038static void
9039image_transform_reset_count(void)
9040{
9041 image_transform *next = image_transform_first;
9042 int count = 0;
9043
9044 while (next != &image_transform_end)
9045 {
9046 next->local_use = 0;
9047 next->next = 0;
9048 next = next->list;
9049 ++count;
9050 }
9051
9052 /* This can only happen if we every have more than 32 transforms (excluding
9053 * the end) in the list.
9054 */
9055 if (count > 32) abort();
9056}
9057
9058static int
9059image_transform_test_counter(png_uint_32 counter, unsigned int max)
9060{
9061 /* Test the list to see if there is any point contining, given a current
9062 * counter and a 'max' value.
9063 */
9064 image_transform *next = image_transform_first;
9065
9066 while (next != &image_transform_end)
9067 {
9068 /* For max 0 or 1 continue until the counter overflows: */
9069 counter >>= 1;
9070
9071 /* Continue if any entry hasn't reacked the max. */
9072 if (max > 1 && next->local_use < max)
9073 return 1;
9074 next = next->list;
9075 }
9076
9077 return max <= 1 && counter == 0;
9078}
9079
9080static png_uint_32
Matt Sarett9b1fe632015-11-25 10:21:17 -05009081image_transform_add(const image_transform **this, unsigned int max,
Chris Craikb50c2172013-07-29 15:28:30 -07009082 png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos,
9083 png_byte colour_type, png_byte bit_depth)
9084{
9085 for (;;) /* until we manage to add something */
9086 {
9087 png_uint_32 mask;
9088 image_transform *list;
9089
9090 /* Find the next counter value, if the counter is zero this is the start
9091 * of the list. This routine always returns the current counter (not the
9092 * next) so it returns 0 at the end and expects 0 at the beginning.
9093 */
9094 if (counter == 0) /* first time */
9095 {
9096 image_transform_reset_count();
9097 if (max <= 1)
9098 counter = 1;
9099 else
9100 counter = random_32();
9101 }
9102 else /* advance the counter */
9103 {
9104 switch (max)
9105 {
9106 case 0: ++counter; break;
9107 case 1: counter <<= 1; break;
9108 default: counter = random_32(); break;
9109 }
9110 }
9111
9112 /* Now add all these items, if possible */
9113 *this = &image_transform_end;
9114 list = image_transform_first;
9115 mask = 1;
9116
9117 /* Go through the whole list adding anything that the counter selects: */
9118 while (list != &image_transform_end)
9119 {
9120 if ((counter & mask) != 0 && list->enable &&
9121 (max == 0 || list->local_use < max))
9122 {
9123 /* Candidate to add: */
9124 if (list->add(list, this, colour_type, bit_depth) || max == 0)
9125 {
9126 /* Added, so add to the name too. */
9127 *pos = safecat(name, sizeof_name, *pos, " +");
9128 *pos = safecat(name, sizeof_name, *pos, list->name);
9129 }
9130
9131 else
9132 {
9133 /* Not useful and max>0, so remove it from *this: */
9134 *this = list->next;
9135 list->next = 0;
9136
9137 /* And, since we know it isn't useful, stop it being added again
9138 * in this run:
9139 */
9140 list->local_use = max;
9141 }
9142 }
9143
9144 mask <<= 1;
9145 list = list->list;
9146 }
9147
9148 /* Now if anything was added we have something to do. */
9149 if (*this != &image_transform_end)
9150 return counter;
9151
9152 /* Nothing added, but was there anything in there to add? */
9153 if (!image_transform_test_counter(counter, max))
9154 return 0;
9155 }
9156}
9157
Chris Craikb50c2172013-07-29 15:28:30 -07009158static void
9159perform_transform_test(png_modifier *pm)
9160{
9161 png_byte colour_type = 0;
9162 png_byte bit_depth = 0;
9163 unsigned int palette_number = 0;
9164
Matt Sarett9b1fe632015-11-25 10:21:17 -05009165 while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg,
9166 pm->test_tRNS))
Chris Craikb50c2172013-07-29 15:28:30 -07009167 {
9168 png_uint_32 counter = 0;
9169 size_t base_pos;
9170 char name[64];
9171
9172 base_pos = safecat(name, sizeof name, 0, "transform:");
9173
9174 for (;;)
9175 {
9176 size_t pos = base_pos;
Matt Sarett9b1fe632015-11-25 10:21:17 -05009177 const image_transform *list = 0;
Chris Craikb50c2172013-07-29 15:28:30 -07009178
9179 /* 'max' is currently hardwired to '1'; this should be settable on the
9180 * command line.
9181 */
9182 counter = image_transform_add(&list, 1/*max*/, counter,
9183 name, sizeof name, &pos, colour_type, bit_depth);
9184
9185 if (counter == 0)
9186 break;
9187
9188 /* The command line can change this to checking interlaced images. */
9189 do
9190 {
9191 pm->repeat = 0;
9192 transform_test(pm, FILEID(colour_type, bit_depth, palette_number,
9193 pm->interlace_type, 0, 0, 0), list, name);
9194
9195 if (fail(pm))
9196 return;
9197 }
9198 while (pm->repeat);
9199 }
9200 }
9201}
9202#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
9203
9204/********************************* GAMMA TESTS ********************************/
9205#ifdef PNG_READ_GAMMA_SUPPORTED
9206/* Reader callbacks and implementations, where they differ from the standard
9207 * ones.
9208 */
9209typedef struct gamma_display
9210{
9211 standard_display this;
9212
9213 /* Parameters */
9214 png_modifier* pm;
9215 double file_gamma;
9216 double screen_gamma;
9217 double background_gamma;
9218 png_byte sbit;
9219 int threshold_test;
9220 int use_input_precision;
9221 int scale16;
9222 int expand16;
9223 int do_background;
9224 png_color_16 background_color;
9225
9226 /* Local variables */
9227 double maxerrout;
9228 double maxerrpc;
9229 double maxerrabs;
9230} gamma_display;
9231
9232#define ALPHA_MODE_OFFSET 4
9233
9234static void
9235gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
9236 double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
9237 int use_input_precision, int scale16, int expand16,
Matt Sarett9b1fe632015-11-25 10:21:17 -05009238 int do_background, const png_color_16 *pointer_to_the_background_color,
Chris Craikb50c2172013-07-29 15:28:30 -07009239 double background_gamma)
9240{
9241 /* Standard fields */
Matt Sarett06f10872016-01-04 12:56:20 -05009242 standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
Chris Craikb50c2172013-07-29 15:28:30 -07009243 pm->use_update_info);
9244
9245 /* Parameter fields */
9246 dp->pm = pm;
9247 dp->file_gamma = file_gamma;
9248 dp->screen_gamma = screen_gamma;
9249 dp->background_gamma = background_gamma;
9250 dp->sbit = sbit;
9251 dp->threshold_test = threshold_test;
9252 dp->use_input_precision = use_input_precision;
9253 dp->scale16 = scale16;
9254 dp->expand16 = expand16;
9255 dp->do_background = do_background;
9256 if (do_background && pointer_to_the_background_color != 0)
9257 dp->background_color = *pointer_to_the_background_color;
9258 else
9259 memset(&dp->background_color, 0, sizeof dp->background_color);
9260
9261 /* Local variable fields */
9262 dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
9263}
9264
9265static void
9266gamma_info_imp(gamma_display *dp, png_structp pp, png_infop pi)
9267{
9268 /* Reuse the standard stuff as appropriate. */
9269 standard_info_part1(&dp->this, pp, pi);
9270
9271 /* If requested strip 16 to 8 bits - this is handled automagically below
9272 * because the output bit depth is read from the library. Note that there
9273 * are interactions with sBIT but, internally, libpng makes sbit at most
Matt Sarett06f10872016-01-04 12:56:20 -05009274 * PNG_MAX_GAMMA_8 prior to 1.7 when doing the following.
Chris Craikb50c2172013-07-29 15:28:30 -07009275 */
9276 if (dp->scale16)
9277# ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
9278 png_set_scale_16(pp);
9279# else
9280 /* The following works both in 1.5.4 and earlier versions: */
9281# ifdef PNG_READ_16_TO_8_SUPPORTED
9282 png_set_strip_16(pp);
9283# else
9284 png_error(pp, "scale16 (16 to 8 bit conversion) not supported");
9285# endif
9286# endif
9287
9288 if (dp->expand16)
9289# ifdef PNG_READ_EXPAND_16_SUPPORTED
9290 png_set_expand_16(pp);
9291# else
9292 png_error(pp, "expand16 (8 to 16 bit conversion) not supported");
9293# endif
9294
9295 if (dp->do_background >= ALPHA_MODE_OFFSET)
9296 {
9297# ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9298 {
9299 /* This tests the alpha mode handling, if supported. */
9300 int mode = dp->do_background - ALPHA_MODE_OFFSET;
9301
9302 /* The gamma value is the output gamma, and is in the standard,
xNombred07bb0d2020-03-10 20:17:12 +01009303 * non-inverted, representation. It provides a default for the PNG file
Chris Craikb50c2172013-07-29 15:28:30 -07009304 * gamma, but since the file has a gAMA chunk this does not matter.
9305 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05009306 const double sg = dp->screen_gamma;
Chris Craikb50c2172013-07-29 15:28:30 -07009307# ifndef PNG_FLOATING_POINT_SUPPORTED
xNombred07bb0d2020-03-10 20:17:12 +01009308 png_fixed_point g = fix(sg);
Chris Craikb50c2172013-07-29 15:28:30 -07009309# endif
9310
9311# ifdef PNG_FLOATING_POINT_SUPPORTED
9312 png_set_alpha_mode(pp, mode, sg);
9313# else
9314 png_set_alpha_mode_fixed(pp, mode, g);
9315# endif
9316
9317 /* However, for the standard Porter-Duff algorithm the output defaults
9318 * to be linear, so if the test requires non-linear output it must be
9319 * corrected here.
9320 */
9321 if (mode == PNG_ALPHA_STANDARD && sg != 1)
9322 {
9323# ifdef PNG_FLOATING_POINT_SUPPORTED
9324 png_set_gamma(pp, sg, dp->file_gamma);
9325# else
9326 png_fixed_point f = fix(dp->file_gamma);
9327 png_set_gamma_fixed(pp, g, f);
9328# endif
9329 }
9330 }
9331# else
9332 png_error(pp, "alpha mode handling not supported");
9333# endif
9334 }
9335
9336 else
9337 {
9338 /* Set up gamma processing. */
9339# ifdef PNG_FLOATING_POINT_SUPPORTED
9340 png_set_gamma(pp, dp->screen_gamma, dp->file_gamma);
9341# else
9342 {
9343 png_fixed_point s = fix(dp->screen_gamma);
9344 png_fixed_point f = fix(dp->file_gamma);
9345 png_set_gamma_fixed(pp, s, f);
9346 }
9347# endif
9348
9349 if (dp->do_background)
9350 {
9351# ifdef PNG_READ_BACKGROUND_SUPPORTED
9352 /* NOTE: this assumes the caller provided the correct background gamma!
9353 */
Matt Sarett9b1fe632015-11-25 10:21:17 -05009354 const double bg = dp->background_gamma;
Chris Craikb50c2172013-07-29 15:28:30 -07009355# ifndef PNG_FLOATING_POINT_SUPPORTED
xNombred07bb0d2020-03-10 20:17:12 +01009356 png_fixed_point g = fix(bg);
Chris Craikb50c2172013-07-29 15:28:30 -07009357# endif
9358
9359# ifdef PNG_FLOATING_POINT_SUPPORTED
9360 png_set_background(pp, &dp->background_color, dp->do_background,
9361 0/*need_expand*/, bg);
9362# else
9363 png_set_background_fixed(pp, &dp->background_color,
9364 dp->do_background, 0/*need_expand*/, g);
9365# endif
9366# else
9367 png_error(pp, "png_set_background not supported");
9368# endif
9369 }
9370 }
9371
9372 {
9373 int i = dp->this.use_update_info;
9374 /* Always do one call, even if use_update_info is 0. */
9375 do
9376 png_read_update_info(pp, pi);
9377 while (--i > 0);
9378 }
9379
9380 /* Now we may get a different cbRow: */
9381 standard_info_part2(&dp->this, pp, pi, 1 /*images*/);
9382}
9383
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309384static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -07009385gamma_info(png_structp pp, png_infop pi)
9386{
9387 gamma_info_imp(voidcast(gamma_display*, png_get_progressive_ptr(pp)), pp,
9388 pi);
9389}
9390
9391/* Validate a single component value - the routine gets the input and output
9392 * sample values as unscaled PNG component values along with a cache of all the
9393 * information required to validate the values.
9394 */
9395typedef struct validate_info
9396{
9397 png_const_structp pp;
9398 gamma_display *dp;
9399 png_byte sbit;
9400 int use_input_precision;
9401 int do_background;
9402 int scale16;
9403 unsigned int sbit_max;
9404 unsigned int isbit_shift;
9405 unsigned int outmax;
9406
9407 double gamma_correction; /* Overall correction required. */
9408 double file_inverse; /* Inverse of file gamma. */
9409 double screen_gamma;
9410 double screen_inverse; /* Inverse of screen gamma. */
9411
9412 double background_red; /* Linear background value, red or gray. */
9413 double background_green;
9414 double background_blue;
9415
9416 double maxabs;
9417 double maxpc;
9418 double maxcalc;
9419 double maxout;
9420 double maxout_total; /* Total including quantization error */
9421 double outlog;
9422 int outquant;
9423}
9424validate_info;
9425
9426static void
9427init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp,
9428 int in_depth, int out_depth)
9429{
xNombred07bb0d2020-03-10 20:17:12 +01009430 unsigned int outmax = (1U<<out_depth)-1;
Chris Craikb50c2172013-07-29 15:28:30 -07009431
9432 vi->pp = pp;
9433 vi->dp = dp;
9434
9435 if (dp->sbit > 0 && dp->sbit < in_depth)
9436 {
9437 vi->sbit = dp->sbit;
9438 vi->isbit_shift = in_depth - dp->sbit;
9439 }
9440
9441 else
9442 {
9443 vi->sbit = (png_byte)in_depth;
9444 vi->isbit_shift = 0;
9445 }
9446
9447 vi->sbit_max = (1U << vi->sbit)-1;
9448
9449 /* This mimics the libpng threshold test, '0' is used to prevent gamma
9450 * correction in the validation test.
9451 */
9452 vi->screen_gamma = dp->screen_gamma;
9453 if (fabs(vi->screen_gamma-1) < PNG_GAMMA_THRESHOLD)
9454 vi->screen_gamma = vi->screen_inverse = 0;
9455 else
9456 vi->screen_inverse = 1/vi->screen_gamma;
9457
9458 vi->use_input_precision = dp->use_input_precision;
9459 vi->outmax = outmax;
9460 vi->maxabs = abserr(dp->pm, in_depth, out_depth);
9461 vi->maxpc = pcerr(dp->pm, in_depth, out_depth);
9462 vi->maxcalc = calcerr(dp->pm, in_depth, out_depth);
9463 vi->maxout = outerr(dp->pm, in_depth, out_depth);
9464 vi->outquant = output_quantization_factor(dp->pm, in_depth, out_depth);
9465 vi->maxout_total = vi->maxout + vi->outquant * .5;
9466 vi->outlog = outlog(dp->pm, in_depth, out_depth);
9467
9468 if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 ||
Matt Sarett9b1fe632015-11-25 10:21:17 -05009469 (dp->this.colour_type == 3 && dp->this.is_transparent) ||
9470 ((dp->this.colour_type == 0 || dp->this.colour_type == 2) &&
9471 dp->this.has_tRNS))
Chris Craikb50c2172013-07-29 15:28:30 -07009472 {
9473 vi->do_background = dp->do_background;
9474
9475 if (vi->do_background != 0)
9476 {
Matt Sarett9b1fe632015-11-25 10:21:17 -05009477 const double bg_inverse = 1/dp->background_gamma;
Chris Craikb50c2172013-07-29 15:28:30 -07009478 double r, g, b;
9479
9480 /* Caller must at least put the gray value into the red channel */
9481 r = dp->background_color.red; r /= outmax;
9482 g = dp->background_color.green; g /= outmax;
9483 b = dp->background_color.blue; b /= outmax;
9484
9485# if 0
9486 /* libpng doesn't do this optimization, if we do pngvalid will fail.
9487 */
9488 if (fabs(bg_inverse-1) >= PNG_GAMMA_THRESHOLD)
9489# endif
9490 {
9491 r = pow(r, bg_inverse);
9492 g = pow(g, bg_inverse);
9493 b = pow(b, bg_inverse);
9494 }
9495
9496 vi->background_red = r;
9497 vi->background_green = g;
9498 vi->background_blue = b;
9499 }
9500 }
Matt Sarett9b1fe632015-11-25 10:21:17 -05009501 else /* Do not expect any background processing */
Chris Craikb50c2172013-07-29 15:28:30 -07009502 vi->do_background = 0;
9503
9504 if (vi->do_background == 0)
9505 vi->background_red = vi->background_green = vi->background_blue = 0;
9506
9507 vi->gamma_correction = 1/(dp->file_gamma*dp->screen_gamma);
9508 if (fabs(vi->gamma_correction-1) < PNG_GAMMA_THRESHOLD)
9509 vi->gamma_correction = 0;
9510
9511 vi->file_inverse = 1/dp->file_gamma;
9512 if (fabs(vi->file_inverse-1) < PNG_GAMMA_THRESHOLD)
9513 vi->file_inverse = 0;
9514
9515 vi->scale16 = dp->scale16;
9516}
9517
9518/* This function handles composition of a single non-alpha component. The
9519 * argument is the input sample value, in the range 0..1, and the alpha value.
9520 * The result is the composed, linear, input sample. If alpha is less than zero
9521 * this is the alpha component and the function should not be called!
9522 */
9523static double
9524gamma_component_compose(int do_background, double input_sample, double alpha,
9525 double background, int *compose)
9526{
9527 switch (do_background)
9528 {
9529#ifdef PNG_READ_BACKGROUND_SUPPORTED
9530 case PNG_BACKGROUND_GAMMA_SCREEN:
9531 case PNG_BACKGROUND_GAMMA_FILE:
9532 case PNG_BACKGROUND_GAMMA_UNIQUE:
9533 /* Standard PNG background processing. */
9534 if (alpha < 1)
9535 {
9536 if (alpha > 0)
9537 {
9538 input_sample = input_sample * alpha + background * (1-alpha);
9539 if (compose != NULL)
9540 *compose = 1;
9541 }
9542
9543 else
9544 input_sample = background;
9545 }
9546 break;
9547#endif
9548
9549#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9550 case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
9551 case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
9552 /* The components are premultiplied in either case and the output is
9553 * gamma encoded (to get standard Porter-Duff we expect the output
9554 * gamma to be set to 1.0!)
9555 */
9556 case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
9557 /* The optimization is that the partial-alpha entries are linear
9558 * while the opaque pixels are gamma encoded, but this only affects the
9559 * output encoding.
9560 */
9561 if (alpha < 1)
9562 {
9563 if (alpha > 0)
9564 {
9565 input_sample *= alpha;
9566 if (compose != NULL)
9567 *compose = 1;
9568 }
9569
9570 else
9571 input_sample = 0;
9572 }
9573 break;
9574#endif
9575
9576 default:
9577 /* Standard cases where no compositing is done (so the component
9578 * value is already correct.)
9579 */
9580 UNUSED(alpha)
9581 UNUSED(background)
9582 UNUSED(compose)
9583 break;
9584 }
9585
9586 return input_sample;
9587}
9588
9589/* This API returns the encoded *input* component, in the range 0..1 */
9590static double
Matt Sarett9b1fe632015-11-25 10:21:17 -05009591gamma_component_validate(const char *name, const validate_info *vi,
xNombred07bb0d2020-03-10 20:17:12 +01009592 unsigned int id, unsigned int od,
Matt Sarett9b1fe632015-11-25 10:21:17 -05009593 const double alpha /* <0 for the alpha channel itself */,
9594 const double background /* component background value */)
Chris Craikb50c2172013-07-29 15:28:30 -07009595{
xNombred07bb0d2020-03-10 20:17:12 +01009596 unsigned int isbit = id >> vi->isbit_shift;
9597 unsigned int sbit_max = vi->sbit_max;
9598 unsigned int outmax = vi->outmax;
9599 int do_background = vi->do_background;
Chris Craikb50c2172013-07-29 15:28:30 -07009600
9601 double i;
9602
9603 /* First check on the 'perfect' result obtained from the digitized input
9604 * value, id, and compare this against the actual digitized result, 'od'.
9605 * 'i' is the input result in the range 0..1:
9606 */
9607 i = isbit; i /= sbit_max;
9608
9609 /* Check for the fast route: if we don't do any background composition or if
9610 * this is the alpha channel ('alpha' < 0) or if the pixel is opaque then
9611 * just use the gamma_correction field to correct to the final output gamma.
9612 */
9613 if (alpha == 1 /* opaque pixel component */ || !do_background
9614#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9615 || do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_PNG
9616#endif
9617 || (alpha < 0 /* alpha channel */
9618#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9619 && do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN
9620#endif
9621 ))
9622 {
9623 /* Then get the gamma corrected version of 'i' and compare to 'od', any
9624 * error less than .5 is insignificant - just quantization of the output
9625 * value to the nearest digital value (nevertheless the error is still
9626 * recorded - it's interesting ;-)
9627 */
9628 double encoded_sample = i;
9629 double encoded_error;
9630
9631 /* alpha less than 0 indicates the alpha channel, which is always linear
9632 */
9633 if (alpha >= 0 && vi->gamma_correction > 0)
9634 encoded_sample = pow(encoded_sample, vi->gamma_correction);
9635 encoded_sample *= outmax;
9636
9637 encoded_error = fabs(od-encoded_sample);
9638
9639 if (encoded_error > vi->dp->maxerrout)
9640 vi->dp->maxerrout = encoded_error;
9641
9642 if (encoded_error < vi->maxout_total && encoded_error < vi->outlog)
9643 return i;
9644 }
9645
9646 /* The slow route - attempt to do linear calculations. */
9647 /* There may be an error, or background processing is required, so calculate
9648 * the actual sample values - unencoded light intensity values. Note that in
9649 * practice these are not completely unencoded because they include a
9650 * 'viewing correction' to decrease or (normally) increase the perceptual
9651 * contrast of the image. There's nothing we can do about this - we don't
9652 * know what it is - so assume the unencoded value is perceptually linear.
9653 */
9654 {
9655 double input_sample = i; /* In range 0..1 */
9656 double output, error, encoded_sample, encoded_error;
9657 double es_lo, es_hi;
9658 int compose = 0; /* Set to one if composition done */
9659 int output_is_encoded; /* Set if encoded to screen gamma */
9660 int log_max_error = 1; /* Check maximum error values */
9661 png_const_charp pass = 0; /* Reason test passes (or 0 for fail) */
9662
9663 /* Convert to linear light (with the above caveat.) The alpha channel is
9664 * already linear.
9665 */
9666 if (alpha >= 0)
9667 {
9668 int tcompose;
9669
9670 if (vi->file_inverse > 0)
9671 input_sample = pow(input_sample, vi->file_inverse);
9672
9673 /* Handle the compose processing: */
9674 tcompose = 0;
9675 input_sample = gamma_component_compose(do_background, input_sample,
9676 alpha, background, &tcompose);
9677
9678 if (tcompose)
9679 compose = 1;
9680 }
9681
9682 /* And similarly for the output value, but we need to check the background
9683 * handling to linearize it correctly.
9684 */
9685 output = od;
9686 output /= outmax;
9687
9688 output_is_encoded = vi->screen_gamma > 0;
9689
9690 if (alpha < 0) /* The alpha channel */
9691 {
9692#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9693 if (do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN)
9694#endif
9695 {
9696 /* In all other cases the output alpha channel is linear already,
9697 * don't log errors here, they are much larger in linear data.
9698 */
9699 output_is_encoded = 0;
9700 log_max_error = 0;
9701 }
9702 }
9703
9704#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
9705 else /* A component */
9706 {
9707 if (do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED &&
9708 alpha < 1) /* the optimized case - linear output */
9709 {
9710 if (alpha > 0) log_max_error = 0;
9711 output_is_encoded = 0;
9712 }
9713 }
9714#endif
9715
9716 if (output_is_encoded)
9717 output = pow(output, vi->screen_gamma);
9718
9719 /* Calculate (or recalculate) the encoded_sample value and repeat the
9720 * check above (unnecessary if we took the fast route, but harmless.)
9721 */
9722 encoded_sample = input_sample;
9723 if (output_is_encoded)
9724 encoded_sample = pow(encoded_sample, vi->screen_inverse);
9725 encoded_sample *= outmax;
9726
9727 encoded_error = fabs(od-encoded_sample);
9728
9729 /* Don't log errors in the alpha channel, or the 'optimized' case,
9730 * neither are significant to the overall perception.
9731 */
9732 if (log_max_error && encoded_error > vi->dp->maxerrout)
9733 vi->dp->maxerrout = encoded_error;
9734
9735 if (encoded_error < vi->maxout_total)
9736 {
9737 if (encoded_error < vi->outlog)
9738 return i;
9739
9740 /* Test passed but error is bigger than the log limit, record why the
9741 * test passed:
9742 */
9743 pass = "less than maxout:\n";
9744 }
9745
9746 /* i: the original input value in the range 0..1
9747 *
9748 * pngvalid calculations:
9749 * input_sample: linear result; i linearized and composed, range 0..1
xNombred07bb0d2020-03-10 20:17:12 +01009750 * encoded_sample: encoded result; input_sample scaled to output bit depth
Chris Craikb50c2172013-07-29 15:28:30 -07009751 *
9752 * libpng calculations:
9753 * output: linear result; od scaled to 0..1 and linearized
9754 * od: encoded result from libpng
9755 */
9756
9757 /* Now we have the numbers for real errors, both absolute values as as a
9758 * percentage of the correct value (output):
9759 */
9760 error = fabs(input_sample-output);
9761
9762 if (log_max_error && error > vi->dp->maxerrabs)
9763 vi->dp->maxerrabs = error;
9764
9765 /* The following is an attempt to ignore the tendency of quantization to
9766 * dominate the percentage errors for lower result values:
9767 */
9768 if (log_max_error && input_sample > .5)
9769 {
9770 double percentage_error = error/input_sample;
9771 if (percentage_error > vi->dp->maxerrpc)
9772 vi->dp->maxerrpc = percentage_error;
9773 }
9774
9775 /* Now calculate the digitization limits for 'encoded_sample' using the
9776 * 'max' values. Note that maxout is in the encoded space but maxpc and
9777 * maxabs are in linear light space.
9778 *
9779 * First find the maximum error in linear light space, range 0..1:
9780 */
9781 {
9782 double tmp = input_sample * vi->maxpc;
9783 if (tmp < vi->maxabs) tmp = vi->maxabs;
9784 /* If 'compose' is true the composition was done in linear space using
9785 * integer arithmetic. This introduces an extra error of +/- 0.5 (at
9786 * least) in the integer space used. 'maxcalc' records this, taking
9787 * into account the possibility that even for 16 bit output 8 bit space
9788 * may have been used.
9789 */
9790 if (compose && tmp < vi->maxcalc) tmp = vi->maxcalc;
9791
9792 /* The 'maxout' value refers to the encoded result, to compare with
9793 * this encode input_sample adjusted by the maximum error (tmp) above.
9794 */
9795 es_lo = encoded_sample - vi->maxout;
9796
9797 if (es_lo > 0 && input_sample-tmp > 0)
9798 {
9799 double low_value = input_sample-tmp;
9800 if (output_is_encoded)
9801 low_value = pow(low_value, vi->screen_inverse);
9802 low_value *= outmax;
9803 if (low_value < es_lo) es_lo = low_value;
9804
9805 /* Quantize this appropriately: */
9806 es_lo = ceil(es_lo / vi->outquant - .5) * vi->outquant;
9807 }
9808
9809 else
9810 es_lo = 0;
9811
9812 es_hi = encoded_sample + vi->maxout;
9813
9814 if (es_hi < outmax && input_sample+tmp < 1)
9815 {
9816 double high_value = input_sample+tmp;
9817 if (output_is_encoded)
9818 high_value = pow(high_value, vi->screen_inverse);
9819 high_value *= outmax;
9820 if (high_value > es_hi) es_hi = high_value;
9821
9822 es_hi = floor(es_hi / vi->outquant + .5) * vi->outquant;
9823 }
9824
9825 else
9826 es_hi = outmax;
9827 }
9828
9829 /* The primary test is that the final encoded value returned by the
9830 * library should be between the two limits (inclusive) that were
9831 * calculated above.
9832 */
9833 if (od >= es_lo && od <= es_hi)
9834 {
9835 /* The value passes, but we may need to log the information anyway. */
9836 if (encoded_error < vi->outlog)
9837 return i;
9838
9839 if (pass == 0)
9840 pass = "within digitization limits:\n";
9841 }
9842
9843 {
9844 /* There has been an error in processing, or we need to log this
9845 * value.
9846 */
9847 double is_lo, is_hi;
9848
9849 /* pass is set at this point if either of the tests above would have
9850 * passed. Don't do these additional tests here - just log the
9851 * original [es_lo..es_hi] values.
9852 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309853 if (pass == 0 && vi->use_input_precision && vi->dp->sbit)
Chris Craikb50c2172013-07-29 15:28:30 -07009854 {
9855 /* Ok, something is wrong - this actually happens in current libpng
9856 * 16-to-8 processing. Assume that the input value (id, adjusted
9857 * for sbit) can be anywhere between value-.5 and value+.5 - quite a
9858 * large range if sbit is low.
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309859 *
9860 * NOTE: at present because the libpng gamma table stuff has been
9861 * changed to use a rounding algorithm to correct errors in 8-bit
9862 * calculations the precise sbit calculation (a shift) has been
9863 * lost. This can result in up to a +/-1 error in the presence of
9864 * an sbit less than the bit depth.
Chris Craikb50c2172013-07-29 15:28:30 -07009865 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309866# if PNG_LIBPNG_VER < 10700
9867# define SBIT_ERROR .5
9868# else
9869# define SBIT_ERROR 1.
9870# endif
9871 double tmp = (isbit - SBIT_ERROR)/sbit_max;
Chris Craikb50c2172013-07-29 15:28:30 -07009872
9873 if (tmp <= 0)
9874 tmp = 0;
9875
9876 else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
9877 tmp = pow(tmp, vi->file_inverse);
9878
9879 tmp = gamma_component_compose(do_background, tmp, alpha, background,
9880 NULL);
9881
9882 if (output_is_encoded && tmp > 0 && tmp < 1)
9883 tmp = pow(tmp, vi->screen_inverse);
9884
9885 is_lo = ceil(outmax * tmp - vi->maxout_total);
9886
9887 if (is_lo < 0)
9888 is_lo = 0;
9889
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309890 tmp = (isbit + SBIT_ERROR)/sbit_max;
Chris Craikb50c2172013-07-29 15:28:30 -07009891
Sireesh Tripurarib478e662014-05-09 15:15:10 +05309892 if (tmp >= 1)
9893 tmp = 1;
Chris Craikb50c2172013-07-29 15:28:30 -07009894
9895 else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
9896 tmp = pow(tmp, vi->file_inverse);
9897
9898 tmp = gamma_component_compose(do_background, tmp, alpha, background,
9899 NULL);
9900
9901 if (output_is_encoded && tmp > 0 && tmp < 1)
9902 tmp = pow(tmp, vi->screen_inverse);
9903
9904 is_hi = floor(outmax * tmp + vi->maxout_total);
9905
9906 if (is_hi > outmax)
9907 is_hi = outmax;
9908
9909 if (!(od < is_lo || od > is_hi))
9910 {
9911 if (encoded_error < vi->outlog)
9912 return i;
9913
9914 pass = "within input precision limits:\n";
9915 }
9916
9917 /* One last chance. If this is an alpha channel and the 16to8
9918 * option has been used and 'inaccurate' scaling is used then the
9919 * bit reduction is obtained by simply using the top 8 bits of the
9920 * value.
9921 *
9922 * This is only done for older libpng versions when the 'inaccurate'
9923 * (chop) method of scaling was used.
9924 */
9925# ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
9926# if PNG_LIBPNG_VER < 10504
9927 /* This may be required for other components in the future,
9928 * but at present the presence of gamma correction effectively
9929 * prevents the errors in the component scaling (I don't quite
9930 * understand why, but since it's better this way I care not
9931 * to ask, JB 20110419.)
9932 */
9933 if (pass == 0 && alpha < 0 && vi->scale16 && vi->sbit > 8 &&
9934 vi->sbit + vi->isbit_shift == 16)
9935 {
9936 tmp = ((id >> 8) - .5)/255;
9937
9938 if (tmp > 0)
9939 {
9940 is_lo = ceil(outmax * tmp - vi->maxout_total);
9941 if (is_lo < 0) is_lo = 0;
9942 }
9943
9944 else
9945 is_lo = 0;
9946
9947 tmp = ((id >> 8) + .5)/255;
9948
9949 if (tmp < 1)
9950 {
9951 is_hi = floor(outmax * tmp + vi->maxout_total);
9952 if (is_hi > outmax) is_hi = outmax;
9953 }
9954
9955 else
9956 is_hi = outmax;
9957
9958 if (!(od < is_lo || od > is_hi))
9959 {
9960 if (encoded_error < vi->outlog)
9961 return i;
9962
9963 pass = "within 8 bit limits:\n";
9964 }
9965 }
9966# endif
9967# endif
9968 }
9969 else /* !use_input_precision */
9970 is_lo = es_lo, is_hi = es_hi;
9971
9972 /* Attempt to output a meaningful error/warning message: the message
9973 * output depends on the background/composite operation being performed
9974 * because this changes what parameters were actually used above.
9975 */
9976 {
9977 size_t pos = 0;
9978 /* Need either 1/255 or 1/65535 precision here; 3 or 6 decimal
9979 * places. Just use outmax to work out which.
9980 */
9981 int precision = (outmax >= 1000 ? 6 : 3);
9982 int use_input=1, use_background=0, do_compose=0;
9983 char msg[256];
9984
9985 if (pass != 0)
9986 pos = safecat(msg, sizeof msg, pos, "\n\t");
9987
9988 /* Set up the various flags, the output_is_encoded flag above
9989 * is also used below. do_compose is just a double check.
9990 */
9991 switch (do_background)
9992 {
9993# ifdef PNG_READ_BACKGROUND_SUPPORTED
9994 case PNG_BACKGROUND_GAMMA_SCREEN:
9995 case PNG_BACKGROUND_GAMMA_FILE:
9996 case PNG_BACKGROUND_GAMMA_UNIQUE:
9997 use_background = (alpha >= 0 && alpha < 1);
Chris Craikb50c2172013-07-29 15:28:30 -07009998# endif
9999# ifdef PNG_READ_ALPHA_MODE_SUPPORTED
Leon Scroggins III3cc83ac2017-10-06 11:02:56 -040010000 /* FALLTHROUGH */
Chris Craikb50c2172013-07-29 15:28:30 -070010001 case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
10002 case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
10003 case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
10004# endif /* ALPHA_MODE_SUPPORTED */
10005 do_compose = (alpha > 0 && alpha < 1);
10006 use_input = (alpha != 0);
10007 break;
10008
10009 default:
10010 break;
10011 }
10012
10013 /* Check the 'compose' flag */
10014 if (compose != do_compose)
10015 png_error(vi->pp, "internal error (compose)");
10016
10017 /* 'name' is the component name */
10018 pos = safecat(msg, sizeof msg, pos, name);
10019 pos = safecat(msg, sizeof msg, pos, "(");
10020 pos = safecatn(msg, sizeof msg, pos, id);
10021 if (use_input || pass != 0/*logging*/)
10022 {
10023 if (isbit != id)
10024 {
10025 /* sBIT has reduced the precision of the input: */
10026 pos = safecat(msg, sizeof msg, pos, ", sbit(");
10027 pos = safecatn(msg, sizeof msg, pos, vi->sbit);
10028 pos = safecat(msg, sizeof msg, pos, "): ");
10029 pos = safecatn(msg, sizeof msg, pos, isbit);
10030 }
10031 pos = safecat(msg, sizeof msg, pos, "/");
10032 /* The output is either "id/max" or "id sbit(sbit): isbit/max" */
10033 pos = safecatn(msg, sizeof msg, pos, vi->sbit_max);
10034 }
10035 pos = safecat(msg, sizeof msg, pos, ")");
10036
10037 /* A component may have been multiplied (in linear space) by the
10038 * alpha value, 'compose' says whether this is relevant.
10039 */
10040 if (compose || pass != 0)
10041 {
10042 /* If any form of composition is being done report our
10043 * calculated linear value here (the code above doesn't record
10044 * the input value before composition is performed, so what
10045 * gets reported is the value after composition.)
10046 */
10047 if (use_input || pass != 0)
10048 {
10049 if (vi->file_inverse > 0)
10050 {
10051 pos = safecat(msg, sizeof msg, pos, "^");
10052 pos = safecatd(msg, sizeof msg, pos, vi->file_inverse, 2);
10053 }
10054
10055 else
10056 pos = safecat(msg, sizeof msg, pos, "[linear]");
10057
10058 pos = safecat(msg, sizeof msg, pos, "*(alpha)");
10059 pos = safecatd(msg, sizeof msg, pos, alpha, precision);
10060 }
10061
10062 /* Now record the *linear* background value if it was used
10063 * (this function is not passed the original, non-linear,
10064 * value but it is contained in the test name.)
10065 */
10066 if (use_background)
10067 {
10068 pos = safecat(msg, sizeof msg, pos, use_input ? "+" : " ");
10069 pos = safecat(msg, sizeof msg, pos, "(background)");
10070 pos = safecatd(msg, sizeof msg, pos, background, precision);
10071 pos = safecat(msg, sizeof msg, pos, "*");
10072 pos = safecatd(msg, sizeof msg, pos, 1-alpha, precision);
10073 }
10074 }
10075
10076 /* Report the calculated value (input_sample) and the linearized
10077 * libpng value (output) unless this is just a component gamma
10078 * correction.
10079 */
10080 if (compose || alpha < 0 || pass != 0)
10081 {
10082 pos = safecat(msg, sizeof msg, pos,
10083 pass != 0 ? " =\n\t" : " = ");
10084 pos = safecatd(msg, sizeof msg, pos, input_sample, precision);
10085 pos = safecat(msg, sizeof msg, pos, " (libpng: ");
10086 pos = safecatd(msg, sizeof msg, pos, output, precision);
10087 pos = safecat(msg, sizeof msg, pos, ")");
10088
10089 /* Finally report the output gamma encoding, if any. */
10090 if (output_is_encoded)
10091 {
10092 pos = safecat(msg, sizeof msg, pos, " ^");
10093 pos = safecatd(msg, sizeof msg, pos, vi->screen_inverse, 2);
10094 pos = safecat(msg, sizeof msg, pos, "(to screen) =");
10095 }
10096
10097 else
10098 pos = safecat(msg, sizeof msg, pos, " [screen is linear] =");
10099 }
10100
10101 if ((!compose && alpha >= 0) || pass != 0)
10102 {
10103 if (pass != 0) /* logging */
10104 pos = safecat(msg, sizeof msg, pos, "\n\t[overall:");
10105
10106 /* This is the non-composition case, the internal linear
10107 * values are irrelevant (though the log below will reveal
10108 * them.) Output a much shorter warning/error message and report
10109 * the overall gamma correction.
10110 */
10111 if (vi->gamma_correction > 0)
10112 {
10113 pos = safecat(msg, sizeof msg, pos, " ^");
10114 pos = safecatd(msg, sizeof msg, pos, vi->gamma_correction, 2);
10115 pos = safecat(msg, sizeof msg, pos, "(gamma correction) =");
10116 }
10117
10118 else
10119 pos = safecat(msg, sizeof msg, pos,
10120 " [no gamma correction] =");
10121
10122 if (pass != 0)
10123 pos = safecat(msg, sizeof msg, pos, "]");
10124 }
10125
10126 /* This is our calculated encoded_sample which should (but does
10127 * not) match od:
10128 */
10129 pos = safecat(msg, sizeof msg, pos, pass != 0 ? "\n\t" : " ");
10130 pos = safecatd(msg, sizeof msg, pos, is_lo, 1);
10131 pos = safecat(msg, sizeof msg, pos, " < ");
10132 pos = safecatd(msg, sizeof msg, pos, encoded_sample, 1);
10133 pos = safecat(msg, sizeof msg, pos, " (libpng: ");
10134 pos = safecatn(msg, sizeof msg, pos, od);
10135 pos = safecat(msg, sizeof msg, pos, ")");
10136 pos = safecat(msg, sizeof msg, pos, "/");
10137 pos = safecatn(msg, sizeof msg, pos, outmax);
10138 pos = safecat(msg, sizeof msg, pos, " < ");
10139 pos = safecatd(msg, sizeof msg, pos, is_hi, 1);
10140
10141 if (pass == 0) /* The error condition */
10142 {
10143# ifdef PNG_WARNINGS_SUPPORTED
10144 png_warning(vi->pp, msg);
10145# else
10146 store_warning(vi->pp, msg);
10147# endif
10148 }
10149
10150 else /* logging this value */
10151 store_verbose(&vi->dp->pm->this, vi->pp, pass, msg);
10152 }
10153 }
10154 }
10155
10156 return i;
10157}
10158
10159static void
10160gamma_image_validate(gamma_display *dp, png_const_structp pp,
10161 png_infop pi)
10162{
10163 /* Get some constants derived from the input and output file formats: */
Matt Sarett9b1fe632015-11-25 10:21:17 -050010164 const png_store* const ps = dp->this.ps;
xNombred07bb0d2020-03-10 20:17:12 +010010165 png_byte in_ct = dp->this.colour_type;
10166 png_byte in_bd = dp->this.bit_depth;
10167 png_uint_32 w = dp->this.w;
10168 png_uint_32 h = dp->this.h;
Matt Sarett9b1fe632015-11-25 10:21:17 -050010169 const size_t cbRow = dp->this.cbRow;
xNombred07bb0d2020-03-10 20:17:12 +010010170 png_byte out_ct = png_get_color_type(pp, pi);
10171 png_byte out_bd = png_get_bit_depth(pp, pi);
Chris Craikb50c2172013-07-29 15:28:30 -070010172
10173 /* There are three sources of error, firstly the quantization in the
10174 * file encoding, determined by sbit and/or the file depth, secondly
10175 * the output (screen) gamma and thirdly the output file encoding.
10176 *
10177 * Since this API receives the screen and file gamma in double
10178 * precision it is possible to calculate an exact answer given an input
10179 * pixel value. Therefore we assume that the *input* value is exact -
10180 * sample/maxsample - calculate the corresponding gamma corrected
10181 * output to the limits of double precision arithmetic and compare with
10182 * what libpng returns.
10183 *
10184 * Since the library must quantize the output to 8 or 16 bits there is
10185 * a fundamental limit on the accuracy of the output of +/-.5 - this
10186 * quantization limit is included in addition to the other limits
xNombred07bb0d2020-03-10 20:17:12 +010010187 * specified by the parameters to the API. (Effectively, add .5
Chris Craikb50c2172013-07-29 15:28:30 -070010188 * everywhere.)
10189 *
xNombred07bb0d2020-03-10 20:17:12 +010010190 * The behavior of the 'sbit' parameter is defined by section 12.5
Chris Craikb50c2172013-07-29 15:28:30 -070010191 * (sample depth scaling) of the PNG spec. That section forces the
10192 * decoder to assume that the PNG values have been scaled if sBIT is
10193 * present:
10194 *
10195 * png-sample = floor( input-sample * (max-out/max-in) + .5);
10196 *
10197 * This means that only a subset of the possible PNG values should
10198 * appear in the input. However, the spec allows the encoder to use a
10199 * variety of approximations to the above and doesn't require any
10200 * restriction of the values produced.
10201 *
10202 * Nevertheless the spec requires that the upper 'sBIT' bits of the
10203 * value stored in a PNG file be the original sample bits.
10204 * Consequently the code below simply scales the top sbit bits by
10205 * (1<<sbit)-1 to obtain an original sample value.
10206 *
10207 * Because there is limited precision in the input it is arguable that
10208 * an acceptable result is any valid result from input-.5 to input+.5.
10209 * The basic tests below do not do this, however if 'use_input_precision'
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010210 * is set a subsequent test is performed above.
Chris Craikb50c2172013-07-29 15:28:30 -070010211 */
xNombred07bb0d2020-03-10 20:17:12 +010010212 unsigned int samples_per_pixel = (out_ct & 2U) ? 3U : 1U;
Chris Craikb50c2172013-07-29 15:28:30 -070010213 int processing;
10214 png_uint_32 y;
Matt Sarett9b1fe632015-11-25 10:21:17 -050010215 const store_palette_entry *in_palette = dp->this.palette;
xNombred07bb0d2020-03-10 20:17:12 +010010216 int in_is_transparent = dp->this.is_transparent;
Matt Sarett9b1fe632015-11-25 10:21:17 -050010217 int process_tRNS;
Chris Craikb50c2172013-07-29 15:28:30 -070010218 int out_npalette = -1;
10219 int out_is_transparent = 0; /* Just refers to the palette case */
10220 store_palette out_palette;
10221 validate_info vi;
10222
10223 /* Check for row overwrite errors */
10224 store_image_check(dp->this.ps, pp, 0);
10225
10226 /* Supply the input and output sample depths here - 8 for an indexed image,
10227 * otherwise the bit depth.
10228 */
10229 init_validate_info(&vi, dp, pp, in_ct==3?8:in_bd, out_ct==3?8:out_bd);
10230
10231 processing = (vi.gamma_correction > 0 && !dp->threshold_test)
10232 || in_bd != out_bd || in_ct != out_ct || vi.do_background;
Matt Sarett9b1fe632015-11-25 10:21:17 -050010233 process_tRNS = dp->this.has_tRNS && vi.do_background;
Chris Craikb50c2172013-07-29 15:28:30 -070010234
10235 /* TODO: FIX THIS: MAJOR BUG! If the transformations all happen inside
10236 * the palette there is no way of finding out, because libpng fails to
10237 * update the palette on png_read_update_info. Indeed, libpng doesn't
10238 * even do the required work until much later, when it doesn't have any
10239 * info pointer. Oops. For the moment 'processing' is turned off if
10240 * out_ct is palette.
10241 */
10242 if (in_ct == 3 && out_ct == 3)
10243 processing = 0;
10244
10245 if (processing && out_ct == 3)
10246 out_is_transparent = read_palette(out_palette, &out_npalette, pp, pi);
10247
10248 for (y=0; y<h; ++y)
10249 {
10250 png_const_bytep pRow = store_image_row(ps, pp, 0, y);
10251 png_byte std[STANDARD_ROWMAX];
10252
10253 transform_row(pp, std, in_ct, in_bd, y);
10254
10255 if (processing)
10256 {
10257 unsigned int x;
10258
10259 for (x=0; x<w; ++x)
10260 {
10261 double alpha = 1; /* serves as a flag value */
10262
10263 /* Record the palette index for index images. */
xNombred07bb0d2020-03-10 20:17:12 +010010264 unsigned int in_index =
Matt Sarett9b1fe632015-11-25 10:21:17 -050010265 in_ct == 3 ? sample(std, 3, in_bd, x, 0, 0, 0) : 256;
xNombred07bb0d2020-03-10 20:17:12 +010010266 unsigned int out_index =
Matt Sarett9b1fe632015-11-25 10:21:17 -050010267 out_ct == 3 ? sample(std, 3, out_bd, x, 0, 0, 0) : 256;
Chris Craikb50c2172013-07-29 15:28:30 -070010268
10269 /* Handle input alpha - png_set_background will cause the output
10270 * alpha to disappear so there is nothing to check.
10271 */
Matt Sarett9b1fe632015-11-25 10:21:17 -050010272 if ((in_ct & PNG_COLOR_MASK_ALPHA) != 0 ||
10273 (in_ct == 3 && in_is_transparent))
Chris Craikb50c2172013-07-29 15:28:30 -070010274 {
xNombred07bb0d2020-03-10 20:17:12 +010010275 unsigned int input_alpha = in_ct == 3 ?
Chris Craikb50c2172013-07-29 15:28:30 -070010276 dp->this.palette[in_index].alpha :
Matt Sarett9b1fe632015-11-25 10:21:17 -050010277 sample(std, in_ct, in_bd, x, samples_per_pixel, 0, 0);
Chris Craikb50c2172013-07-29 15:28:30 -070010278
10279 unsigned int output_alpha = 65536 /* as a flag value */;
10280
10281 if (out_ct == 3)
10282 {
10283 if (out_is_transparent)
10284 output_alpha = out_palette[out_index].alpha;
10285 }
10286
10287 else if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0)
10288 output_alpha = sample(pRow, out_ct, out_bd, x,
Matt Sarett9b1fe632015-11-25 10:21:17 -050010289 samples_per_pixel, 0, 0);
Chris Craikb50c2172013-07-29 15:28:30 -070010290
10291 if (output_alpha != 65536)
10292 alpha = gamma_component_validate("alpha", &vi, input_alpha,
10293 output_alpha, -1/*alpha*/, 0/*background*/);
10294
10295 else /* no alpha in output */
10296 {
10297 /* This is a copy of the calculation of 'i' above in order to
10298 * have the alpha value to use in the background calculation.
10299 */
10300 alpha = input_alpha >> vi.isbit_shift;
10301 alpha /= vi.sbit_max;
10302 }
10303 }
10304
Matt Sarett9b1fe632015-11-25 10:21:17 -050010305 else if (process_tRNS)
10306 {
10307 /* alpha needs to be set appropriately for this pixel, it is
10308 * currently 1 and needs to be 0 for an input pixel which matches
10309 * the values in tRNS.
10310 */
10311 switch (in_ct)
10312 {
10313 case 0: /* gray */
10314 if (sample(std, in_ct, in_bd, x, 0, 0, 0) ==
10315 dp->this.transparent.red)
10316 alpha = 0;
10317 break;
10318
10319 case 2: /* RGB */
10320 if (sample(std, in_ct, in_bd, x, 0, 0, 0) ==
10321 dp->this.transparent.red &&
10322 sample(std, in_ct, in_bd, x, 1, 0, 0) ==
10323 dp->this.transparent.green &&
10324 sample(std, in_ct, in_bd, x, 2, 0, 0) ==
10325 dp->this.transparent.blue)
10326 alpha = 0;
10327 break;
10328
10329 default:
10330 break;
10331 }
10332 }
10333
Chris Craikb50c2172013-07-29 15:28:30 -070010334 /* Handle grayscale or RGB components. */
10335 if ((in_ct & PNG_COLOR_MASK_COLOR) == 0) /* grayscale */
10336 (void)gamma_component_validate("gray", &vi,
Matt Sarett9b1fe632015-11-25 10:21:17 -050010337 sample(std, in_ct, in_bd, x, 0, 0, 0),
10338 sample(pRow, out_ct, out_bd, x, 0, 0, 0),
10339 alpha/*component*/, vi.background_red);
Chris Craikb50c2172013-07-29 15:28:30 -070010340 else /* RGB or palette */
10341 {
10342 (void)gamma_component_validate("red", &vi,
10343 in_ct == 3 ? in_palette[in_index].red :
Matt Sarett9b1fe632015-11-25 10:21:17 -050010344 sample(std, in_ct, in_bd, x, 0, 0, 0),
Chris Craikb50c2172013-07-29 15:28:30 -070010345 out_ct == 3 ? out_palette[out_index].red :
Matt Sarett9b1fe632015-11-25 10:21:17 -050010346 sample(pRow, out_ct, out_bd, x, 0, 0, 0),
Chris Craikb50c2172013-07-29 15:28:30 -070010347 alpha/*component*/, vi.background_red);
10348
10349 (void)gamma_component_validate("green", &vi,
10350 in_ct == 3 ? in_palette[in_index].green :
Matt Sarett9b1fe632015-11-25 10:21:17 -050010351 sample(std, in_ct, in_bd, x, 1, 0, 0),
Chris Craikb50c2172013-07-29 15:28:30 -070010352 out_ct == 3 ? out_palette[out_index].green :
Matt Sarett9b1fe632015-11-25 10:21:17 -050010353 sample(pRow, out_ct, out_bd, x, 1, 0, 0),
Chris Craikb50c2172013-07-29 15:28:30 -070010354 alpha/*component*/, vi.background_green);
10355
10356 (void)gamma_component_validate("blue", &vi,
10357 in_ct == 3 ? in_palette[in_index].blue :
Matt Sarett9b1fe632015-11-25 10:21:17 -050010358 sample(std, in_ct, in_bd, x, 2, 0, 0),
Chris Craikb50c2172013-07-29 15:28:30 -070010359 out_ct == 3 ? out_palette[out_index].blue :
Matt Sarett9b1fe632015-11-25 10:21:17 -050010360 sample(pRow, out_ct, out_bd, x, 2, 0, 0),
Chris Craikb50c2172013-07-29 15:28:30 -070010361 alpha/*component*/, vi.background_blue);
10362 }
10363 }
10364 }
10365
10366 else if (memcmp(std, pRow, cbRow) != 0)
10367 {
10368 char msg[64];
10369
10370 /* No transform is expected on the threshold tests. */
10371 sprintf(msg, "gamma: below threshold row %lu changed",
10372 (unsigned long)y);
10373
10374 png_error(pp, msg);
10375 }
10376 } /* row (y) loop */
10377
10378 dp->this.ps->validated = 1;
10379}
10380
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010381static void PNGCBAPI
Chris Craikb50c2172013-07-29 15:28:30 -070010382gamma_end(png_structp ppIn, png_infop pi)
10383{
10384 png_const_structp pp = ppIn;
10385 gamma_display *dp = voidcast(gamma_display*, png_get_progressive_ptr(pp));
10386
10387 if (!dp->this.speed)
10388 gamma_image_validate(dp, pp, pi);
10389 else
10390 dp->this.ps->validated = 1;
10391}
10392
10393/* A single test run checking a gamma transformation.
10394 *
10395 * maxabs: maximum absolute error as a fraction
10396 * maxout: maximum output error in the output units
10397 * maxpc: maximum percentage error (as a percentage)
10398 */
10399static void
xNombred07bb0d2020-03-10 20:17:12 +010010400gamma_test(png_modifier *pmIn, png_byte colour_typeIn,
10401 png_byte bit_depthIn, int palette_numberIn,
10402 int interlace_typeIn,
Matt Sarett9b1fe632015-11-25 10:21:17 -050010403 const double file_gammaIn, const double screen_gammaIn,
xNombred07bb0d2020-03-10 20:17:12 +010010404 png_byte sbitIn, int threshold_testIn,
Matt Sarett9b1fe632015-11-25 10:21:17 -050010405 const char *name,
xNombred07bb0d2020-03-10 20:17:12 +010010406 int use_input_precisionIn, int scale16In,
10407 int expand16In, int do_backgroundIn,
Matt Sarett9b1fe632015-11-25 10:21:17 -050010408 const png_color_16 *bkgd_colorIn, double bkgd_gammaIn)
Chris Craikb50c2172013-07-29 15:28:30 -070010409{
10410 gamma_display d;
10411 context(&pmIn->this, fault);
10412
10413 gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn,
10414 palette_numberIn, interlace_typeIn, 0, 0, 0),
10415 file_gammaIn, screen_gammaIn, sbitIn,
10416 threshold_testIn, use_input_precisionIn, scale16In,
10417 expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn);
10418
10419 Try
10420 {
10421 png_structp pp;
10422 png_infop pi;
10423 gama_modification gama_mod;
10424 srgb_modification srgb_mod;
10425 sbit_modification sbit_mod;
10426
10427 /* For the moment don't use the png_modifier support here. */
10428 d.pm->encoding_counter = 0;
10429 modifier_set_encoding(d.pm); /* Just resets everything */
10430 d.pm->current_gamma = d.file_gamma;
10431
10432 /* Make an appropriate modifier to set the PNG file gamma to the
10433 * given gamma value and the sBIT chunk to the given precision.
10434 */
10435 d.pm->modifications = NULL;
10436 gama_modification_init(&gama_mod, d.pm, d.file_gamma);
10437 srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/);
10438 if (d.sbit > 0)
10439 sbit_modification_init(&sbit_mod, d.pm, d.sbit);
10440
10441 modification_reset(d.pm->modifications);
10442
Matt Sarett9b1fe632015-11-25 10:21:17 -050010443 /* Get a png_struct for reading the image. */
Chris Craikb50c2172013-07-29 15:28:30 -070010444 pp = set_modifier_for_read(d.pm, &pi, d.this.id, name);
10445 standard_palette_init(&d.this);
10446
10447 /* Introduce the correct read function. */
10448 if (d.pm->this.progressive)
10449 {
10450 /* Share the row function with the standard implementation. */
10451 png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row,
10452 gamma_end);
10453
10454 /* Now feed data into the reader until we reach the end: */
10455 modifier_progressive_read(d.pm, pp, pi);
10456 }
10457 else
10458 {
10459 /* modifier_read expects a png_modifier* */
10460 png_set_read_fn(pp, d.pm, modifier_read);
10461
10462 /* Check the header values: */
10463 png_read_info(pp, pi);
10464
10465 /* Process the 'info' requirements. Only one image is generated */
10466 gamma_info_imp(&d, pp, pi);
10467
10468 sequential_row(&d.this, pp, pi, -1, 0);
10469
10470 if (!d.this.speed)
10471 gamma_image_validate(&d, pp, pi);
10472 else
10473 d.this.ps->validated = 1;
10474 }
10475
10476 modifier_reset(d.pm);
10477
10478 if (d.pm->log && !d.threshold_test && !d.this.speed)
10479 fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n",
10480 d.this.bit_depth, colour_types[d.this.colour_type], name,
10481 d.maxerrout, d.maxerrabs, 100*d.maxerrpc);
10482
10483 /* Log the summary values too. */
10484 if (d.this.colour_type == 0 || d.this.colour_type == 4)
10485 {
10486 switch (d.this.bit_depth)
10487 {
10488 case 1:
10489 break;
10490
10491 case 2:
10492 if (d.maxerrout > d.pm->error_gray_2)
10493 d.pm->error_gray_2 = d.maxerrout;
10494
10495 break;
10496
10497 case 4:
10498 if (d.maxerrout > d.pm->error_gray_4)
10499 d.pm->error_gray_4 = d.maxerrout;
10500
10501 break;
10502
10503 case 8:
10504 if (d.maxerrout > d.pm->error_gray_8)
10505 d.pm->error_gray_8 = d.maxerrout;
10506
10507 break;
10508
10509 case 16:
10510 if (d.maxerrout > d.pm->error_gray_16)
10511 d.pm->error_gray_16 = d.maxerrout;
10512
10513 break;
10514
10515 default:
10516 png_error(pp, "bad bit depth (internal: 1)");
10517 }
10518 }
10519
10520 else if (d.this.colour_type == 2 || d.this.colour_type == 6)
10521 {
10522 switch (d.this.bit_depth)
10523 {
10524 case 8:
10525
10526 if (d.maxerrout > d.pm->error_color_8)
10527 d.pm->error_color_8 = d.maxerrout;
10528
10529 break;
10530
10531 case 16:
10532
10533 if (d.maxerrout > d.pm->error_color_16)
10534 d.pm->error_color_16 = d.maxerrout;
10535
10536 break;
10537
10538 default:
10539 png_error(pp, "bad bit depth (internal: 2)");
10540 }
10541 }
10542
10543 else if (d.this.colour_type == 3)
10544 {
10545 if (d.maxerrout > d.pm->error_indexed)
10546 d.pm->error_indexed = d.maxerrout;
10547 }
10548 }
10549
10550 Catch(fault)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010551 modifier_reset(voidcast(png_modifier*,(void*)fault));
Chris Craikb50c2172013-07-29 15:28:30 -070010552}
10553
10554static void gamma_threshold_test(png_modifier *pm, png_byte colour_type,
10555 png_byte bit_depth, int interlace_type, double file_gamma,
10556 double screen_gamma)
10557{
10558 size_t pos = 0;
10559 char name[64];
10560 pos = safecat(name, sizeof name, pos, "threshold ");
10561 pos = safecatd(name, sizeof name, pos, file_gamma, 3);
10562 pos = safecat(name, sizeof name, pos, "/");
10563 pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
10564
10565 (void)gamma_test(pm, colour_type, bit_depth, 0/*palette*/, interlace_type,
10566 file_gamma, screen_gamma, 0/*sBIT*/, 1/*threshold test*/, name,
10567 0 /*no input precision*/,
10568 0 /*no scale16*/, 0 /*no expand16*/, 0 /*no background*/, 0 /*hence*/,
10569 0 /*no background gamma*/);
10570}
10571
10572static void
10573perform_gamma_threshold_tests(png_modifier *pm)
10574{
10575 png_byte colour_type = 0;
10576 png_byte bit_depth = 0;
10577 unsigned int palette_number = 0;
10578
10579 /* Don't test more than one instance of each palette - it's pointless, in
10580 * fact this test is somewhat excessive since libpng doesn't make this
10581 * decision based on colour type or bit depth!
Matt Sarett9b1fe632015-11-25 10:21:17 -050010582 *
10583 * CHANGED: now test two palettes and, as a side effect, images with and
10584 * without tRNS.
Chris Craikb50c2172013-07-29 15:28:30 -070010585 */
Matt Sarett9b1fe632015-11-25 10:21:17 -050010586 while (next_format(&colour_type, &bit_depth, &palette_number,
10587 pm->test_lbg_gamma_threshold, pm->test_tRNS))
10588 if (palette_number < 2)
Chris Craikb50c2172013-07-29 15:28:30 -070010589 {
10590 double test_gamma = 1.0;
10591 while (test_gamma >= .4)
10592 {
10593 /* There's little point testing the interlacing vs non-interlacing,
10594 * but this can be set from the command line.
10595 */
10596 gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
10597 test_gamma, 1/test_gamma);
10598 test_gamma *= .95;
10599 }
10600
10601 /* And a special test for sRGB */
10602 gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
10603 .45455, 2.2);
10604
10605 if (fail(pm))
10606 return;
10607 }
10608}
10609
10610static void gamma_transform_test(png_modifier *pm,
xNombred07bb0d2020-03-10 20:17:12 +010010611 png_byte colour_type, png_byte bit_depth,
10612 int palette_number,
10613 int interlace_type, const double file_gamma,
10614 const double screen_gamma, png_byte sbit,
10615 int use_input_precision, int scale16)
Chris Craikb50c2172013-07-29 15:28:30 -070010616{
10617 size_t pos = 0;
10618 char name[64];
10619
10620 if (sbit != bit_depth && sbit != 0)
10621 {
10622 pos = safecat(name, sizeof name, pos, "sbit(");
10623 pos = safecatn(name, sizeof name, pos, sbit);
10624 pos = safecat(name, sizeof name, pos, ") ");
10625 }
10626
10627 else
10628 pos = safecat(name, sizeof name, pos, "gamma ");
10629
10630 if (scale16)
10631 pos = safecat(name, sizeof name, pos, "16to8 ");
10632
10633 pos = safecatd(name, sizeof name, pos, file_gamma, 3);
10634 pos = safecat(name, sizeof name, pos, "->");
10635 pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
10636
10637 gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
10638 file_gamma, screen_gamma, sbit, 0, name, use_input_precision,
10639 scale16, pm->test_gamma_expand16, 0 , 0, 0);
10640}
10641
10642static void perform_gamma_transform_tests(png_modifier *pm)
10643{
10644 png_byte colour_type = 0;
10645 png_byte bit_depth = 0;
10646 unsigned int palette_number = 0;
10647
Matt Sarett9b1fe632015-11-25 10:21:17 -050010648 while (next_format(&colour_type, &bit_depth, &palette_number,
10649 pm->test_lbg_gamma_transform, pm->test_tRNS))
Chris Craikb50c2172013-07-29 15:28:30 -070010650 {
10651 unsigned int i, j;
10652
10653 for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
10654 if (i != j)
10655 {
10656 gamma_transform_test(pm, colour_type, bit_depth, palette_number,
10657 pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], 0/*sBIT*/,
10658 pm->use_input_precision, 0 /*do not scale16*/);
10659
10660 if (fail(pm))
10661 return;
10662 }
10663 }
10664}
10665
10666static void perform_gamma_sbit_tests(png_modifier *pm)
10667{
10668 png_byte sbit;
10669
10670 /* The only interesting cases are colour and grayscale, alpha is ignored here
10671 * for overall speed. Only bit depths where sbit is less than the bit depth
10672 * are tested.
10673 */
10674 for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit)
10675 {
10676 png_byte colour_type = 0, bit_depth = 0;
10677 unsigned int npalette = 0;
10678
Matt Sarett9b1fe632015-11-25 10:21:17 -050010679 while (next_format(&colour_type, &bit_depth, &npalette,
10680 pm->test_lbg_gamma_sbit, pm->test_tRNS))
Chris Craikb50c2172013-07-29 15:28:30 -070010681 if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 &&
10682 ((colour_type == 3 && sbit < 8) ||
10683 (colour_type != 3 && sbit < bit_depth)))
10684 {
10685 unsigned int i;
10686
10687 for (i=0; i<pm->ngamma_tests; ++i)
10688 {
10689 unsigned int j;
10690
10691 for (j=0; j<pm->ngamma_tests; ++j) if (i != j)
10692 {
10693 gamma_transform_test(pm, colour_type, bit_depth, npalette,
10694 pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
10695 sbit, pm->use_input_precision_sbit, 0 /*scale16*/);
10696
10697 if (fail(pm))
10698 return;
10699 }
10700 }
10701 }
10702 }
10703}
10704
10705/* Note that this requires a 16 bit source image but produces 8 bit output, so
10706 * we only need the 16bit write support, but the 16 bit images are only
10707 * generated if DO_16BIT is defined.
10708 */
10709#ifdef DO_16BIT
10710static void perform_gamma_scale16_tests(png_modifier *pm)
10711{
10712# ifndef PNG_MAX_GAMMA_8
10713# define PNG_MAX_GAMMA_8 11
10714# endif
Matt Sarett06f10872016-01-04 12:56:20 -050010715# if defined PNG_MAX_GAMMA_8 || PNG_LIBPNG_VER < 10700
10716# define SBIT_16_TO_8 PNG_MAX_GAMMA_8
10717# else
10718# define SBIT_16_TO_8 16
10719# endif
Chris Craikb50c2172013-07-29 15:28:30 -070010720 /* Include the alpha cases here. Note that sbit matches the internal value
10721 * used by the library - otherwise we will get spurious errors from the
10722 * internal sbit style approximation.
10723 *
10724 * The threshold test is here because otherwise the 16 to 8 conversion will
10725 * proceed *without* gamma correction, and the tests above will fail (but not
10726 * by much) - this could be fixed, it only appears with the -g option.
10727 */
10728 unsigned int i, j;
10729 for (i=0; i<pm->ngamma_tests; ++i)
10730 {
10731 for (j=0; j<pm->ngamma_tests; ++j)
10732 {
10733 if (i != j &&
10734 fabs(pm->gammas[j]/pm->gammas[i]-1) >= PNG_GAMMA_THRESHOLD)
10735 {
10736 gamma_transform_test(pm, 0, 16, 0, pm->interlace_type,
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010737 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
Chris Craikb50c2172013-07-29 15:28:30 -070010738 pm->use_input_precision_16to8, 1 /*scale16*/);
10739
10740 if (fail(pm))
10741 return;
10742
10743 gamma_transform_test(pm, 2, 16, 0, pm->interlace_type,
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010744 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
Chris Craikb50c2172013-07-29 15:28:30 -070010745 pm->use_input_precision_16to8, 1 /*scale16*/);
10746
10747 if (fail(pm))
10748 return;
10749
10750 gamma_transform_test(pm, 4, 16, 0, pm->interlace_type,
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010751 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
Chris Craikb50c2172013-07-29 15:28:30 -070010752 pm->use_input_precision_16to8, 1 /*scale16*/);
10753
10754 if (fail(pm))
10755 return;
10756
10757 gamma_transform_test(pm, 6, 16, 0, pm->interlace_type,
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010758 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
Chris Craikb50c2172013-07-29 15:28:30 -070010759 pm->use_input_precision_16to8, 1 /*scale16*/);
10760
10761 if (fail(pm))
10762 return;
10763 }
10764 }
10765 }
10766}
10767#endif /* 16 to 8 bit conversion */
10768
10769#if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\
10770 defined(PNG_READ_ALPHA_MODE_SUPPORTED)
10771static void gamma_composition_test(png_modifier *pm,
xNombred07bb0d2020-03-10 20:17:12 +010010772 png_byte colour_type, png_byte bit_depth,
10773 int palette_number,
10774 int interlace_type, const double file_gamma,
Matt Sarett9b1fe632015-11-25 10:21:17 -050010775 const double screen_gamma,
xNombred07bb0d2020-03-10 20:17:12 +010010776 int use_input_precision, int do_background,
10777 int expand_16)
Chris Craikb50c2172013-07-29 15:28:30 -070010778{
10779 size_t pos = 0;
10780 png_const_charp base;
10781 double bg;
10782 char name[128];
10783 png_color_16 background;
10784
10785 /* Make up a name and get an appropriate background gamma value. */
10786 switch (do_background)
10787 {
10788 default:
10789 base = "";
10790 bg = 4; /* should not be used */
10791 break;
10792 case PNG_BACKGROUND_GAMMA_SCREEN:
10793 base = " bckg(Screen):";
10794 bg = 1/screen_gamma;
10795 break;
10796 case PNG_BACKGROUND_GAMMA_FILE:
10797 base = " bckg(File):";
10798 bg = file_gamma;
10799 break;
10800 case PNG_BACKGROUND_GAMMA_UNIQUE:
10801 base = " bckg(Unique):";
10802 /* This tests the handling of a unique value, the math is such that the
10803 * value tends to be <1, but is neither screen nor file (even if they
10804 * match!)
10805 */
10806 bg = (file_gamma + screen_gamma) / 3;
10807 break;
10808#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
10809 case ALPHA_MODE_OFFSET + PNG_ALPHA_PNG:
10810 base = " alpha(PNG)";
10811 bg = 4; /* should not be used */
10812 break;
10813 case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
10814 base = " alpha(Porter-Duff)";
10815 bg = 4; /* should not be used */
10816 break;
10817 case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
10818 base = " alpha(Optimized)";
10819 bg = 4; /* should not be used */
10820 break;
10821 case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
10822 base = " alpha(Broken)";
10823 bg = 4; /* should not be used */
10824 break;
10825#endif
10826 }
10827
10828 /* Use random background values - the background is always presented in the
10829 * output space (8 or 16 bit components).
10830 */
10831 if (expand_16 || bit_depth == 16)
10832 {
10833 png_uint_32 r = random_32();
10834
10835 background.red = (png_uint_16)r;
10836 background.green = (png_uint_16)(r >> 16);
10837 r = random_32();
10838 background.blue = (png_uint_16)r;
10839 background.gray = (png_uint_16)(r >> 16);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010840
10841 /* In earlier libpng versions, those where DIGITIZE is set, any background
10842 * gamma correction in the expand16 case was done using 8-bit gamma
10843 * correction tables, resulting in larger errors. To cope with those
10844 * cases use a 16-bit background value which will handle this gamma
10845 * correction.
10846 */
10847# if DIGITIZE
10848 if (expand_16 && (do_background == PNG_BACKGROUND_GAMMA_UNIQUE ||
10849 do_background == PNG_BACKGROUND_GAMMA_FILE) &&
10850 fabs(bg*screen_gamma-1) > PNG_GAMMA_THRESHOLD)
10851 {
10852 /* The background values will be looked up in an 8-bit table to do
10853 * the gamma correction, so only select values which are an exact
10854 * match for the 8-bit table entries:
10855 */
10856 background.red = (png_uint_16)((background.red >> 8) * 257);
10857 background.green = (png_uint_16)((background.green >> 8) * 257);
10858 background.blue = (png_uint_16)((background.blue >> 8) * 257);
10859 background.gray = (png_uint_16)((background.gray >> 8) * 257);
10860 }
10861# endif
Chris Craikb50c2172013-07-29 15:28:30 -070010862 }
10863
10864 else /* 8 bit colors */
10865 {
10866 png_uint_32 r = random_32();
10867
10868 background.red = (png_byte)r;
10869 background.green = (png_byte)(r >> 8);
10870 background.blue = (png_byte)(r >> 16);
10871 background.gray = (png_byte)(r >> 24);
10872 }
10873
10874 background.index = 193; /* rgb(193,193,193) to detect errors */
Matt Sarett9b1fe632015-11-25 10:21:17 -050010875
Chris Craikb50c2172013-07-29 15:28:30 -070010876 if (!(colour_type & PNG_COLOR_MASK_COLOR))
10877 {
Matt Sarett9b1fe632015-11-25 10:21:17 -050010878 /* Because, currently, png_set_background is always called with
10879 * 'need_expand' false in this case and because the gamma test itself
10880 * doesn't cause an expand to 8-bit for lower bit depths the colour must
10881 * be reduced to the correct range.
10882 */
10883 if (bit_depth < 8)
10884 background.gray &= (png_uint_16)((1U << bit_depth)-1);
10885
Chris Craikb50c2172013-07-29 15:28:30 -070010886 /* Grayscale input, we do not convert to RGB (TBD), so we must set the
10887 * background to gray - else libpng seems to fail.
10888 */
10889 background.red = background.green = background.blue = background.gray;
10890 }
10891
10892 pos = safecat(name, sizeof name, pos, "gamma ");
10893 pos = safecatd(name, sizeof name, pos, file_gamma, 3);
10894 pos = safecat(name, sizeof name, pos, "->");
10895 pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
10896
10897 pos = safecat(name, sizeof name, pos, base);
10898 if (do_background < ALPHA_MODE_OFFSET)
10899 {
10900 /* Include the background color and gamma in the name: */
10901 pos = safecat(name, sizeof name, pos, "(");
10902 /* This assumes no expand gray->rgb - the current code won't handle that!
10903 */
10904 if (colour_type & PNG_COLOR_MASK_COLOR)
10905 {
10906 pos = safecatn(name, sizeof name, pos, background.red);
10907 pos = safecat(name, sizeof name, pos, ",");
10908 pos = safecatn(name, sizeof name, pos, background.green);
10909 pos = safecat(name, sizeof name, pos, ",");
10910 pos = safecatn(name, sizeof name, pos, background.blue);
10911 }
10912 else
10913 pos = safecatn(name, sizeof name, pos, background.gray);
10914 pos = safecat(name, sizeof name, pos, ")^");
10915 pos = safecatd(name, sizeof name, pos, bg, 3);
10916 }
10917
10918 gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
10919 file_gamma, screen_gamma, 0/*sBIT*/, 0, name, use_input_precision,
10920 0/*strip 16*/, expand_16, do_background, &background, bg);
10921}
10922
10923
10924static void
10925perform_gamma_composition_tests(png_modifier *pm, int do_background,
10926 int expand_16)
10927{
10928 png_byte colour_type = 0;
10929 png_byte bit_depth = 0;
10930 unsigned int palette_number = 0;
10931
10932 /* Skip the non-alpha cases - there is no setting of a transparency colour at
10933 * present.
Matt Sarett9b1fe632015-11-25 10:21:17 -050010934 *
10935 * TODO: incorrect; the palette case sets tRNS and, now RGB and gray do,
10936 * however the palette case fails miserably so is commented out below.
Chris Craikb50c2172013-07-29 15:28:30 -070010937 */
Matt Sarett9b1fe632015-11-25 10:21:17 -050010938 while (next_format(&colour_type, &bit_depth, &palette_number,
10939 pm->test_lbg_gamma_composition, pm->test_tRNS))
10940 if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0
10941#if 0 /* TODO: FIXME */
10942 /*TODO: FIXME: this should work */
10943 || colour_type == 3
10944#endif
10945 || (colour_type != 3 && palette_number != 0))
Chris Craikb50c2172013-07-29 15:28:30 -070010946 {
10947 unsigned int i, j;
10948
10949 /* Don't skip the i==j case here - it's relevant. */
10950 for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
10951 {
10952 gamma_composition_test(pm, colour_type, bit_depth, palette_number,
10953 pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
10954 pm->use_input_precision, do_background, expand_16);
10955
10956 if (fail(pm))
10957 return;
10958 }
10959 }
10960}
10961#endif /* READ_BACKGROUND || READ_ALPHA_MODE */
10962
10963static void
10964init_gamma_errors(png_modifier *pm)
10965{
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010966 /* Use -1 to catch tests that were not actually run */
10967 pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = -1.;
10968 pm->error_color_8 = -1.;
10969 pm->error_indexed = -1.;
10970 pm->error_gray_16 = pm->error_color_16 = -1.;
Chris Craikb50c2172013-07-29 15:28:30 -070010971}
10972
10973static void
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010974print_one(const char *leader, double err)
Chris Craikb50c2172013-07-29 15:28:30 -070010975{
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010976 if (err != -1.)
10977 printf(" %s %.5f\n", leader, err);
10978}
10979
10980static void
10981summarize_gamma_errors(png_modifier *pm, png_const_charp who, int low_bit_depth,
10982 int indexed)
10983{
10984 fflush(stderr);
10985
Chris Craikb50c2172013-07-29 15:28:30 -070010986 if (who)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010987 printf("\nGamma correction with %s:\n", who);
10988
10989 else
10990 printf("\nBasic gamma correction:\n");
Chris Craikb50c2172013-07-29 15:28:30 -070010991
10992 if (low_bit_depth)
10993 {
Sireesh Tripurarib478e662014-05-09 15:15:10 +053010994 print_one(" 2 bit gray: ", pm->error_gray_2);
10995 print_one(" 4 bit gray: ", pm->error_gray_4);
10996 print_one(" 8 bit gray: ", pm->error_gray_8);
10997 print_one(" 8 bit color:", pm->error_color_8);
10998 if (indexed)
10999 print_one(" indexed: ", pm->error_indexed);
Chris Craikb50c2172013-07-29 15:28:30 -070011000 }
11001
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011002 print_one("16 bit gray: ", pm->error_gray_16);
11003 print_one("16 bit color:", pm->error_color_16);
11004
11005 fflush(stdout);
Chris Craikb50c2172013-07-29 15:28:30 -070011006}
11007
11008static void
11009perform_gamma_test(png_modifier *pm, int summary)
11010{
11011 /*TODO: remove this*/
11012 /* Save certain values for the temporary overrides below. */
11013 unsigned int calculations_use_input_precision =
11014 pm->calculations_use_input_precision;
11015# ifdef PNG_READ_BACKGROUND_SUPPORTED
11016 double maxout8 = pm->maxout8;
11017# endif
11018
11019 /* First some arbitrary no-transform tests: */
11020 if (!pm->this.speed && pm->test_gamma_threshold)
11021 {
11022 perform_gamma_threshold_tests(pm);
11023
11024 if (fail(pm))
11025 return;
11026 }
11027
11028 /* Now some real transforms. */
11029 if (pm->test_gamma_transform)
11030 {
Chris Craikb50c2172013-07-29 15:28:30 -070011031 if (summary)
11032 {
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011033 fflush(stderr);
Chris Craikb50c2172013-07-29 15:28:30 -070011034 printf("Gamma correction error summary\n\n");
11035 printf("The printed value is the maximum error in the pixel values\n");
11036 printf("calculated by the libpng gamma correction code. The error\n");
11037 printf("is calculated as the difference between the output pixel\n");
11038 printf("value (always an integer) and the ideal value from the\n");
11039 printf("libpng specification (typically not an integer).\n\n");
11040
11041 printf("Expect this value to be less than .5 for 8 bit formats,\n");
11042 printf("less than 1 for formats with fewer than 8 bits and a small\n");
11043 printf("number (typically less than 5) for the 16 bit formats.\n");
11044 printf("For performance reasons the value for 16 bit formats\n");
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011045 printf("increases when the image file includes an sBIT chunk.\n");
11046 fflush(stdout);
Chris Craikb50c2172013-07-29 15:28:30 -070011047 }
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011048
11049 init_gamma_errors(pm);
11050 /*TODO: remove this. Necessary because the current libpng
11051 * implementation works in 8 bits:
11052 */
11053 if (pm->test_gamma_expand16)
11054 pm->calculations_use_input_precision = 1;
11055 perform_gamma_transform_tests(pm);
11056 if (!calculations_use_input_precision)
11057 pm->calculations_use_input_precision = 0;
11058
11059 if (summary)
11060 summarize_gamma_errors(pm, 0/*who*/, 1/*low bit depth*/, 1/*indexed*/);
11061
11062 if (fail(pm))
11063 return;
Chris Craikb50c2172013-07-29 15:28:30 -070011064 }
11065
11066 /* The sbit tests produce much larger errors: */
11067 if (pm->test_gamma_sbit)
11068 {
11069 init_gamma_errors(pm);
11070 perform_gamma_sbit_tests(pm);
11071
11072 if (summary)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011073 summarize_gamma_errors(pm, "sBIT", pm->sbitlow < 8U, 1/*indexed*/);
11074
11075 if (fail(pm))
11076 return;
Chris Craikb50c2172013-07-29 15:28:30 -070011077 }
11078
11079#ifdef DO_16BIT /* Should be READ_16BIT_SUPPORTED */
11080 if (pm->test_gamma_scale16)
11081 {
11082 /* The 16 to 8 bit strip operations: */
11083 init_gamma_errors(pm);
11084 perform_gamma_scale16_tests(pm);
11085
11086 if (summary)
11087 {
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011088 fflush(stderr);
11089 printf("\nGamma correction with 16 to 8 bit reduction:\n");
Chris Craikb50c2172013-07-29 15:28:30 -070011090 printf(" 16 bit gray: %.5f\n", pm->error_gray_16);
11091 printf(" 16 bit color: %.5f\n", pm->error_color_16);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011092 fflush(stdout);
Chris Craikb50c2172013-07-29 15:28:30 -070011093 }
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011094
11095 if (fail(pm))
11096 return;
Chris Craikb50c2172013-07-29 15:28:30 -070011097 }
11098#endif
11099
11100#ifdef PNG_READ_BACKGROUND_SUPPORTED
11101 if (pm->test_gamma_background)
11102 {
11103 init_gamma_errors(pm);
11104
11105 /*TODO: remove this. Necessary because the current libpng
11106 * implementation works in 8 bits:
11107 */
11108 if (pm->test_gamma_expand16)
11109 {
11110 pm->calculations_use_input_precision = 1;
11111 pm->maxout8 = .499; /* because the 16 bit background is smashed */
11112 }
11113 perform_gamma_composition_tests(pm, PNG_BACKGROUND_GAMMA_UNIQUE,
11114 pm->test_gamma_expand16);
11115 if (!calculations_use_input_precision)
11116 pm->calculations_use_input_precision = 0;
11117 pm->maxout8 = maxout8;
11118
11119 if (summary)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011120 summarize_gamma_errors(pm, "background", 1, 0/*indexed*/);
11121
11122 if (fail(pm))
11123 return;
Chris Craikb50c2172013-07-29 15:28:30 -070011124 }
11125#endif
11126
11127#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
11128 if (pm->test_gamma_alpha_mode)
11129 {
11130 int do_background;
11131
11132 init_gamma_errors(pm);
11133
11134 /*TODO: remove this. Necessary because the current libpng
11135 * implementation works in 8 bits:
11136 */
11137 if (pm->test_gamma_expand16)
11138 pm->calculations_use_input_precision = 1;
11139 for (do_background = ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD;
11140 do_background <= ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN && !fail(pm);
11141 ++do_background)
11142 perform_gamma_composition_tests(pm, do_background,
11143 pm->test_gamma_expand16);
11144 if (!calculations_use_input_precision)
11145 pm->calculations_use_input_precision = 0;
11146
11147 if (summary)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011148 summarize_gamma_errors(pm, "alpha mode", 1, 0/*indexed*/);
11149
11150 if (fail(pm))
11151 return;
Chris Craikb50c2172013-07-29 15:28:30 -070011152 }
11153#endif
11154}
11155#endif /* PNG_READ_GAMMA_SUPPORTED */
11156#endif /* PNG_READ_SUPPORTED */
11157
11158/* INTERLACE MACRO VALIDATION */
11159/* This is copied verbatim from the specification, it is simply the pass
11160 * number in which each pixel in each 8x8 tile appears. The array must
11161 * be indexed adam7[y][x] and notice that the pass numbers are based at
11162 * 1, not 0 - the base libpng uses.
11163 */
Matt Sarett9b1fe632015-11-25 10:21:17 -050011164static const
Chris Craikb50c2172013-07-29 15:28:30 -070011165png_byte adam7[8][8] =
11166{
11167 { 1,6,4,6,2,6,4,6 },
11168 { 7,7,7,7,7,7,7,7 },
11169 { 5,6,5,6,5,6,5,6 },
11170 { 7,7,7,7,7,7,7,7 },
11171 { 3,6,4,6,3,6,4,6 },
11172 { 7,7,7,7,7,7,7,7 },
11173 { 5,6,5,6,5,6,5,6 },
11174 { 7,7,7,7,7,7,7,7 }
11175};
11176
11177/* This routine validates all the interlace support macros in png.h for
11178 * a variety of valid PNG widths and heights. It uses a number of similarly
11179 * named internal routines that feed off the above array.
11180 */
11181static png_uint_32
11182png_pass_start_row(int pass)
11183{
11184 int x, y;
11185 ++pass;
11186 for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
11187 return y;
11188 return 0xf;
11189}
11190
11191static png_uint_32
11192png_pass_start_col(int pass)
11193{
11194 int x, y;
11195 ++pass;
11196 for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
11197 return x;
11198 return 0xf;
11199}
11200
11201static int
11202png_pass_row_shift(int pass)
11203{
11204 int x, y, base=(-1), inc=8;
11205 ++pass;
11206 for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
11207 {
11208 if (base == (-1))
11209 base = y;
11210 else if (base == y)
11211 {}
11212 else if (inc == y-base)
11213 base=y;
11214 else if (inc == 8)
11215 inc = y-base, base=y;
11216 else if (inc != y-base)
11217 return 0xff; /* error - more than one 'inc' value! */
11218 }
11219
11220 if (base == (-1)) return 0xfe; /* error - no row in pass! */
11221
11222 /* The shift is always 1, 2 or 3 - no pass has all the rows! */
11223 switch (inc)
11224 {
11225case 2: return 1;
11226case 4: return 2;
11227case 8: return 3;
11228default: break;
11229 }
11230
11231 /* error - unrecognized 'inc' */
11232 return (inc << 8) + 0xfd;
11233}
11234
11235static int
11236png_pass_col_shift(int pass)
11237{
11238 int x, y, base=(-1), inc=8;
11239 ++pass;
11240 for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
11241 {
11242 if (base == (-1))
11243 base = x;
11244 else if (base == x)
11245 {}
11246 else if (inc == x-base)
11247 base=x;
11248 else if (inc == 8)
11249 inc = x-base, base=x;
11250 else if (inc != x-base)
11251 return 0xff; /* error - more than one 'inc' value! */
11252 }
11253
11254 if (base == (-1)) return 0xfe; /* error - no row in pass! */
11255
11256 /* The shift is always 1, 2 or 3 - no pass has all the rows! */
11257 switch (inc)
11258 {
11259case 1: return 0; /* pass 7 has all the columns */
11260case 2: return 1;
11261case 4: return 2;
11262case 8: return 3;
11263default: break;
11264 }
11265
11266 /* error - unrecognized 'inc' */
11267 return (inc << 8) + 0xfd;
11268}
11269
11270static png_uint_32
11271png_row_from_pass_row(png_uint_32 yIn, int pass)
11272{
11273 /* By examination of the array: */
11274 switch (pass)
11275 {
11276case 0: return yIn * 8;
11277case 1: return yIn * 8;
11278case 2: return yIn * 8 + 4;
11279case 3: return yIn * 4;
11280case 4: return yIn * 4 + 2;
11281case 5: return yIn * 2;
11282case 6: return yIn * 2 + 1;
11283default: break;
11284 }
11285
11286 return 0xff; /* bad pass number */
11287}
11288
11289static png_uint_32
11290png_col_from_pass_col(png_uint_32 xIn, int pass)
11291{
11292 /* By examination of the array: */
11293 switch (pass)
11294 {
11295case 0: return xIn * 8;
11296case 1: return xIn * 8 + 4;
11297case 2: return xIn * 4;
11298case 3: return xIn * 4 + 2;
11299case 4: return xIn * 2;
11300case 5: return xIn * 2 + 1;
11301case 6: return xIn;
11302default: break;
11303 }
11304
11305 return 0xff; /* bad pass number */
11306}
11307
11308static int
11309png_row_in_interlace_pass(png_uint_32 y, int pass)
11310{
11311 /* Is row 'y' in pass 'pass'? */
11312 int x;
11313 y &= 7;
11314 ++pass;
11315 for (x=0; x<8; ++x) if (adam7[y][x] == pass)
11316 return 1;
11317
11318 return 0;
11319}
11320
11321static int
11322png_col_in_interlace_pass(png_uint_32 x, int pass)
11323{
11324 /* Is column 'x' in pass 'pass'? */
11325 int y;
11326 x &= 7;
11327 ++pass;
11328 for (y=0; y<8; ++y) if (adam7[y][x] == pass)
11329 return 1;
11330
11331 return 0;
11332}
11333
11334static png_uint_32
11335png_pass_rows(png_uint_32 height, int pass)
11336{
11337 png_uint_32 tiles = height>>3;
11338 png_uint_32 rows = 0;
11339 unsigned int x, y;
11340
11341 height &= 7;
11342 ++pass;
11343 for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
11344 {
11345 rows += tiles;
11346 if (y < height) ++rows;
11347 break; /* i.e. break the 'x', column, loop. */
11348 }
11349
11350 return rows;
11351}
11352
11353static png_uint_32
11354png_pass_cols(png_uint_32 width, int pass)
11355{
11356 png_uint_32 tiles = width>>3;
11357 png_uint_32 cols = 0;
11358 unsigned int x, y;
11359
11360 width &= 7;
11361 ++pass;
11362 for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
11363 {
11364 cols += tiles;
11365 if (x < width) ++cols;
11366 break; /* i.e. break the 'y', row, loop. */
11367 }
11368
11369 return cols;
11370}
11371
11372static void
11373perform_interlace_macro_validation(void)
11374{
11375 /* The macros to validate, first those that depend only on pass:
11376 *
11377 * PNG_PASS_START_ROW(pass)
11378 * PNG_PASS_START_COL(pass)
11379 * PNG_PASS_ROW_SHIFT(pass)
11380 * PNG_PASS_COL_SHIFT(pass)
11381 */
11382 int pass;
11383
11384 for (pass=0; pass<7; ++pass)
11385 {
11386 png_uint_32 m, f, v;
11387
11388 m = PNG_PASS_START_ROW(pass);
11389 f = png_pass_start_row(pass);
11390 if (m != f)
11391 {
11392 fprintf(stderr, "PNG_PASS_START_ROW(%d) = %u != %x\n", pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011393 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070011394 }
11395
11396 m = PNG_PASS_START_COL(pass);
11397 f = png_pass_start_col(pass);
11398 if (m != f)
11399 {
11400 fprintf(stderr, "PNG_PASS_START_COL(%d) = %u != %x\n", pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011401 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070011402 }
11403
11404 m = PNG_PASS_ROW_SHIFT(pass);
11405 f = png_pass_row_shift(pass);
11406 if (m != f)
11407 {
11408 fprintf(stderr, "PNG_PASS_ROW_SHIFT(%d) = %u != %x\n", pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011409 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070011410 }
11411
11412 m = PNG_PASS_COL_SHIFT(pass);
11413 f = png_pass_col_shift(pass);
11414 if (m != f)
11415 {
11416 fprintf(stderr, "PNG_PASS_COL_SHIFT(%d) = %u != %x\n", pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011417 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070011418 }
11419
11420 /* Macros that depend on the image or sub-image height too:
11421 *
11422 * PNG_PASS_ROWS(height, pass)
11423 * PNG_PASS_COLS(width, pass)
11424 * PNG_ROW_FROM_PASS_ROW(yIn, pass)
11425 * PNG_COL_FROM_PASS_COL(xIn, pass)
11426 * PNG_ROW_IN_INTERLACE_PASS(y, pass)
11427 * PNG_COL_IN_INTERLACE_PASS(x, pass)
11428 */
11429 for (v=0;;)
11430 {
Leon Scroggins III3cc83ac2017-10-06 11:02:56 -040011431 /* The first two tests overflow if the pass row or column is outside
11432 * the possible range for a 32-bit result. In fact the values should
11433 * never be outside the range for a 31-bit result, but checking for 32
11434 * bits here ensures that if an app uses a bogus pass row or column
11435 * (just so long as it fits in a 32 bit integer) it won't get a
11436 * possibly dangerous overflow.
11437 */
Chris Craikb50c2172013-07-29 15:28:30 -070011438 /* First the base 0 stuff: */
Leon Scroggins III3cc83ac2017-10-06 11:02:56 -040011439 if (v < png_pass_rows(0xFFFFFFFFU, pass))
Chris Craikb50c2172013-07-29 15:28:30 -070011440 {
Leon Scroggins III3cc83ac2017-10-06 11:02:56 -040011441 m = PNG_ROW_FROM_PASS_ROW(v, pass);
11442 f = png_row_from_pass_row(v, pass);
11443 if (m != f)
11444 {
11445 fprintf(stderr, "PNG_ROW_FROM_PASS_ROW(%u, %d) = %u != %x\n",
11446 v, pass, m, f);
11447 exit(99);
11448 }
Chris Craikb50c2172013-07-29 15:28:30 -070011449 }
11450
Leon Scroggins III3cc83ac2017-10-06 11:02:56 -040011451 if (v < png_pass_cols(0xFFFFFFFFU, pass))
Chris Craikb50c2172013-07-29 15:28:30 -070011452 {
Leon Scroggins III3cc83ac2017-10-06 11:02:56 -040011453 m = PNG_COL_FROM_PASS_COL(v, pass);
11454 f = png_col_from_pass_col(v, pass);
11455 if (m != f)
11456 {
11457 fprintf(stderr, "PNG_COL_FROM_PASS_COL(%u, %d) = %u != %x\n",
11458 v, pass, m, f);
11459 exit(99);
11460 }
Chris Craikb50c2172013-07-29 15:28:30 -070011461 }
11462
11463 m = PNG_ROW_IN_INTERLACE_PASS(v, pass);
11464 f = png_row_in_interlace_pass(v, pass);
11465 if (m != f)
11466 {
11467 fprintf(stderr, "PNG_ROW_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
11468 v, pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011469 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070011470 }
11471
11472 m = PNG_COL_IN_INTERLACE_PASS(v, pass);
11473 f = png_col_in_interlace_pass(v, pass);
11474 if (m != f)
11475 {
11476 fprintf(stderr, "PNG_COL_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
11477 v, pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011478 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070011479 }
11480
11481 /* Then the base 1 stuff: */
11482 ++v;
11483 m = PNG_PASS_ROWS(v, pass);
11484 f = png_pass_rows(v, pass);
11485 if (m != f)
11486 {
11487 fprintf(stderr, "PNG_PASS_ROWS(%u, %d) = %u != %x\n",
11488 v, pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011489 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070011490 }
11491
11492 m = PNG_PASS_COLS(v, pass);
11493 f = png_pass_cols(v, pass);
11494 if (m != f)
11495 {
11496 fprintf(stderr, "PNG_PASS_COLS(%u, %d) = %u != %x\n",
11497 v, pass, m, f);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011498 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070011499 }
11500
11501 /* Move to the next v - the stepping algorithm starts skipping
11502 * values above 1024.
11503 */
11504 if (v > 1024)
11505 {
11506 if (v == PNG_UINT_31_MAX)
11507 break;
11508
11509 v = (v << 1) ^ v;
11510 if (v >= PNG_UINT_31_MAX)
11511 v = PNG_UINT_31_MAX-1;
11512 }
11513 }
11514 }
11515}
11516
11517/* Test color encodings. These values are back-calculated from the published
11518 * chromaticities. The values are accurate to about 14 decimal places; 15 are
11519 * given. These values are much more accurate than the ones given in the spec,
11520 * which typically don't exceed 4 decimal places. This allows testing of the
11521 * libpng code to its theoretical accuracy of 4 decimal places. (If pngvalid
11522 * used the published errors the 'slack' permitted would have to be +/-.5E-4 or
11523 * more.)
11524 *
11525 * The png_modifier code assumes that encodings[0] is sRGB and treats it
11526 * specially: do not change the first entry in this list!
11527 */
Matt Sarett9b1fe632015-11-25 10:21:17 -050011528static const color_encoding test_encodings[] =
Chris Craikb50c2172013-07-29 15:28:30 -070011529{
11530/* sRGB: must be first in this list! */
11531/*gamma:*/ { 1/2.2,
11532/*red: */ { 0.412390799265959, 0.212639005871510, 0.019330818715592 },
11533/*green:*/ { 0.357584339383878, 0.715168678767756, 0.119194779794626 },
11534/*blue: */ { 0.180480788401834, 0.072192315360734, 0.950532152249660} },
11535/* Kodak ProPhoto (wide gamut) */
11536/*gamma:*/ { 1/1.6 /*approximate: uses 1.8 power law compared to sRGB 2.4*/,
11537/*red: */ { 0.797760489672303, 0.288071128229293, 0.000000000000000 },
11538/*green:*/ { 0.135185837175740, 0.711843217810102, 0.000000000000000 },
11539/*blue: */ { 0.031349349581525, 0.000085653960605, 0.825104602510460} },
11540/* Adobe RGB (1998) */
11541/*gamma:*/ { 1/(2+51./256),
11542/*red: */ { 0.576669042910131, 0.297344975250536, 0.027031361386412 },
11543/*green:*/ { 0.185558237906546, 0.627363566255466, 0.070688852535827 },
11544/*blue: */ { 0.188228646234995, 0.075291458493998, 0.991337536837639} },
11545/* Adobe Wide Gamut RGB */
11546/*gamma:*/ { 1/(2+51./256),
11547/*red: */ { 0.716500716779386, 0.258728243040113, 0.000000000000000 },
11548/*green:*/ { 0.101020574397477, 0.724682314948566, 0.051211818965388 },
11549/*blue: */ { 0.146774385252705, 0.016589442011321, 0.773892783545073} },
Matt Sarett9b1fe632015-11-25 10:21:17 -050011550/* Fake encoding which selects just the green channel */
11551/*gamma:*/ { 1.45/2.2, /* the 'Mac' gamma */
11552/*red: */ { 0.716500716779386, 0.000000000000000, 0.000000000000000 },
11553/*green:*/ { 0.101020574397477, 1.000000000000000, 0.051211818965388 },
11554/*blue: */ { 0.146774385252705, 0.000000000000000, 0.773892783545073} },
Chris Craikb50c2172013-07-29 15:28:30 -070011555};
11556
11557/* signal handler
11558 *
11559 * This attempts to trap signals and escape without crashing. It needs a
11560 * context pointer so that it can throw an exception (call longjmp) to recover
11561 * from the condition; this is handled by making the png_modifier used by 'main'
11562 * into a global variable.
11563 */
11564static png_modifier pm;
11565
11566static void signal_handler(int signum)
11567{
11568
11569 size_t pos = 0;
11570 char msg[64];
11571
11572 pos = safecat(msg, sizeof msg, pos, "caught signal: ");
11573
11574 switch (signum)
11575 {
11576 case SIGABRT:
11577 pos = safecat(msg, sizeof msg, pos, "abort");
11578 break;
11579
11580 case SIGFPE:
11581 pos = safecat(msg, sizeof msg, pos, "floating point exception");
11582 break;
11583
11584 case SIGILL:
11585 pos = safecat(msg, sizeof msg, pos, "illegal instruction");
11586 break;
11587
11588 case SIGINT:
11589 pos = safecat(msg, sizeof msg, pos, "interrupt");
11590 break;
11591
11592 case SIGSEGV:
11593 pos = safecat(msg, sizeof msg, pos, "invalid memory access");
11594 break;
11595
11596 case SIGTERM:
11597 pos = safecat(msg, sizeof msg, pos, "termination request");
11598 break;
11599
11600 default:
11601 pos = safecat(msg, sizeof msg, pos, "unknown ");
11602 pos = safecatn(msg, sizeof msg, pos, signum);
11603 break;
11604 }
11605
11606 store_log(&pm.this, NULL/*png_structp*/, msg, 1/*error*/);
11607
11608 /* And finally throw an exception so we can keep going, unless this is
11609 * SIGTERM in which case stop now.
11610 */
11611 if (signum != SIGTERM)
11612 {
11613 struct exception_context *the_exception_context =
11614 &pm.this.exception_context;
11615
11616 Throw &pm.this;
11617 }
11618
11619 else
11620 exit(1);
11621}
11622
11623/* main program */
11624int main(int argc, char **argv)
11625{
Matt Sarett9b1fe632015-11-25 10:21:17 -050011626 int summary = 1; /* Print the error summary at the end */
11627 int memstats = 0; /* Print memory statistics at the end */
Chris Craikb50c2172013-07-29 15:28:30 -070011628
11629 /* Create the given output file on success: */
Matt Sarett9b1fe632015-11-25 10:21:17 -050011630 const char *touch = NULL;
Chris Craikb50c2172013-07-29 15:28:30 -070011631
11632 /* This is an array of standard gamma values (believe it or not I've seen
11633 * every one of these mentioned somewhere.)
11634 *
11635 * In the following list the most useful values are first!
11636 */
11637 static double
11638 gammas[]={2.2, 1.0, 2.2/1.45, 1.8, 1.5, 2.4, 2.5, 2.62, 2.9};
11639
11640 /* This records the command and arguments: */
11641 size_t cp = 0;
11642 char command[1024];
11643
11644 anon_context(&pm.this);
11645
Matt Sarett9b1fe632015-11-25 10:21:17 -050011646 gnu_volatile(summary)
11647 gnu_volatile(memstats)
11648 gnu_volatile(touch)
11649
Chris Craikb50c2172013-07-29 15:28:30 -070011650 /* Add appropriate signal handlers, just the ANSI specified ones: */
11651 signal(SIGABRT, signal_handler);
11652 signal(SIGFPE, signal_handler);
11653 signal(SIGILL, signal_handler);
11654 signal(SIGINT, signal_handler);
11655 signal(SIGSEGV, signal_handler);
11656 signal(SIGTERM, signal_handler);
11657
11658#ifdef HAVE_FEENABLEEXCEPT
11659 /* Only required to enable FP exceptions on platforms where they start off
11660 * disabled; this is not necessary but if it is not done pngvalid will likely
11661 * end up ignoring FP conditions that other platforms fault.
11662 */
11663 feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
11664#endif
11665
11666 modifier_init(&pm);
11667
11668 /* Preallocate the image buffer, because we know how big it needs to be,
11669 * note that, for testing purposes, it is deliberately mis-aligned by tag
11670 * bytes either side. All rows have an additional five bytes of padding for
11671 * overwrite checking.
11672 */
11673 store_ensure_image(&pm.this, NULL, 2, TRANSFORM_ROWMAX, TRANSFORM_HEIGHTMAX);
11674
11675 /* Don't give argv[0], it's normally some horrible libtool string: */
11676 cp = safecat(command, sizeof command, cp, "pngvalid");
11677
11678 /* Default to error on warning: */
11679 pm.this.treat_warnings_as_errors = 1;
11680
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011681 /* Default assume_16_bit_calculations appropriately; this tells the checking
11682 * code that 16-bit arithmetic is used for 8-bit samples when it would make a
11683 * difference.
11684 */
11685 pm.assume_16_bit_calculations = PNG_LIBPNG_VER >= 10700;
11686
11687 /* Currently 16 bit expansion happens at the end of the pipeline, so the
11688 * calculations are done in the input bit depth not the output.
11689 *
11690 * TODO: fix this
11691 */
11692 pm.calculations_use_input_precision = 1U;
11693
Chris Craikb50c2172013-07-29 15:28:30 -070011694 /* Store the test gammas */
11695 pm.gammas = gammas;
Matt Sarett9b1fe632015-11-25 10:21:17 -050011696 pm.ngammas = ARRAY_SIZE(gammas);
Chris Craikb50c2172013-07-29 15:28:30 -070011697 pm.ngamma_tests = 0; /* default to off */
11698
Matt Sarett9b1fe632015-11-25 10:21:17 -050011699 /* Low bit depth gray images don't do well in the gamma tests, until
11700 * this is fixed turn them off for some gamma cases:
11701 */
11702# ifdef PNG_WRITE_tRNS_SUPPORTED
11703 pm.test_tRNS = 1;
11704# endif
11705 pm.test_lbg = PNG_LIBPNG_VER >= 10600;
11706 pm.test_lbg_gamma_threshold = 1;
11707 pm.test_lbg_gamma_transform = PNG_LIBPNG_VER >= 10600;
11708 pm.test_lbg_gamma_sbit = 1;
11709 pm.test_lbg_gamma_composition = PNG_LIBPNG_VER >= 10700;
11710
Chris Craikb50c2172013-07-29 15:28:30 -070011711 /* And the test encodings */
11712 pm.encodings = test_encodings;
Matt Sarett9b1fe632015-11-25 10:21:17 -050011713 pm.nencodings = ARRAY_SIZE(test_encodings);
Chris Craikb50c2172013-07-29 15:28:30 -070011714
Matt Sarett9b1fe632015-11-25 10:21:17 -050011715# if PNG_LIBPNG_VER < 10700
11716 pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */
11717# else
11718 pm.sbitlow = 1U;
11719# endif
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011720
Chris Craikb50c2172013-07-29 15:28:30 -070011721 /* The following allows results to pass if they correspond to anything in the
11722 * transformed range [input-.5,input+.5]; this is is required because of the
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011723 * way libpng treates the 16_TO_8 flag when building the gamma tables in
11724 * releases up to 1.6.0.
Chris Craikb50c2172013-07-29 15:28:30 -070011725 *
11726 * TODO: review this
11727 */
11728 pm.use_input_precision_16to8 = 1U;
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011729 pm.use_input_precision_sbit = 1U; /* because libpng now rounds sBIT */
Chris Craikb50c2172013-07-29 15:28:30 -070011730
11731 /* Some default values (set the behavior for 'make check' here).
11732 * These values simply control the maximum error permitted in the gamma
xNombred07bb0d2020-03-10 20:17:12 +010011733 * transformations. The practical limits for human perception are described
Chris Craikb50c2172013-07-29 15:28:30 -070011734 * below (the setting for maxpc16), however for 8 bit encodings it isn't
11735 * possible to meet the accepted capabilities of human vision - i.e. 8 bit
11736 * images can never be good enough, regardless of encoding.
11737 */
11738 pm.maxout8 = .1; /* Arithmetic error in *encoded* value */
11739 pm.maxabs8 = .00005; /* 1/20000 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011740 pm.maxcalc8 = 1./255; /* +/-1 in 8 bits for compose errors */
Chris Craikb50c2172013-07-29 15:28:30 -070011741 pm.maxpc8 = .499; /* I.e., .499% fractional error */
11742 pm.maxout16 = .499; /* Error in *encoded* value */
11743 pm.maxabs16 = .00005;/* 1/20000 */
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011744 pm.maxcalc16 =1./65535;/* +/-1 in 16 bits for compose errors */
Matt Sarett06f10872016-01-04 12:56:20 -050011745# if PNG_LIBPNG_VER < 10700
11746 pm.maxcalcG = 1./((1<<PNG_MAX_GAMMA_8)-1);
11747# else
11748 pm.maxcalcG = 1./((1<<16)-1);
11749# endif
Chris Craikb50c2172013-07-29 15:28:30 -070011750
11751 /* NOTE: this is a reasonable perceptual limit. We assume that humans can
11752 * perceive light level differences of 1% over a 100:1 range, so we need to
11753 * maintain 1 in 10000 accuracy (in linear light space), which is what the
11754 * following guarantees. It also allows significantly higher errors at
11755 * higher 16 bit values, which is important for performance. The actual
11756 * maximum 16 bit error is about +/-1.9 in the fixed point implementation but
11757 * this is only allowed for values >38149 by the following:
11758 */
11759 pm.maxpc16 = .005; /* I.e., 1/200% - 1/20000 */
11760
11761 /* Now parse the command line options. */
11762 while (--argc >= 1)
11763 {
11764 int catmore = 0; /* Set if the argument has an argument. */
11765
11766 /* Record each argument for posterity: */
11767 cp = safecat(command, sizeof command, cp, " ");
11768 cp = safecat(command, sizeof command, cp, *++argv);
11769
11770 if (strcmp(*argv, "-v") == 0)
11771 pm.this.verbose = 1;
11772
11773 else if (strcmp(*argv, "-l") == 0)
11774 pm.log = 1;
11775
11776 else if (strcmp(*argv, "-q") == 0)
11777 summary = pm.this.verbose = pm.log = 0;
11778
Matt Sarett9b1fe632015-11-25 10:21:17 -050011779 else if (strcmp(*argv, "-w") == 0 ||
11780 strcmp(*argv, "--strict") == 0)
Matt Sarett11466862016-02-19 13:41:30 -050011781 pm.this.treat_warnings_as_errors = 1; /* NOTE: this is the default! */
11782
11783 else if (strcmp(*argv, "--nostrict") == 0)
Chris Craikb50c2172013-07-29 15:28:30 -070011784 pm.this.treat_warnings_as_errors = 0;
11785
11786 else if (strcmp(*argv, "--speed") == 0)
11787 pm.this.speed = 1, pm.ngamma_tests = pm.ngammas, pm.test_standard = 0,
11788 summary = 0;
11789
11790 else if (strcmp(*argv, "--memory") == 0)
11791 memstats = 1;
11792
11793 else if (strcmp(*argv, "--size") == 0)
11794 pm.test_size = 1;
11795
11796 else if (strcmp(*argv, "--nosize") == 0)
11797 pm.test_size = 0;
11798
11799 else if (strcmp(*argv, "--standard") == 0)
11800 pm.test_standard = 1;
11801
11802 else if (strcmp(*argv, "--nostandard") == 0)
11803 pm.test_standard = 0;
11804
11805 else if (strcmp(*argv, "--transform") == 0)
11806 pm.test_transform = 1;
11807
11808 else if (strcmp(*argv, "--notransform") == 0)
11809 pm.test_transform = 0;
11810
11811#ifdef PNG_READ_TRANSFORMS_SUPPORTED
11812 else if (strncmp(*argv, "--transform-disable=",
11813 sizeof "--transform-disable") == 0)
11814 {
11815 pm.test_transform = 1;
11816 transform_disable(*argv + sizeof "--transform-disable");
11817 }
11818
11819 else if (strncmp(*argv, "--transform-enable=",
11820 sizeof "--transform-enable") == 0)
11821 {
11822 pm.test_transform = 1;
11823 transform_enable(*argv + sizeof "--transform-enable");
11824 }
11825#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
11826
11827 else if (strcmp(*argv, "--gamma") == 0)
11828 {
11829 /* Just do two gamma tests here (2.2 and linear) for speed: */
11830 pm.ngamma_tests = 2U;
11831 pm.test_gamma_threshold = 1;
11832 pm.test_gamma_transform = 1;
11833 pm.test_gamma_sbit = 1;
11834 pm.test_gamma_scale16 = 1;
Matt Sarett9b1fe632015-11-25 10:21:17 -050011835 pm.test_gamma_background = 1; /* composition */
Chris Craikb50c2172013-07-29 15:28:30 -070011836 pm.test_gamma_alpha_mode = 1;
11837 }
11838
11839 else if (strcmp(*argv, "--nogamma") == 0)
11840 pm.ngamma_tests = 0;
11841
11842 else if (strcmp(*argv, "--gamma-threshold") == 0)
11843 pm.ngamma_tests = 2U, pm.test_gamma_threshold = 1;
11844
11845 else if (strcmp(*argv, "--nogamma-threshold") == 0)
11846 pm.test_gamma_threshold = 0;
11847
11848 else if (strcmp(*argv, "--gamma-transform") == 0)
11849 pm.ngamma_tests = 2U, pm.test_gamma_transform = 1;
11850
11851 else if (strcmp(*argv, "--nogamma-transform") == 0)
11852 pm.test_gamma_transform = 0;
11853
11854 else if (strcmp(*argv, "--gamma-sbit") == 0)
11855 pm.ngamma_tests = 2U, pm.test_gamma_sbit = 1;
11856
11857 else if (strcmp(*argv, "--nogamma-sbit") == 0)
11858 pm.test_gamma_sbit = 0;
11859
11860 else if (strcmp(*argv, "--gamma-16-to-8") == 0)
11861 pm.ngamma_tests = 2U, pm.test_gamma_scale16 = 1;
11862
11863 else if (strcmp(*argv, "--nogamma-16-to-8") == 0)
11864 pm.test_gamma_scale16 = 0;
11865
11866 else if (strcmp(*argv, "--gamma-background") == 0)
11867 pm.ngamma_tests = 2U, pm.test_gamma_background = 1;
11868
11869 else if (strcmp(*argv, "--nogamma-background") == 0)
11870 pm.test_gamma_background = 0;
11871
11872 else if (strcmp(*argv, "--gamma-alpha-mode") == 0)
11873 pm.ngamma_tests = 2U, pm.test_gamma_alpha_mode = 1;
11874
11875 else if (strcmp(*argv, "--nogamma-alpha-mode") == 0)
11876 pm.test_gamma_alpha_mode = 0;
11877
11878 else if (strcmp(*argv, "--expand16") == 0)
11879 pm.test_gamma_expand16 = 1;
11880
11881 else if (strcmp(*argv, "--noexpand16") == 0)
11882 pm.test_gamma_expand16 = 0;
11883
Matt Sarett9b1fe632015-11-25 10:21:17 -050011884 else if (strcmp(*argv, "--low-depth-gray") == 0)
11885 pm.test_lbg = pm.test_lbg_gamma_threshold =
11886 pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
11887 pm.test_lbg_gamma_composition = 1;
11888
11889 else if (strcmp(*argv, "--nolow-depth-gray") == 0)
11890 pm.test_lbg = pm.test_lbg_gamma_threshold =
11891 pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
11892 pm.test_lbg_gamma_composition = 0;
11893
11894# ifdef PNG_WRITE_tRNS_SUPPORTED
11895 else if (strcmp(*argv, "--tRNS") == 0)
11896 pm.test_tRNS = 1;
11897# endif
11898
11899 else if (strcmp(*argv, "--notRNS") == 0)
11900 pm.test_tRNS = 0;
11901
Chris Craikb50c2172013-07-29 15:28:30 -070011902 else if (strcmp(*argv, "--more-gammas") == 0)
11903 pm.ngamma_tests = 3U;
11904
11905 else if (strcmp(*argv, "--all-gammas") == 0)
11906 pm.ngamma_tests = pm.ngammas;
11907
11908 else if (strcmp(*argv, "--progressive-read") == 0)
11909 pm.this.progressive = 1;
11910
11911 else if (strcmp(*argv, "--use-update-info") == 0)
11912 ++pm.use_update_info; /* Can call multiple times */
11913
11914 else if (strcmp(*argv, "--interlace") == 0)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011915 {
Matt Sarett9b1fe632015-11-25 10:21:17 -050011916# if CAN_WRITE_INTERLACE
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011917 pm.interlace_type = PNG_INTERLACE_ADAM7;
Matt Sarett06f10872016-01-04 12:56:20 -050011918# else /* !CAN_WRITE_INTERLACE */
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011919 fprintf(stderr, "pngvalid: no write interlace support\n");
11920 return SKIP;
Matt Sarett06f10872016-01-04 12:56:20 -050011921# endif /* !CAN_WRITE_INTERLACE */
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011922 }
Chris Craikb50c2172013-07-29 15:28:30 -070011923
11924 else if (strcmp(*argv, "--use-input-precision") == 0)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011925 pm.use_input_precision = 1U;
11926
11927 else if (strcmp(*argv, "--use-calculation-precision") == 0)
11928 pm.use_input_precision = 0;
Chris Craikb50c2172013-07-29 15:28:30 -070011929
11930 else if (strcmp(*argv, "--calculations-use-input-precision") == 0)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011931 pm.calculations_use_input_precision = 1U;
Chris Craikb50c2172013-07-29 15:28:30 -070011932
11933 else if (strcmp(*argv, "--assume-16-bit-calculations") == 0)
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011934 pm.assume_16_bit_calculations = 1U;
Chris Craikb50c2172013-07-29 15:28:30 -070011935
11936 else if (strcmp(*argv, "--calculations-follow-bit-depth") == 0)
11937 pm.calculations_use_input_precision =
11938 pm.assume_16_bit_calculations = 0;
11939
11940 else if (strcmp(*argv, "--exhaustive") == 0)
11941 pm.test_exhaustive = 1;
11942
11943 else if (argc > 1 && strcmp(*argv, "--sbitlow") == 0)
11944 --argc, pm.sbitlow = (png_byte)atoi(*++argv), catmore = 1;
11945
11946 else if (argc > 1 && strcmp(*argv, "--touch") == 0)
11947 --argc, touch = *++argv, catmore = 1;
11948
11949 else if (argc > 1 && strncmp(*argv, "--max", 5) == 0)
11950 {
11951 --argc;
11952
11953 if (strcmp(5+*argv, "abs8") == 0)
11954 pm.maxabs8 = atof(*++argv);
11955
11956 else if (strcmp(5+*argv, "abs16") == 0)
11957 pm.maxabs16 = atof(*++argv);
11958
11959 else if (strcmp(5+*argv, "calc8") == 0)
11960 pm.maxcalc8 = atof(*++argv);
11961
11962 else if (strcmp(5+*argv, "calc16") == 0)
11963 pm.maxcalc16 = atof(*++argv);
11964
11965 else if (strcmp(5+*argv, "out8") == 0)
11966 pm.maxout8 = atof(*++argv);
11967
11968 else if (strcmp(5+*argv, "out16") == 0)
11969 pm.maxout16 = atof(*++argv);
11970
11971 else if (strcmp(5+*argv, "pc8") == 0)
11972 pm.maxpc8 = atof(*++argv);
11973
11974 else if (strcmp(5+*argv, "pc16") == 0)
11975 pm.maxpc16 = atof(*++argv);
11976
11977 else
11978 {
11979 fprintf(stderr, "pngvalid: %s: unknown 'max' option\n", *argv);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011980 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070011981 }
11982
11983 catmore = 1;
11984 }
11985
11986 else if (strcmp(*argv, "--log8") == 0)
11987 --argc, pm.log8 = atof(*++argv), catmore = 1;
11988
11989 else if (strcmp(*argv, "--log16") == 0)
11990 --argc, pm.log16 = atof(*++argv), catmore = 1;
11991
Sireesh Tripurarib478e662014-05-09 15:15:10 +053011992#ifdef PNG_SET_OPTION_SUPPORTED
11993 else if (strncmp(*argv, "--option=", 9) == 0)
11994 {
11995 /* Syntax of the argument is <option>:{on|off} */
11996 const char *arg = 9+*argv;
11997 unsigned char option=0, setting=0;
11998
Matt Sarett9b1fe632015-11-25 10:21:17 -050011999#ifdef PNG_ARM_NEON
Sireesh Tripurarib478e662014-05-09 15:15:10 +053012000 if (strncmp(arg, "arm-neon:", 9) == 0)
12001 option = PNG_ARM_NEON, arg += 9;
12002
12003 else
12004#endif
Matt Sarett9b1fe632015-11-25 10:21:17 -050012005#ifdef PNG_EXTENSIONS
12006 if (strncmp(arg, "extensions:", 11) == 0)
12007 option = PNG_EXTENSIONS, arg += 11;
12008
12009 else
12010#endif
Sireesh Tripurarib478e662014-05-09 15:15:10 +053012011#ifdef PNG_MAXIMUM_INFLATE_WINDOW
12012 if (strncmp(arg, "max-inflate-window:", 19) == 0)
12013 option = PNG_MAXIMUM_INFLATE_WINDOW, arg += 19;
12014
12015 else
12016#endif
12017 {
12018 fprintf(stderr, "pngvalid: %s: %s: unknown option\n", *argv, arg);
12019 exit(99);
12020 }
12021
12022 if (strcmp(arg, "off") == 0)
12023 setting = PNG_OPTION_OFF;
12024
12025 else if (strcmp(arg, "on") == 0)
12026 setting = PNG_OPTION_ON;
12027
12028 else
12029 {
12030 fprintf(stderr,
12031 "pngvalid: %s: %s: unknown setting (use 'on' or 'off')\n",
12032 *argv, arg);
12033 exit(99);
12034 }
12035
12036 pm.this.options[pm.this.noptions].option = option;
12037 pm.this.options[pm.this.noptions++].setting = setting;
12038 }
12039#endif /* PNG_SET_OPTION_SUPPORTED */
12040
Chris Craikb50c2172013-07-29 15:28:30 -070012041 else
12042 {
12043 fprintf(stderr, "pngvalid: %s: unknown argument\n", *argv);
Sireesh Tripurarib478e662014-05-09 15:15:10 +053012044 exit(99);
Chris Craikb50c2172013-07-29 15:28:30 -070012045 }
12046
12047 if (catmore) /* consumed an extra *argv */
12048 {
12049 cp = safecat(command, sizeof command, cp, " ");
12050 cp = safecat(command, sizeof command, cp, *argv);
12051 }
12052 }
12053
12054 /* If pngvalid is run with no arguments default to a reasonable set of the
12055 * tests.
12056 */
12057 if (pm.test_standard == 0 && pm.test_size == 0 && pm.test_transform == 0 &&
12058 pm.ngamma_tests == 0)
12059 {
12060 /* Make this do all the tests done in the test shell scripts with the same
12061 * parameters, where possible. The limitation is that all the progressive
12062 * read and interlace stuff has to be done in separate runs, so only the
12063 * basic 'standard' and 'size' tests are done.
12064 */
12065 pm.test_standard = 1;
12066 pm.test_size = 1;
12067 pm.test_transform = 1;
12068 pm.ngamma_tests = 2U;
12069 }
12070
12071 if (pm.ngamma_tests > 0 &&
12072 pm.test_gamma_threshold == 0 && pm.test_gamma_transform == 0 &&
12073 pm.test_gamma_sbit == 0 && pm.test_gamma_scale16 == 0 &&
12074 pm.test_gamma_background == 0 && pm.test_gamma_alpha_mode == 0)
12075 {
12076 pm.test_gamma_threshold = 1;
12077 pm.test_gamma_transform = 1;
12078 pm.test_gamma_sbit = 1;
12079 pm.test_gamma_scale16 = 1;
12080 pm.test_gamma_background = 1;
12081 pm.test_gamma_alpha_mode = 1;
12082 }
12083
12084 else if (pm.ngamma_tests == 0)
12085 {
12086 /* Nothing to test so turn everything off: */
12087 pm.test_gamma_threshold = 0;
12088 pm.test_gamma_transform = 0;
12089 pm.test_gamma_sbit = 0;
12090 pm.test_gamma_scale16 = 0;
12091 pm.test_gamma_background = 0;
12092 pm.test_gamma_alpha_mode = 0;
12093 }
12094
12095 Try
12096 {
12097 /* Make useful base images */
Matt Sarett9b1fe632015-11-25 10:21:17 -050012098 make_transform_images(&pm);
Chris Craikb50c2172013-07-29 15:28:30 -070012099
12100 /* Perform the standard and gamma tests. */
12101 if (pm.test_standard)
12102 {
12103 perform_interlace_macro_validation();
12104 perform_formatting_test(&pm.this);
12105# ifdef PNG_READ_SUPPORTED
12106 perform_standard_test(&pm);
12107# endif
12108 perform_error_test(&pm);
12109 }
12110
12111 /* Various oddly sized images: */
12112 if (pm.test_size)
12113 {
12114 make_size_images(&pm.this);
12115# ifdef PNG_READ_SUPPORTED
12116 perform_size_test(&pm);
12117# endif
12118 }
12119
12120#ifdef PNG_READ_TRANSFORMS_SUPPORTED
12121 /* Combinatorial transforms: */
12122 if (pm.test_transform)
12123 perform_transform_test(&pm);
12124#endif /* PNG_READ_TRANSFORMS_SUPPORTED */
12125
12126#ifdef PNG_READ_GAMMA_SUPPORTED
12127 if (pm.ngamma_tests > 0)
12128 perform_gamma_test(&pm, summary);
12129#endif
12130 }
12131
12132 Catch_anonymous
12133 {
12134 fprintf(stderr, "pngvalid: test aborted (probably failed in cleanup)\n");
12135 if (!pm.this.verbose)
12136 {
12137 if (pm.this.error[0] != 0)
12138 fprintf(stderr, "pngvalid: first error: %s\n", pm.this.error);
12139
12140 fprintf(stderr, "pngvalid: run with -v to see what happened\n");
12141 }
12142 exit(1);
12143 }
12144
12145 if (summary)
12146 {
12147 printf("%s: %s (%s point arithmetic)\n",
12148 (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
12149 pm.this.nwarnings)) ? "FAIL" : "PASS",
12150 command,
12151#if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || PNG_LIBPNG_VER < 10500
12152 "floating"
12153#else
12154 "fixed"
12155#endif
12156 );
12157 }
12158
12159 if (memstats)
12160 {
12161 printf("Allocated memory statistics (in bytes):\n"
12162 "\tread %lu maximum single, %lu peak, %lu total\n"
12163 "\twrite %lu maximum single, %lu peak, %lu total\n",
12164 (unsigned long)pm.this.read_memory_pool.max_max,
12165 (unsigned long)pm.this.read_memory_pool.max_limit,
12166 (unsigned long)pm.this.read_memory_pool.max_total,
12167 (unsigned long)pm.this.write_memory_pool.max_max,
12168 (unsigned long)pm.this.write_memory_pool.max_limit,
12169 (unsigned long)pm.this.write_memory_pool.max_total);
12170 }
12171
12172 /* Do this here to provoke memory corruption errors in memory not directly
12173 * allocated by libpng - not a complete test, but better than nothing.
12174 */
12175 store_delete(&pm.this);
12176
12177 /* Error exit if there are any errors, and maybe if there are any
12178 * warnings.
12179 */
12180 if (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
12181 pm.this.nwarnings))
12182 {
12183 if (!pm.this.verbose)
12184 fprintf(stderr, "pngvalid: %s\n", pm.this.error);
12185
12186 fprintf(stderr, "pngvalid: %d errors, %d warnings\n", pm.this.nerrors,
12187 pm.this.nwarnings);
12188
12189 exit(1);
12190 }
12191
12192 /* Success case. */
12193 if (touch != NULL)
12194 {
12195 FILE *fsuccess = fopen(touch, "wt");
12196
12197 if (fsuccess != NULL)
12198 {
12199 int error = 0;
12200 fprintf(fsuccess, "PNG validation succeeded\n");
12201 fflush(fsuccess);
12202 error = ferror(fsuccess);
12203
12204 if (fclose(fsuccess) || error)
12205 {
12206 fprintf(stderr, "%s: write failed\n", touch);
12207 exit(1);
12208 }
12209 }
12210
12211 else
12212 {
12213 fprintf(stderr, "%s: open failed\n", touch);
12214 exit(1);
12215 }
12216 }
12217
Sireesh Tripurarib478e662014-05-09 15:15:10 +053012218 /* This is required because some very minimal configurations do not use it:
12219 */
12220 UNUSED(fail)
Chris Craikb50c2172013-07-29 15:28:30 -070012221 return 0;
12222}
Sireesh Tripurarib478e662014-05-09 15:15:10 +053012223#else /* write or low level APIs not supported */
Chris Craikb50c2172013-07-29 15:28:30 -070012224int main(void)
12225{
Sireesh Tripurarib478e662014-05-09 15:15:10 +053012226 fprintf(stderr,
12227 "pngvalid: no low level write support in libpng, all tests skipped\n");
Chris Craikb50c2172013-07-29 15:28:30 -070012228 /* So the test is skipped: */
Sireesh Tripurarib478e662014-05-09 15:15:10 +053012229 return SKIP;
Chris Craikb50c2172013-07-29 15:28:30 -070012230}
12231#endif