1 
2 /* pngpriv.h - private declarations for use inside libpng
3  *
4  * Last changed in libpng 1.7.0 [(PENDING RELEASE)]
5  * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
6  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
7  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
8  *
9  * This code is released under the libpng license.
10  * For conditions of distribution and use, see the disclaimer
11  * and license in png.h
12  */
13 
14 /* The symbols declared in this file (including the functions declared
15  * as extern) are PRIVATE.  They are not part of the libpng public
16  * interface, and are not recommended for use by regular applications.
17  * Some of them may become public in the future; others may stay private,
18  * change in an incompatible way, or even disappear.
19  * Although the libpng users are not forbidden to include this header,
20  * they should be well aware of the issues that may arise from doing so.
21  */
22 
23 #ifndef PNGPRIV_H
24 #define PNGPRIV_H
25 
26 /* Feature Test Macros.  The following are defined here to ensure that correctly
27  * implemented libraries reveal the APIs libpng needs to build and hide those
28  * that are not needed and potentially damaging to the compilation.
29  *
30  * Feature Test Macros must be defined before any system header is included (see
31  * POSIX 1003.1 2.8.2 "POSIX Symbols."
32  *
33  * These macros only have an effect if the operating system supports either
34  * POSIX 1003.1 or C99, or both.  On other operating systems (particularly
35  * Windows/Visual Studio) there is no effect; the OS specific tests below are
36  * still required (as of 2011-05-02.)
37  */
38 #define _POSIX_SOURCE 1 /* Just the POSIX 1003.1 and C89 APIs */
39 
40 #ifndef PNG_VERSION_INFO_ONLY
41 /* Keep standard libraries at the top of this file */
42 
43 /* Standard library headers not required by png.h: */
44 #  include <stdlib.h>
45 #  include <string.h>
46 
47 /* For headers only required with some build configurations see the lines after
48  * pnglibconf.h is included!
49  */
50 
51 #endif /* VERSION_INFO_ONLY */
52 
53 #define PNGLIB_BUILD /*libpng is being built, not used*/
54 
55 /* If HAVE_CONFIG_H is defined during the build then the build system must
56  * provide an appropriate "config.h" file on the include path.  The header file
57  * must provide definitions as required below (search for "HAVE_CONFIG_H");
58  * see configure.ac for more details of the requirements.  The macro
59  * "PNG_NO_CONFIG_H" is provided for maintainers to test for dependencies on
60  * 'configure'; define this macro to prevent the configure build including the
61  * configure generated config.h.  Libpng is expected to compile without *any*
62  * special build system support on a reasonably ANSI-C compliant system.
63  */
64 #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
65 #  include <config.h>
66 
67    /* Pick up the definition of 'restrict' from config.h if it was read: */
68 #  define PNG_RESTRICT restrict
69 #endif
70 
71 /* To support symbol prefixing it is necessary to know *before* including png.h
72  * whether the fixed point (and maybe other) APIs are exported, because if they
73  * are not internal definitions may be required.  This is handled below just
74  * before png.h is included, but load the configuration now if it is available.
75  */
76 #ifndef PNGLCONF_H
77 #  include "pnglibconf.h"
78 #endif
79 
80 /* Local renames may change non-exported API functions from png.h */
81 #if defined(PNG_PREFIX) && !defined(PNGPREFIX_H)
82 #  include "pngprefix.h"
83 #endif
84 
85 #ifdef PNG_USER_CONFIG
86 #  include "pngusr.h"
87    /* These should have been defined in pngusr.h */
88 #  ifndef PNG_USER_PRIVATEBUILD
89 #    define PNG_USER_PRIVATEBUILD "Custom libpng build"
90 #  endif
91 #  ifndef PNG_USER_DLLFNAME_POSTFIX
92 #    define PNG_USER_DLLFNAME_POSTFIX "Cb"
93 #  endif
94 #endif
95 
96 #ifndef PNG_VERSION_INFO_ONLY
97 /* Additional standard libaries required in certain cases, put only standard
98  * ANSI-C89 headers here.  If not available, or non-functional, the problem
99  * should be fixed by writing a wrapper for the header and the file on your
100  * include path.
101  */
102 #if defined(PNG_sCAL_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
103    /* png.c requires the following ANSI-C constants if the conversion of
104     * floating point to ASCII is implemented therein:
105     *
106     *  DBL_MIN_10_EXP Minimum negative integer such that 10^integer is a
107     *                 normalized (double) value.
108     *  DBL_DIG  Maximum number of decimal digits (can be set to any constant)
109     *  DBL_MIN  Smallest normalized fp number (can be set to an arbitrary value)
110     *  DBL_MAX  Maximum floating point number (can be set to an arbitrary value)
111     */
112 #  include <float.h>
113 #endif /* sCAL && FLOATING_POINT */
114 
115 #if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) ||\
116    defined(PNG_FLOATING_POINT_SUPPORTED)
117    /* ANSI-C90 math functions are required.  Full compliance with the standard
118     * is probably not a requirement, but the functions must exist and be
119     * declared in <math.h>
120     */
121 #  include <math.h>
122 #endif /* FLOATING_ARITHMETIC || FLOATING_POINT */
123 
124 #endif /* VERSION_INFO_ONLY */
125 
126 /* Is this a build of a DLL where compilation of the object modules requires
127  * different preprocessor settings to those required for a simple library?  If
128  * so PNG_BUILD_DLL must be set.
129  *
130  * If libpng is used inside a DLL but that DLL does not export the libpng APIs
131  * PNG_BUILD_DLL must not be set.  To avoid the code below kicking in build a
132  * static library of libpng then link the DLL against that.
133  */
134 #ifndef PNG_BUILD_DLL
135 #  ifdef DLL_EXPORT
136       /* This is set by libtool when files are compiled for a DLL; libtool
137        * always compiles twice, even on systems where it isn't necessary.  Set
138        * PNG_BUILD_DLL in case it is necessary:
139        */
140 #     define PNG_BUILD_DLL
141 #  else
142 #     ifdef _WINDLL
143          /* This is set by the Microsoft Visual Studio IDE in projects that
144           * build a DLL.  It can't easily be removed from those projects (it
145           * isn't visible in the Visual Studio UI) so it is a fairly reliable
146           * indication that PNG_IMPEXP needs to be set to the DLL export
147           * attributes.
148           */
149 #        define PNG_BUILD_DLL
150 #     else
151 #        ifdef __DLL__
152             /* This is set by the Borland C system when compiling for a DLL
153              * (as above.)
154              */
155 #           define PNG_BUILD_DLL
156 #        else
157             /* Add additional compiler cases here. */
158 #        endif
159 #     endif
160 #  endif
161 #endif /* Setting PNG_BUILD_DLL if required */
162 
163 /* See pngconf.h for more details: the builder of the library may set this on
164  * the command line to the right thing for the specific compilation system or it
165  * may be automagically set above (at present we know of no system where it does
166  * need to be set on the command line.)
167  *
168  * PNG_IMPEXP must be set here when building the library to prevent pngconf.h
169  * setting it to the "import" setting for a DLL build.
170  */
171 #ifndef PNG_IMPEXP
172 #  ifdef PNG_BUILD_DLL
173 #     define PNG_IMPEXP PNG_DLL_EXPORT
174 #  else
175       /* Not building a DLL, or the DLL doesn't require specific export
176        * definitions.
177        */
178 #     define PNG_IMPEXP
179 #  endif
180 #endif
181 
182 /* No warnings for private or deprecated functions in the build: */
183 #ifndef PNG_DEPRECATED
184 #  define PNG_DEPRECATED
185 #endif
186 #ifndef PNG_PRIVATE
187 #  define PNG_PRIVATE
188 #endif
189 
190 /* Symbol preprocessing support.
191  *
192  * To enable listing global, but internal, symbols the following macros should
193  * always be used to declare an extern data or function object in this file.
194  */
195 #ifndef PNG_INTERNAL_DATA
196 #  define PNG_INTERNAL_DATA(type, name, array) extern type name array
197 #endif
198 
199 #ifndef PNG_INTERNAL_FUNCTION
200 #  define PNG_INTERNAL_FUNCTION(type, name, args, attributes)\
201       extern PNG_FUNCTION(type, name, args, PNG_EMPTY attributes)
202 #endif
203 
204 #ifndef PNG_INTERNAL_CALLBACK
205 #  define PNG_INTERNAL_CALLBACK(type, name, args, attributes)\
206       extern PNG_FUNCTION(type, (PNGCBAPI name), args, PNG_EMPTY attributes)
207 #endif
208 
209 /* If floating or fixed point APIs are disabled they may still be compiled
210  * internally.  To handle this make sure they are declared as the appropriate
211  * internal extern function (otherwise the symbol prefixing stuff won't work and
212  * the functions will be used without definitions.)
213  *
214  * NOTE: although all the API functions are declared here they are not all
215  * actually built!  Because the declarations are still made it is necessary to
216  * fake out types that they depend on.
217  */
218 #ifndef PNG_FP_EXPORT
219 #  ifndef PNG_FLOATING_POINT_SUPPORTED
220 #     define PNG_FP_EXPORT(ordinal, type, name, args)\
221          PNG_INTERNAL_FUNCTION(type, name, args, PNG_EMPTY);
222 #     ifndef PNG_VERSION_INFO_ONLY
223          typedef struct png_incomplete png_double;
224          typedef png_double*           png_doublep;
225          typedef const png_double*     png_const_doublep;
226          typedef png_double**          png_doublepp;
227 #     endif
228 #  endif
229 #endif
230 #ifndef PNG_FIXED_EXPORT
231 #  ifndef PNG_FIXED_POINT_SUPPORTED
232 #     define PNG_FIXED_EXPORT(ordinal, type, name, args)\
233          PNG_INTERNAL_FUNCTION(type, name, args, PNG_EMPTY);
234 #  endif
235 #endif
236 
237 /* Include png.h here to get the version info and other macros, pngstruct.h and
238  * pnginfo.h are included later under the protection of !PNG_VERSION_INFO_ONLY
239  */
240 #include "png.h"
241 
242 /* pngconf.h does not set PNG_DLL_EXPORT unless it is required, so: */
243 #ifndef PNG_DLL_EXPORT
244 #  define PNG_DLL_EXPORT
245 #endif
246 
247 /* This is a global switch to set the compilation for an installed system
248  * (a release build).  It can be set for testing debug builds to ensure that
249  * they will compile when the build type is switched to RC or STABLE, the
250  * default is just to use PNG_LIBPNG_BUILD_BASE_TYPE.  Set this in CPPFLAGS
251  * with either:
252  *
253  *   -DPNG_RELEASE_BUILD Turns on the release compile path
254  *   -DPNG_RELEASE_BUILD=0 Turns it off
255  * or in your pngusr.h with
256  *   #define PNG_RELEASE_BUILD=1 Turns on the release compile path
257  *   #define PNG_RELEASE_BUILD=0 Turns it off
258  */
259 #ifndef PNG_RELEASE_BUILD
260 #  define PNG_RELEASE_BUILD (PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC)
261 #endif
262 
263 /* General purpose macros avoid the need to put #if PNG_RELEASE_BUILD
264  * macro blocks around function declarations and definitions when the
265  * parameter number varies.  Using these results in slightly cleaner code.
266  */
267 #if PNG_RELEASE_BUILD
268 #  define only_rel(text) text
269 #  define only_deb(text)
270 #  define param_rel(param) param,
271 #  define param_deb(param)
272 #else
273 #  define only_rel(text)
274 #  define only_deb(text) text
275 #  define param_rel(param)
276 #  define param_deb(param) param,
277 #endif
278 
279 /* The affirm mechanism results in a minimal png_error() in released versions
280  * ('STABLE' versions) and a more descriptive PNG_ABORT in all other cases,
281  * when the "condition" is false (zero).  If "condition" is true (nonzero),
282  * then the affirm mechanism does nothing.
283  *
284  * The PNG_RELEASE_BUILD macro, defined above, controls the behavior of
285  * 'affirm': if set to 1 affirm will call png_error (or png_err) rather than
286  * abort.  The png_error text is the minimal (file location) text in this case,
287  * if it is produced. This flag indicates a STABLE (or RC) build.
288  *
289  * The macros rely on the naming convention throughout this code - png_ptr
290  * exists and is of type png_const_structrp or a compatible type - and the
291  * presence in each file of a uniquely defined macro PNG_SRC_FILE; a number
292  * indicating which file this is (this is to save space in released versions).
293  *
294  * 'affirm' is intended to look like the ANSI-C <assert.h> macro; note that
295  * this macro can coexist with the assert macro if <assert.h> is
296  * included.
297  *
298  * PNG_SRC_LINE is the position of the affirm macro.  There are currently 15
299  * main source files (4 bits) and the biggest (pngrtran.c) has more than 4095
300  * lines (12 bits).  However, to ensure the number will fit into 16-bits in the
301  * future and to allow hardware files to use affirm, the encoding is a bit-wise
302  * encoding based on the current number of lines.
303  *
304  * 'debug' is a version of 'affirm' that is completely removed from RELEASE
305  * builds.  This is used when either an unexpected condition is completely
306  * handled or when it can't be handled even by png_error, for example after a
307  * memory overwrite.
308  *
309  * UNTESTED is used to mark code that has not been tested; it causes an assert
310  * if the code is executed and (therefore) tested.  UNTESTED should not remain
311  * in release candidate code.
312  *
313  * PNG_AFFIRM_TEXT is set to 1 if affirm text should be produced, either
314  * the minimal text or, if PNG_RELEASE_BUILD is 0, the more verbose text
315  * including the 'condition' string.  This value depends on whether the
316  * build supports an appropriate way of outputting the message.
317  *
318  * Note that PNG_AFFIRM_TEXT is not configurable but is worked out here: this
319  * is just the affirm code; there's no reason to allow configuration of this
320  * option.
321  */
322 #if PNG_RELEASE_BUILD ?\
323       (defined PNG_ERROR_TEXT_SUPPORTED) :\
324       (defined PNG_WARNINGS_SUPPORTED) || (defined PNG_CONSOLE_IO_SUPPORTED)
325 #  define PNG_AFFIRM_TEXT 1
326 #else
327 #  define PNG_AFFIRM_TEXT 0
328 #endif /* PNG_AFFIRM_TEXT definition */
329 
330 #define PNG_SRC_LINE (PNG_SRC_FILE + __LINE__)
331 
332 /* png_affirmpp and png_impossiblepp are macros to make the correct call to the
333  * png_affirm function; these macros do not assume that the png_structp is
334  * called png_ptr.
335  */
336 #if PNG_RELEASE_BUILD
337 #  define png_affirmpp(pp, cond)\
338       do\
339          if (!(cond)) png_affirm(pp, PNG_SRC_LINE);\
340       while (0)
341 #  define png_affirmexp(pp, cond)\
342       ((cond) ? (void)0 : png_affirm(pp, PNG_SRC_LINE))
343 #  define png_handled(pp, m) ((void)0)
344 #  define png_impossiblepp(pp, reason) png_affirm(pp, PNG_SRC_LINE)
345 
346 #  define debug(cond) do {} while (0)
347 #  define debug_handled(cond) do {} while (0)
348 #  if PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC
349      /* Make sure there are no 'UNTESTED' macros in released code: */
350 #    define UNTESTED libpng untested code
351 #  endif
352 #  define NOT_REACHED do {} while (0)
353 #else
354 #  define png_affirmpp(pp, cond)\
355       do\
356          if (!(cond)) png_affirm(pp, #cond, PNG_SRC_LINE);\
357       while (0)
358 #  define png_affirmexp(pp, cond)\
359       ((cond) ? (void)0 : png_affirm(pp, #cond, PNG_SRC_LINE))
360 #  define png_handled(pp, m) (png_handled_affirm((pp), (m), PNG_SRC_LINE))
361 #  define png_impossiblepp(pp, reason) png_affirm(pp, reason, PNG_SRC_LINE)
362 
363 #  define debug(cond) png_affirmpp(png_ptr, cond)
364 #  define debug_handled(cond)\
365       do\
366          if (!(cond)) png_handled(png_ptr, #cond);\
367       while (0)
368 #  define UNTESTED png_affirm(png_ptr, "untested code", PNG_SRC_LINE);
369 #  define NOT_REACHED png_affirm(png_ptr, "NOT REACHED", PNG_SRC_LINE)
370 #endif
371 
372 #define affirm(cond) png_affirmpp(png_ptr, cond)
373 #define affirmexp(cond) png_affirmexp(png_ptr, cond)
374 #define handled(m) png_handled(png_ptr, (m))
375 #define impossible(cond) png_impossiblepp(png_ptr, cond)
376 #define implies(a, b) debug(!(a) || (b))
377 
378 /* The defines for PNG_SRC_FILE: */
379 #define PNG_SRC_FILE_(f,lines) PNG_SRC_FILE_ ## f + lines
380 
381 #define PNG_SRC_FILE_png      0
382 #define PNG_SRC_FILE_pngerror (PNG_SRC_FILE_png      +8192)
383 #define PNG_SRC_FILE_pngget   (PNG_SRC_FILE_pngerror +2048)
384 #define PNG_SRC_FILE_pngmem   (PNG_SRC_FILE_pngget   +2048)
385 #define PNG_SRC_FILE_pngpread (PNG_SRC_FILE_pngmem   +1024)
386 #define PNG_SRC_FILE_pngread  (PNG_SRC_FILE_pngpread +2048)
387 #define PNG_SRC_FILE_pngrio   (PNG_SRC_FILE_pngread  +8192)
388 #define PNG_SRC_FILE_pngrtran (PNG_SRC_FILE_pngrio   +1024)
389 #define PNG_SRC_FILE_pngrutil (PNG_SRC_FILE_pngrtran +8192)
390 #define PNG_SRC_FILE_pngset   (PNG_SRC_FILE_pngrutil +8192)
391 #define PNG_SRC_FILE_pngtrans (PNG_SRC_FILE_pngset   +2048)
392 #define PNG_SRC_FILE_pngwio   (PNG_SRC_FILE_pngtrans +4096)
393 #define PNG_SRC_FILE_pngwrite (PNG_SRC_FILE_pngwio   +1024)
394 #define PNG_SRC_FILE_pngwtran (PNG_SRC_FILE_pngwrite +4096)
395 #define PNG_SRC_FILE_pngwutil (PNG_SRC_FILE_pngwtran +1024)
396 
397 #define PNG_SRC_FILE_arm_arm_init (PNG_SRC_FILE_pngwutil +8192)
398 #define PNG_SRC_FILE_arm_filter_neon_intrinsics\
399              (PNG_SRC_FILE_arm_arm_init +1024)
400 
401 /* Add new files by changing the following line: */
402 #define PNG_SRC_FILE_LAST (PNG_SRC_FILE_arm_filter_neon_intrinsics +1024)
403 
404 /* The following #define must list the files in exactly the same order as
405  * the above.
406  */
407 #define PNG_FILES\
408    PNG_apply(png)\
409    PNG_apply(pngerror)\
410    PNG_apply(pngget)\
411    PNG_apply(pngmem)\
412    PNG_apply(pngpread)\
413    PNG_apply(pngread)\
414    PNG_apply(pngrio)\
415    PNG_apply(pngrtran)\
416    PNG_apply(pngrutil)\
417    PNG_apply(pngset)\
418    PNG_apply(pngtrans)\
419    PNG_apply(pngwio)\
420    PNG_apply(pngwrite)\
421    PNG_apply(pngwtran)\
422    PNG_apply(pngwutil)\
423    PNG_apply(arm_arm_init)\
424    PNG_apply(arm_filter_neon_intrinsics)\
425    PNG_end
426 
427 /* SECURITY and SAFETY:
428  *
429  * libpng is built with support for internal limits on image dimensions and
430  * memory usage.  These are documented in scripts/pnglibconf.dfa of the
431  * source and recorded in the machine generated header file pnglibconf.h.
432  */
433 
434 /* If you are running on a machine where you cannot allocate more
435  * than 64K of memory at once, uncomment this.  While libpng will not
436  * normally need that much memory in a chunk (unless you load up a very
437  * large file), zlib needs to know how big of a chunk it can use, and
438  * libpng thus makes sure to check any memory allocation to verify it
439  * will fit into memory.
440  *
441  * zlib provides 'MAXSEG_64K' which, if defined, indicates the
442  * same limit and pngconf.h (already included) sets the limit
443  * if certain operating systems are detected.
444  */
445 #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
446 #  define PNG_MAX_MALLOC_64K
447 #endif
448 
449 #ifndef PNG_UNUSED
450 /* Unused formal parameter warnings are silenced using the following macro
451  * which is expected to have no bad effects on performance (optimizing
452  * compilers will probably remove it entirely).  Note that if you replace
453  * it with something other than whitespace, you must include the terminating
454  * semicolon.
455  */
456 #  define PNG_UNUSED(param) (void)param;
457 #endif
458 
459 /* This is a convenience for parameters which are not used in release
460  * builds.
461  */
462 #define PNG_UNUSEDRC(param) only_rel(PNG_UNUSED(param))
463 
464 /* Just a little check that someone hasn't tried to define something
465  * contradictory.
466  */
467 #if (PNG_ZBUF_SIZE > 32768) && defined(PNG_MAX_MALLOC_64K)
468 #  undef PNG_ZBUF_SIZE
469 #  define PNG_ZBUF_SIZE 32768
470 #endif
471 
472 /* If warnings or errors are turned off the code is disabled or redirected here.
473  * From 1.5.4 functions have been added to allow very limited formatting of
474  * error and warning messages - this code will also be disabled here.
475  */
476 #ifdef PNG_WARNINGS_SUPPORTED
477 #  define PNG_WARNING_PARAMETERS(p) png_warning_parameters p;
478 #else
479 #  define png_warning_parameter(p,number,string) ((void)0)
480 #  define png_warning_parameter_unsigned(p,number,format,value) ((void)0)
481 #  define png_warning_parameter_signed(p,number,format,value) ((void)0)
482 #  define png_formatted_warning(pp,p,message) ((void)(pp))
483 #  define PNG_WARNING_PARAMETERS(p)
484 #endif
485 #ifndef PNG_ERROR_TEXT_SUPPORTED
486 #  define png_fixed_error(s1,s2) png_err(s1)
487 #endif
488 
489 /* C allows up-casts from (void*) to any pointer and (const void*) to any
490  * pointer to a const object.  C++ regards this as a type error and requires an
491  * explicit, static, cast and provides the static_cast<> rune to ensure that
492  * const is not cast away.
493  */
494 #ifdef __cplusplus
495 #  define png_voidcast(type, value) static_cast<type>(value)
496 #  define png_upcast(type, value) static_cast<type>(value)
497 #  define png_constcast(type, value) const_cast<type>(value)
498 #  define png_aligncast(type, value) \
499    static_cast<type>(static_cast<void*>(value))
500 #  define png_aligncastconst(type, value) \
501    static_cast<type>(static_cast<const void*>(value))
502 #else
503 #  define png_voidcast(type, value) (value)
504 #  define png_upcast(type, value) ((type)(value))
505 #  define png_constcast(type, value) ((type)(value))
506 #  define png_aligncast(type, value) ((void*)(value))
507 #  define png_aligncastconst(type, value) ((const void*)(value))
508 #endif /* __cplusplus */
509 
510 /* Some fixed point APIs are still required even if not exported because
511  * they get used by the corresponding floating point APIs.  This magic
512  * deals with this:
513  */
514 #ifdef PNG_FIXED_POINT_SUPPORTED
515 #  define PNGFAPI PNGAPI
516 #else
517 #  define PNGFAPI /* PRIVATE */
518 #endif
519 
520 /* These macros may need to be architecture dependent. */
521 #define PNG_ALIGN_NONE   0 /* do not use data alignment */
522 #define PNG_ALIGN_ALWAYS 1 /* assume unaligned accesses are OK */
523 #ifdef offsetof
524 #  define PNG_ALIGN_OFFSET 2 /* use offsetof to determine alignment */
525 #else
526 #  define PNG_ALIGN_OFFSET -1 /* prevent the use of this */
527 #endif
528 #define PNG_ALIGN_SIZE   3 /* use sizeof to determine alignment */
529 
530 #ifndef PNG_ALIGN_TYPE
531    /* Default to using aligned access optimizations and requiring alignment to a
532     * multiple of the data type size.  Override in a compiler specific fashion
533     * if necessary by inserting tests here:
534     */
535 #  define PNG_ALIGN_TYPE PNG_ALIGN_SIZE
536 #endif
537 
538 #if PNG_ALIGN_TYPE == PNG_ALIGN_SIZE
539    /* This is used because in some compiler implementations non-aligned
540     * structure members are supported, so the offsetof approach below fails.
541     * Set PNG_ALIGN_SIZE=0 for compiler combinations where unaligned access
542     * is good for performance.  Do not do this unless you have tested the result
543     * and understand it.
544     */
545 #  define png_alignof(type) (sizeof (type))
546 #else
547 #  if PNG_ALIGN_TYPE == PNG_ALIGN_OFFSET
548 #     define png_alignof(type) offsetof(struct{char c; type t;}, t)
549 #  else
550 #     if PNG_ALIGN_TYPE == PNG_ALIGN_ALWAYS
551 #        define png_alignof(type) (1)
552 #     endif
553       /* Else leave png_alignof undefined to prevent use thereof */
554 #  endif
555 #endif
556 
557 /* This implicitly assumes alignment is always to a power of 2. */
558 #ifdef png_alignof
559 #  define png_isaligned(ptr, type)\
560    ((((const char*)ptr-(const char*)0) & (png_alignof(type)-1)) == 0)
561 #else
562 #  define png_isaligned(ptr, type) 0
563 #endif
564 
565 /* Buffer alignment control.  These #defines control how the buffers used during
566  * read are aligned and how big they are.
567  */
568 #ifndef PNG_ROW_BUFFER_ALIGN_TYPE
569    /* The absolute minimum alignment for a row buffer is that required for
570     * png_uint_32 direct access.  The #define is of a legal C type that can be
571     * used as the type in the definition of the first member of a C union; give
572     * a typedef name if in doubt.
573     */
574 #  define PNG_ROW_BUFFER_ALIGN_TYPE png_uint_32
575 #endif /* !ROW_BUFFER_ALIGN_TYPE */
576 #ifndef PNG_ROW_BUFFER_BYTE_ALIGN
577    /* This is the minimum size in bytes of the buffer used while processing
578     * parts of row.  Except at the end of the row pixels will always be
579     * processed in blocks such that the block size is a multiple of this number
580     */
581 #  define PNG_ROW_BUFFER_BYTE_ALIGN\
582    ((unsigned int)/*SAFE*/(sizeof (PNG_ROW_BUFFER_ALIGN_TYPE)))
583 #endif /* !ROW_BUFFER_BYTE_ALIGN */
584 #ifdef PNG_READ_USER_TRANSFORM_SUPPORTED
585 #  define PNG_MAX_PIXEL_BYTES 16U /* 4x32-bit channels */
586 #else /* !READ_USER_TRANSFORM */
587 #  define PNG_MAX_PIXEL_BYTES  8U /* 4x16-bit channels */
588 #endif /* !READ_USER_TRANSFORM */
589 /* PNG_ROW_BUFFER_SIZE is a compile time constant for the size of the row
590  * buffer.  The minimum size of 2048 bytes is intended to allow the buffer to
591  * hold a complete 256 entry color map of 64-bit (8-byte) pixels.  This is a
592  * requirement at some points of the colormap handling code.
593  *
594  * The maximum size is intended to allow (unsigned int) indexing of the buffer,
595  * it only affects systems with a 16-bit unsigned value where it limits the
596  * maximum to 4096 bytes.
597  */
598 #define PNG_MIN_ROW_BUFFER_SIZE\
599    (PNG_MAX_PIXEL_BYTES * PNG_ROW_BUFFER_BYTE_ALIGN * 8U)
600 #define PNG_MAX_ROW_BUFFER_SIZE ((UINT_MAX / 16U) + 1U)
601 #ifndef PNG_ROW_BUFFER_SIZE
602 #  define PNG_ROW_BUFFER_SIZE\
603    (PNG_MIN_ROW_BUFFER_SIZE < 2048U ? 2048U : PNG_MIN_ROW_BUFFER_SIZE)
604 #endif /* ROW_BUFFER_SIZE */
605 
606 /* End of memory model/platform independent support */
607 /* End of 1.5.0beta36 move from pngconf.h */
608 
609 /* CONSTANTS and UTILITY MACROS
610  * These are used internally by libpng and not exposed in the API
611  */
612 
613 /* Various modes of operation.  Note that after an init, mode is set to
614  * zero automatically when the structure is created.  Three of these
615  * are defined in png.h because they need to be visible to applications
616  * that call png_set_unknown_chunk().
617  */
618 /* #define PNG_HAVE_IHDR            0x01 (defined as (int) in png.h) */
619 /* #define PNG_HAVE_PLTE            0x02 (defined as (int) in png.h) */
620 #define PNG_HAVE_IDAT               0x04U
621 /* #define PNG_AFTER_IDAT           0x08 (defined as (int) in png.h) */
622 #define PNG_HAVE_IEND               0x10U
623 #define PNG_HAVE_PNG_SIGNATURE      0x20U
624 
625 #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\
626    defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
627 /* See below for the definitions of the tables used in these macros */
628 #define PNG_sRGB_FROM_LINEAR(pp, linear) png_check_byte(pp,\
629    (png_sRGB_base[(linear)>>15] +\
630     ((((linear)&0x7fffU)*png_sRGB_delta[(linear)>>15])>>12)) >> 8)
631    /* Given a value 'linear' in the range 0..255*65535 calculate the 8-bit sRGB
632     * encoded value with maximum error 0.646365.  Note that the input is not a
633     * 16-bit value; it has been multiplied by 255! */
634 #endif /* PNG_SIMPLIFIED_READ/WRITE */
635 
636 /* Added to libpng-1.6.0: scale a 16-bit value in the range 0..65535 to 0..255
637  * by dividing by 257 *with rounding*.  This macro is exact for the given range.
638  * See the discourse in pngrtran.c png_do_scale_16_to_8.  The values in the
639  * macro were established by experiment (modifying the added value).  The macro
640  * has a second variant that takes a value already scaled by 255 and divides by
641  * 65535 - this has a maximum error of .502.  Over the range 0..65535*65535 it
642  * only gives off-by-one errors and only for 0.5% (1 in 200) of the values.
643  */
644 #define PNG_DIV65535(v24) (((v24) + 32895U) >> 16)
645 #define PNG_DIV257(v16) PNG_DIV65535((png_uint_32)(v16) * 255U)
646 
647 /* Added to libpng-1.2.6 JB
648  * Modified in libpng-1.7.0 to avoid the intermediate calculation overflow
649  * when:
650  *
651  *  pixel_bits == 4: any width over 0x3FFFFFFEU overflows
652  *  pixel_bits == 2: any width over 0x7FFFFFFCU overflows
653  *
654  * In both these cases any width results in a rowbytes that fits in 32 bits.
655  * The problem arose in previous versions because the calculation used was
656  * simply ((width x pixel-bit-depth)+7)/8.  At the cost of more calculations
657  * on pixel_depth this avoids the problem.
658  */
659 #define PNG_SHIFTOF(pixel_bits/*<8*/) \
660    ( (pixel_bits) == 1 ? 3 : \
661    ( (pixel_bits) == 2 ? 2 : \
662    ( (pixel_bits) == 4 ? 1 : \
663                          0/*force bytes*/ ) ) )
664 #define PNG_ADDOF(pixel_bits/*<8*/) ((1U<<PNG_SHIFTOF(pixel_bits))-1)
665 #define PNG_ROWBYTES(pixel_bits, width) \
666    ((pixel_bits) >= 8 ? \
667    ((png_alloc_size_t)(width) * ((pixel_bits) >> 3)) : \
668    (((png_alloc_size_t)(width) + PNG_ADDOF(pixel_bits)) >> \
669       PNG_SHIFTOF(pixel_bits)) )
670 
671 /* This macros, added in 1.7.0, makes it easy to deduce the number of channels
672  * and therefore the pixel depth from the color type.  The PNG specification
673  * numbers are used in preference to the png.h constants to make it more clear
674  * why the macro works.
675  */
676 #define PNG_COLOR_TYPE_CHANNELS(ct)\
677    (((ct) & PNG_COLOR_MASK_PALETTE) ?\
678       1U : 1U+((ct) & 2U/*COLOR*/)+(((ct)>>2)&1U/*ALPHA*/))
679 #define PNG_CHANNELS(ps) PNG_COLOR_TYPE_CHANNELS((ps).color_type)
680 #define PNG_PIXEL_DEPTH(ps) (PNG_CHANNELS(ps) * (ps).bit_depth)
681 
682 /* PNG_OUT_OF_RANGE returns true if value is outside the range
683  * ideal-delta..ideal+delta.  Each argument is evaluated twice.
684  * "ideal" and "delta" should be constants, normally simple
685  * integers, "value" a variable. Added to libpng-1.2.6 JB
686  */
687 #define PNG_OUT_OF_RANGE(value, ideal, delta) \
688    ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
689 
690 /* Handling of bit-field masks.  Because the expression:
691  *
692  *     bit_field & ~mask
693  *
694  * has implementation defined behavior in ANSI C-90 for many (int) values of
695  * 'mask' and because some of these are defined in png.h and passed in (int)
696  * parameters use of '~' has been expunged in libpng 1.7 and replaced by this
697  * macro, which is well defined in ANSI C-90 (there is a similar, 16-bit,
698  * version in pngstruct.h for the colorspace flags.)
699  */
700 #define PNG_BIC_MASK(flags) (0xFFFFFFFFU - (flags))
701 
702 /* Conversions between fixed and floating point, only defined if
703  * required (to make sure the code doesn't accidentally use float
704  * when it is supposedly disabled.)
705  */
706 #ifdef PNG_FLOATING_POINT_SUPPORTED
707 /* The floating point conversion can't overflow, though it can and
708  * does lose accuracy relative to the original fixed point value.
709  * In practice this doesn't matter because png_fixed_point only
710  * stores numbers with very low precision.  The png_ptr and s
711  * arguments are unused by default but are there in case error
712  * checking becomes a requirement.
713  */
714 #define png_float(png_ptr, fixed, s) (.00001 * (fixed))
715 
716 /* The fixed point conversion performs range checking and evaluates
717  * its argument multiple times, so must be used with care.  The
718  * range checking uses the PNG specification values for a signed
719  * 32 bit fixed point value except that the values are deliberately
720  * rounded-to-zero to an integral value - 21474 (21474.83 is roughly
721  * (2^31-1) * 100000). 's' is a string that describes the value being
722  * converted.
723  *
724  * NOTE: this macro will raise a png_error if the range check fails,
725  * therefore it is normally only appropriate to use this on values
726  * that come from API calls or other sources where an out of range
727  * error indicates a programming error, not a data error!
728  *
729  * NOTE: by default this is off - the macro is not used - because the
730  * function call saves a lot of code.
731  */
732 #ifdef PNG_FIXED_POINT_MACRO_SUPPORTED
733 #define png_fixed(png_ptr, fp, s) ((fp) <= 21474 && (fp) >= -21474 ?\
734     ((png_fixed_point)(100000 * (fp))) : (png_fixed_error(png_ptr, s),0))
735 #endif
736 /* else the corresponding function is defined below, inside the scope of the
737  * cplusplus test.
738  */
739 #endif
740 
741 /* Gamma values (new at libpng-1.5.4): */
742 #define PNG_GAMMA_MAC_OLD 151724  /* Assume '1.8' is really 2.2/1.45! */
743 #define PNG_GAMMA_MAC_INVERSE 65909
744 #define PNG_GAMMA_sRGB_INVERSE 45455
745 
746 /* Almost everything below is C specific; the #defines above can be used in
747  * non-C code (so long as it is C-preprocessed) the rest of this stuff cannot.
748  */
749 #ifndef PNG_VERSION_INFO_ONLY
750 
751 #include "pngstruct.h"
752 #include "pnginfo.h"
753 
754 /* Validate the include paths - the include path used to generate pnglibconf.h
755  * must match that used in the build, or we must be using pnglibconf.h.prebuilt:
756  */
757 #if PNG_ZLIB_VERNUM != 0 && PNG_ZLIB_VERNUM != ZLIB_VERNUM
758 #  error ZLIB_VERNUM != PNG_ZLIB_VERNUM \
759       "-I (include path) error: see the notes in pngpriv.h"
760    /* This means that when pnglibconf.h was built the copy of zlib.h that it
761     * used is not the same as the one being used here.  Because the build of
762     * libpng makes decisions to use inflateInit2 and inflateReset2 based on the
763     * zlib version number and because this affects handling of certain broken
764     * PNG files the -I directives must match.
765     *
766     * The most likely explanation is that you passed a -I in CFLAGS. This will
767     * not work; all the preprocessor directories and in particular all the -I
768     * directives must be in CPPFLAGS.
769     */
770 #endif
771 
772 /* This is used for 16 bit gamma tables -- only the top level pointers are
773  * const; this could be changed:
774  */
775 typedef const png_uint_16p * png_const_uint_16pp;
776 
777 /* Added to libpng-1.5.7: sRGB conversion tables */
778 #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\
779    defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
780 #ifdef PNG_SIMPLIFIED_READ_SUPPORTED
781 PNG_INTERNAL_DATA(const png_uint_16, png_sRGB_table, [256]);
782    /* Convert from an sRGB encoded value 0..255 to a 16-bit linear value,
783     * 0..65535.  This table gives the closest 16-bit answers (no errors).
784     */
785 #endif
786 
787 PNG_INTERNAL_DATA(const png_uint_16, png_sRGB_base, [512]);
788 PNG_INTERNAL_DATA(const png_byte, png_sRGB_delta, [512]);
789 #endif /* PNG_SIMPLIFIED_READ/WRITE */
790 
791 
792 /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
793 #ifdef __cplusplus
794 extern "C" {
795 #endif /* __cplusplus */
796 
797 /* Internal functions; these are not exported from a DLL however because they
798  * are used within several of the C source files they have to be C extern.
799  *
800  * All of these functions must be declared with PNG_INTERNAL_FUNCTION.
801  */
802 /* Affirm handling */
803 PNG_INTERNAL_FUNCTION(void, png_affirm,(png_const_structrp png_ptr,
804     param_deb(png_const_charp condition) unsigned int position), PNG_NORETURN);
805 
806 #if !PNG_RELEASE_BUILD
807 PNG_INTERNAL_FUNCTION(void, png_handled_affirm,(png_const_structrp png_ptr,
808       png_const_charp message, unsigned int position), PNG_EMPTY);
809    /* This is not marked PNG_NORETURN because in PNG_RELEASE_BUILD it will
810     * disappear and control will pass through it.
811     */
812 #endif /* !RELEASE_BUILD */
813 
814 /* Character/byte range checking. */
815 /* GCC complains about assignments of an (int) expression to a (char) even when
816  * it can readily determine that the value is in range.  This makes arithmetic
817  * on (char) or (png_byte) values tedious.  The warning is not issued by
818  * default, but libpng coding rules require no warnings leading to excessive,
819  * ridiculous and dangerous expressions of the form:
820  *
821  *     <char> = (char)(expression & 0xff)
822  *
823  * They are dangerous because they hide the warning, which might actually be
824  * valid, and therefore merely enable introduction of undetected overflows when
825  * code is modified.
826  *
827  * The following macros exist to reliably detect any overflow in non-release
828  * builds.  The theory here is that we really want to know about overflows, not
829  * merely hide a basically flawed compiler warning by throwing unnecessary casts
830  * into the code.  The warnings disappear in RC builds so that the released
831  * (STABLE) version just assigns the value (with, possibly, a warning if someone
832  * turns on the -Wconversion GCC warning.)
833  *
834  * Doing it this way ensures that the code meets two very important aims:
835  *
836  * 1) Overflows are detected in pre-release tests; previously versions of libpng
837  *    have been released that really did have overflows in the RGB calculations.
838  * 2) In release builds GCC specific operations, which may reduce the ability
839  *    of other compilers and even GCC to optimize the code, are avoided.
840  *
841  * There is one important extra consequence for pre-release code; it is
842  * performing a lot of checks in pixel arithmetic that the release code won't
843  * perform.  As a consequence a build time option, RANGE_CHECK, is provided
844  * to allow the checks to be turned off in pre-release when building for
845  * performance testing.  This is a standard "_SUPPORTED" option except that it
846  * cannot be set in the system configuration (pnglibconf.h, pnglibconf.dfa).
847  *
848  * A separate macro PNG_BYTE() is provided to safely convert an unsigned value
849  * to the PNG byte range 0..255.  This handles the fact that, technically,
850  * an ANSI-C (unsigned char), hence a (png_byte), may be able to store values
851  * outside this range.  Note that if you are building on a system where this is
852  * true libpng is almost certainly going to produce errors; it has never been
853  * tested on such a system.  For the moment pngconf.h ensures that this will
854  * not happen.
855  *
856  * PNG_UINT_16 does the same thing for a 16-bit value passed in an (int) or
857  * (png_uint_32) (where checking is not expected.)
858  */
859 #if !PNG_RELEASE_BUILD
860 #  ifndef PNG_NO_RANGE_CHECK /* Turn off even in pre-release */
861 #     define PNG_RANGE_CHECK_SUPPORTED
862 #  endif
863 #endif
864 
865 #ifdef PNG_RANGE_CHECK_SUPPORTED
866 PNG_INTERNAL_FUNCTION(unsigned int, png_bit_affirm,(png_const_structrp png_ptr,
867       unsigned int position, unsigned int u, unsigned int bits), PNG_EMPTY);
868 
869 PNG_INTERNAL_FUNCTION(char, png_char_affirm,(png_const_structrp png_ptr,
870       unsigned int position, int c), PNG_EMPTY);
871 
872 PNG_INTERNAL_FUNCTION(png_byte, png_byte_affirm,(png_const_structrp png_ptr,
873       unsigned int position, int b), PNG_EMPTY);
874 
875 #if INT_MAX >= 65535
876 PNG_INTERNAL_FUNCTION(png_uint_16, png_u16_affirm,(png_const_structrp png_ptr,
877       unsigned int position, int u), PNG_EMPTY);
878 #  define png_check_u16(pp, u) (png_u16_affirm((pp), PNG_SRC_LINE, (u)))
879 #else
880    /* (int) cannot hold a (png_uint_16) so the above function just won't
881     * compile correctly, for the moment just do this:
882     */
883 #  define png_check_u16(pp, u) (u)
884 #endif
885 
886 #  define png_check_bits(pp, u, bits)\
887    (((1U<<(bits))-1) & png_bit_affirm((pp), PNG_SRC_LINE, (u), (bits)))
888 #  define png_check_char(pp, c) (png_char_affirm((pp), PNG_SRC_LINE, (c)))
889 #  define png_check_byte(pp, b) (png_byte_affirm((pp), PNG_SRC_LINE, (b)))
890 #  define PNG_BYTE(b)           ((png_byte)((b) & 0xFFU))
891 #  define PNG_UINT_16(u)        ((png_uint_16)((u) & 0xFFFFU))
892 #elif !(defined PNG_REMOVE_CASTS) /* && !RANGE_CHECK */
893 #  define png_check_bits(pp, u, bits) (((1U<<(bits))-1U) & (u))
894 #  define png_check_char(pp, c) ((char)(c))
895 #  define png_check_byte(pp, b) ((png_byte)(b))
896 #  define png_check_u16(pp, u)  ((png_uint_16)(u))
897 #  define PNG_BYTE(b)           ((png_byte)((b) & 0xFFU))
898 #  define PNG_UINT_16(u)        ((png_uint_16)((u) & 0xFFFFU))
899 #else /* !RANGE_CHECK */
900    /* This is somewhat trust-me-it-works: if PNG_REMOVE_CASTS is defined then
901     * the casts, which might otherwise change the values, are completely
902     * removed.  Use this to test your compiler to see if it makes *any*
903     * difference (code size or speed.)  Currently NOT SUPPORTED.
904     *
905     * It also makes the PNG_BYTE and PNG_UINT_16 macros do nothing either
906     * NOTE: this seems safe at present but might lead to unexpected results
907     * if someone writes code to depend on the truncation.
908     */
909 #  define png_check_bits(pp, u, bits) (u)
910 #  define png_check_char(pp, c) (c)
911 #  define png_check_byte(pp, b) (b)
912 #  define png_check_u16(pp, u)  (u)
913 #  define PNG_BYTE(b)           (b)
914 #  define PNG_UINT_16(u)        (u)
915 #endif /* RANGE_CHECK */
916 
917 /* Safe calculation of a rowbytes value; does a png_error if the system limits
918  * are exceeded.
919  */
920 PNG_INTERNAL_FUNCTION(png_alloc_size_t,png_calc_rowbytes,
921    (png_const_structrp png_ptr, unsigned int pixel_depth,
922     png_uint_32 row_width),PNG_EMPTY);
923 
924 /* Common code to calculate the maximum number of pixels to transform or filter
925  * at one time; controlled by PNG_ROW_BUFFER_SIZE above:
926  */
927 PNG_INTERNAL_FUNCTION(unsigned int,png_max_pixel_block,
928       (png_const_structrp png_ptr),PNG_EMPTY);
929 
930 /* Copy the row in row_buffer; this is the non-interlaced copy used in both the
931  * read and write code.  'x_in_dest' specifies whether the 'x' applies to
932  * the destination (sp->dp[x], x_in_dest tru) or the source (sp[x]->dp,
933  * x_in_dest false).
934  */
935 PNG_INTERNAL_FUNCTION(void, png_copy_row,(png_const_structrp png_ptr,
936    png_bytep dp, png_const_bytep sp, png_uint_32 x/*in INPUT*/,
937    png_uint_32 width/*of INPUT*/, unsigned int pixel_depth,
938    int clear/*clear the final byte*/, int x_in_dest),PNG_EMPTY);
939 
940 /* Zlib support */
941 #define PNG_UNEXPECTED_ZLIB_RETURN (-7)
942 PNG_INTERNAL_FUNCTION(void, png_zstream_error,(z_stream *zstream, int ret),
943    PNG_EMPTY);
944    /* Used by the zlib handling functions to ensure that z_stream::msg is always
945     * set before they return.
946     */
947 
948 #if defined(PNG_FLOATING_POINT_SUPPORTED) && \
949    !defined(PNG_FIXED_POINT_MACRO_SUPPORTED) && \
950    (defined(PNG_gAMA_SUPPORTED) || defined(PNG_cHRM_SUPPORTED) || \
951    defined(PNG_sCAL_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) || \
952    defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)) || \
953    (defined(PNG_sCAL_SUPPORTED) && \
954    defined(PNG_FLOATING_ARITHMETIC_SUPPORTED))
955 PNG_INTERNAL_FUNCTION(png_fixed_point,png_fixed,(png_const_structrp png_ptr,
956    double fp, png_const_charp text),PNG_EMPTY);
957 #endif
958 
959 /* Internal base allocator - no messages, NULL on failure to allocate.  This
960  * does, however, call the application provided allocator and that could call
961  * png_error (although that would be a bug in the application implementation.)
962  */
963 PNG_INTERNAL_FUNCTION(png_voidp,png_malloc_base,(png_const_structrp png_ptr,
964    png_alloc_size_t size),PNG_ALLOCATED);
965 
966 #if defined(PNG_TEXT_SUPPORTED) || defined(PNG_sPLT_SUPPORTED) ||\
967    defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED)
968 /* Internal array allocator, outputs no error or warning messages on failure,
969  * just returns NULL.
970  */
971 PNG_INTERNAL_FUNCTION(png_voidp,png_malloc_array,(png_const_structrp png_ptr,
972    int nelements, size_t element_size),PNG_ALLOCATED);
973 
974 /* The same but an existing array is extended by add_elements.  This function
975  * also memsets the new elements to 0 and copies the old elements.  The old
976  * array is not freed or altered.
977  */
978 PNG_INTERNAL_FUNCTION(png_voidp,png_realloc_array,(png_structrp png_ptr,
979    png_const_voidp array, int old_elements, int add_elements,
980    size_t element_size),PNG_ALLOCATED);
981 #endif /* text, sPLT or unknown chunks */
982 
983 /* Magic to create a struct when there is no struct to call the user supplied
984  * memory allocators.  Because error handling has not been set up the memory
985  * handlers can't safely call png_error, but this is an obscure and undocumented
986  * restriction so libpng has to assume that the 'free' handler, at least, might
987  * call png_error.
988  */
989 PNG_INTERNAL_FUNCTION(png_structp,png_create_png_struct,
990    (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn,
991     png_error_ptr warn_fn, png_voidp mem_ptr, png_malloc_ptr malloc_fn,
992     png_free_ptr free_fn),PNG_ALLOCATED);
993 
994 /* Free memory from internal libpng struct */
995 PNG_INTERNAL_FUNCTION(void,png_destroy_png_struct,(png_structrp png_ptr),
996    PNG_EMPTY);
997 
998 /* Free an allocated jmp_buf (always succeeds) */
999 PNG_INTERNAL_FUNCTION(void,png_free_jmpbuf,(png_structrp png_ptr),PNG_EMPTY);
1000 
1001 /* Function to allocate memory for zlib.  PNGAPI is disallowed. */
1002 PNG_INTERNAL_FUNCTION(voidpf,png_zalloc,(voidpf png_ptr, uInt items, uInt size),
1003    PNG_ALLOCATED);
1004 
1005 /* Function to free memory for zlib.  PNGAPI is disallowed. */
1006 PNG_INTERNAL_FUNCTION(void,png_zfree,(voidpf png_ptr, voidpf ptr),PNG_EMPTY);
1007 
1008 /* The next three functions are used by png_init_io to set the default
1009  * implementations for reading or writing to a stdio (png_FILE_p) stream.
1010  * They can't be static because in 1.7 png_init_io needs to reference them.
1011  */
1012 #ifdef PNG_STDIO_SUPPORTED
1013 #  ifdef PNG_READ_SUPPORTED
1014 PNG_INTERNAL_FUNCTION(void PNGCBAPI,png_default_read_data,(png_structp png_ptr,
1015     png_bytep data, png_size_t length),PNG_EMPTY);
1016 #  endif /* READ */
1017 
1018 #  ifdef PNG_WRITE_SUPPORTED
1019 PNG_INTERNAL_FUNCTION(void PNGCBAPI,png_default_write_data,(png_structp png_ptr,
1020     png_bytep data, png_size_t length),PNG_EMPTY);
1021 
1022 #     ifdef PNG_WRITE_FLUSH_SUPPORTED
1023 PNG_INTERNAL_FUNCTION(void PNGCBAPI,png_default_flush,(png_structp png_ptr),
1024    PNG_EMPTY);
1025 #     endif /* WRITE_FLUSH */
1026 #  endif /* WRITE */
1027 #endif /* STDIO */
1028 
1029 /* Reset the CRC variable.  The CRC is initialized with the chunk tag (4 bytes).
1030  * NOTE: at present png_struct::chunk_name MUST be set before this as well so
1031  * that png_struct::current_crc is initialized correctly!
1032  */
1033 PNG_INTERNAL_FUNCTION(void,png_reset_crc,(png_structrp png_ptr,
1034          png_const_bytep chunk_tag), PNG_EMPTY);
1035 
1036 /* Write the "data" buffer to whatever output you are using */
1037 PNG_INTERNAL_FUNCTION(void,png_write_data,(png_structrp png_ptr,
1038     png_const_voidp data, png_size_t length),PNG_EMPTY);
1039 
1040 /* Read and check the PNG file signature */
1041 PNG_INTERNAL_FUNCTION(void,png_read_sig,(png_structrp png_ptr,
1042    png_inforp info_ptr),PNG_EMPTY);
1043 
1044 /* Read data from whatever input you are using into the "data" buffer */
1045 PNG_INTERNAL_FUNCTION(void,png_read_data,(png_structrp png_ptr, png_voidp data,
1046     png_size_t length),PNG_EMPTY);
1047 
1048 /* Read bytes into buf, and update png_ptr->crc */
1049 PNG_INTERNAL_FUNCTION(void,png_crc_read,(png_structrp png_ptr, png_voidp buf,
1050     png_uint_32 length),PNG_EMPTY);
1051 
1052 /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
1053 PNG_INTERNAL_FUNCTION(int,png_crc_finish,(png_structrp png_ptr,
1054    png_uint_32 skip),PNG_EMPTY);
1055 
1056 /* Calculate the CRC over a section of data.  Note that we are only
1057  * passing a maximum of 64K on systems that have this as a memory limit,
1058  * since this is the maximum buffer size we can specify.
1059  */
1060 PNG_INTERNAL_FUNCTION(void,png_calculate_crc,(png_structrp png_ptr,
1061    png_const_voidp ptr, png_size_t length),PNG_EMPTY);
1062 
1063 /* Write various chunks */
1064 
1065 /* Write the IHDR chunk, and update the png_struct with the necessary
1066  * information.
1067  */
1068 PNG_INTERNAL_FUNCTION(void,png_write_IHDR,(png_structrp png_ptr,
1069    png_uint_32 width, png_uint_32 height, int bit_depth, int color_type,
1070    int compression_method, int filter_method, int interlace_method),PNG_EMPTY);
1071 
1072 PNG_INTERNAL_FUNCTION(void,png_write_PLTE,(png_structrp png_ptr,
1073    png_const_colorp palette, unsigned int num_pal),PNG_EMPTY);
1074 
1075 PNG_INTERNAL_FUNCTION(void,png_write_IEND,(png_structrp png_ptr),PNG_EMPTY);
1076 
1077 #ifdef PNG_WRITE_gAMA_SUPPORTED
1078 PNG_INTERNAL_FUNCTION(void,png_write_gAMA_fixed,(png_structrp png_ptr,
1079     png_fixed_point file_gamma),PNG_EMPTY);
1080 #endif
1081 
1082 #ifdef PNG_WRITE_sBIT_SUPPORTED
1083 PNG_INTERNAL_FUNCTION(void,png_write_sBIT,(png_structrp png_ptr,
1084     png_const_color_8p sbit, int color_type),PNG_EMPTY);
1085 #endif
1086 
1087 #ifdef PNG_WRITE_cHRM_SUPPORTED
1088 PNG_INTERNAL_FUNCTION(void,png_write_cHRM_fixed,(png_structrp png_ptr,
1089     const png_xy *xy), PNG_EMPTY);
1090    /* The xy value must have been previously validated */
1091 #endif
1092 
1093 #ifdef PNG_WRITE_sRGB_SUPPORTED
1094 PNG_INTERNAL_FUNCTION(void,png_write_sRGB,(png_structrp png_ptr,
1095     int intent),PNG_EMPTY);
1096 #endif
1097 
1098 #ifdef PNG_WRITE_iCCP_SUPPORTED
1099 PNG_INTERNAL_FUNCTION(void,png_write_iCCP,(png_structrp png_ptr,
1100    png_const_charp name, png_const_voidp profile), PNG_EMPTY);
1101    /* The profile must have been previously validated for correctness, the
1102     * length comes from the first four bytes.  Only the base, deflate,
1103     * compression is supported.
1104     */
1105 #endif
1106 
1107 #ifdef PNG_WRITE_sPLT_SUPPORTED
1108 PNG_INTERNAL_FUNCTION(void,png_write_sPLT,(png_structrp png_ptr,
1109     png_const_sPLT_tp palette),PNG_EMPTY);
1110 #endif
1111 
1112 #ifdef PNG_WRITE_tRNS_SUPPORTED
1113 PNG_INTERNAL_FUNCTION(void,png_write_tRNS,(png_structrp png_ptr,
1114     png_const_bytep trans, png_const_color_16p values, int number,
1115     int color_type),PNG_EMPTY);
1116 #endif
1117 
1118 #ifdef PNG_WRITE_bKGD_SUPPORTED
1119 PNG_INTERNAL_FUNCTION(void,png_write_bKGD,(png_structrp png_ptr,
1120     png_const_color_16p values, int color_type),PNG_EMPTY);
1121 #endif
1122 
1123 #ifdef PNG_WRITE_hIST_SUPPORTED
1124 PNG_INTERNAL_FUNCTION(void,png_write_hIST,(png_structrp png_ptr,
1125     png_const_uint_16p hist, int num_hist),PNG_EMPTY);
1126 #endif
1127 
1128 /* Chunks that have keywords */
1129 #ifdef PNG_WRITE_tEXt_SUPPORTED
1130 PNG_INTERNAL_FUNCTION(void,png_write_tEXt,(png_structrp png_ptr,
1131     png_const_charp key, png_const_charp text, png_size_t text_len),PNG_EMPTY);
1132 #endif
1133 
1134 #ifdef PNG_WRITE_zTXt_SUPPORTED
1135 PNG_INTERNAL_FUNCTION(void,png_write_zTXt,(png_structrp png_ptr,
1136     png_const_charp key, png_const_charp text, int compression),PNG_EMPTY);
1137 #endif
1138 
1139 #ifdef PNG_WRITE_iTXt_SUPPORTED
1140 PNG_INTERNAL_FUNCTION(void,png_write_iTXt,(png_structrp png_ptr,
1141     int compression, png_const_charp key, png_const_charp lang,
1142     png_const_charp lang_key, png_const_charp text),PNG_EMPTY);
1143 #endif
1144 
1145 #ifdef PNG_TEXT_SUPPORTED  /* Added at version 1.0.14 and 1.2.4 */
1146 PNG_INTERNAL_FUNCTION(int,png_set_text_2,(png_structrp png_ptr,
1147     png_inforp info_ptr, png_const_textp text_ptr, int num_text),PNG_EMPTY);
1148 #endif
1149 
1150 #ifdef PNG_WRITE_oFFs_SUPPORTED
1151 PNG_INTERNAL_FUNCTION(void,png_write_oFFs,(png_structrp png_ptr,
1152     png_int_32 x_offset, png_int_32 y_offset, int unit_type),PNG_EMPTY);
1153 #endif
1154 
1155 #ifdef PNG_WRITE_pCAL_SUPPORTED
1156 PNG_INTERNAL_FUNCTION(void,png_write_pCAL,(png_structrp png_ptr,
1157     png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
1158     png_const_charp units, png_charpp params),PNG_EMPTY);
1159 #endif
1160 
1161 #ifdef PNG_WRITE_pHYs_SUPPORTED
1162 PNG_INTERNAL_FUNCTION(void,png_write_pHYs,(png_structrp png_ptr,
1163     png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
1164     int unit_type),PNG_EMPTY);
1165 #endif
1166 
1167 #ifdef PNG_WRITE_tIME_SUPPORTED
1168 PNG_INTERNAL_FUNCTION(void,png_write_tIME,(png_structrp png_ptr,
1169     png_const_timep mod_time),PNG_EMPTY);
1170 #endif
1171 
1172 #ifdef PNG_WRITE_sCAL_SUPPORTED
1173 PNG_INTERNAL_FUNCTION(void,png_write_sCAL_s,(png_structrp png_ptr,
1174     int unit, png_const_charp width, png_const_charp height),PNG_EMPTY);
1175 #endif
1176 
1177 #ifdef PNG_WRITE_SUPPORTED
1178 PNG_INTERNAL_FUNCTION(void,png_write_start_IDAT,(png_structrp png_ptr),
1179       PNG_EMPTY);
1180    /* Do any required initialization before IDAT or row processing starts. */
1181 
1182 /* Choose the best filter to use and filter the row data then write it out.  If
1183  * WRITE_FILTERING is not supported this just writes the data out with a zero
1184  * (NONE) filter byte.
1185  *
1186  * This may be called multiple times per row, but calls must be in 'x' order;
1187  * first a call with x 0 to mark the start of the row and, at the end, one with
1188  * PNG_ROW_END set (this can be done in the same function call if the whole row
1189  * is passed.)  The following flags are used internally to control pass
1190  * filtering and deflate:
1191  */
1192 enum
1193 {
1194    png_pass_last      =0x1U, /* This is the last pass in the image */
1195    png_pass_last_row  =0x2U, /* This is the last row in a pass */
1196    png_pass_first_row =0x4U, /* This is the first row in a pass */
1197    png_row_end        =0x8U, /* This is the last block in the row */
1198    png_no_row_info    =0x0U  /* Placeholder */
1199 
1200    /* A useful macro; return true if this is the last block of the last row in
1201     * the image.
1202     */
1203 #  define PNG_IDAT_END(f) (((f) & ~png_pass_first_row) == \
1204       (png_row_end+png_pass_last_row+png_pass_last))
1205 };
1206 PNG_INTERNAL_FUNCTION(void,png_write_png_data,(png_structrp png_ptr,
1207     png_bytep prev_pixels, png_const_bytep unfiltered_row, png_uint_32 x,
1208     unsigned int width/*pixels*/, unsigned int row_info_flags),
1209    PNG_EMPTY);
1210 
1211 PNG_INTERNAL_FUNCTION(void,png_write_png_rows,(png_structrp png_ptr,
1212     png_const_bytep *rows, png_uint_32 num_rows), PNG_EMPTY);
1213    /* As above but rows[num_rows] of correctly (PNG) formated but unfiltered
1214     * data are passed in.  For an interlaced image the rows will be interlaced
1215     * rows and therefore may be narrower than the image width.
1216     *
1217     * This function advances png_structp::pass and png_structp::row_number as
1218     * required.
1219     */
1220 
1221 /* Release memory used by the deflate mechanism */
1222 PNG_INTERNAL_FUNCTION(void, png_deflate_destroy, (png_structp png_ptr),
1223    PNG_EMPTY);
1224 #endif /* WRITE */
1225 
1226 #ifdef PNG_TRANSFORM_MECH_SUPPORTED
1227 PNG_INTERNAL_FUNCTION(void,png_transform_free,(png_const_structrp png_ptr,
1228          png_transformp *list),PNG_EMPTY);
1229    /* Free the entire transform list, from the given point on. the argument is
1230     * set to NULL.
1231     */
1232 
1233 PNG_INTERNAL_FUNCTION(void,png_init_transform_control,(
1234    png_transform_controlp out, png_structp png_ptr),PNG_EMPTY);
1235    /* Initialize a transform control for running the transform list forward (the
1236     * read case, and write initialization, but the write case is called within
1237     * pngtrans.c by the above function.)
1238     */
1239 
1240 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
1241 PNG_INTERNAL_FUNCTION(unsigned int,png_run_this_transform_list_forwards,
1242    (png_transform_controlp tc, png_transformp *start, png_transformp end),
1243    PNG_EMPTY);
1244    /* Used by the transform cache code to run a sub-list, from *start to the
1245     * transform end.
1246     */
1247 #endif /* READ_TRANSFORMS */
1248 
1249 #ifdef PNG_READ_SUPPORTED
1250 PNG_INTERNAL_FUNCTION(unsigned int,png_run_transform_list_forwards,
1251    (png_structp png_ptr, png_transform_controlp tc),PNG_EMPTY);
1252    /* Run the transform list in the forwards direction (from PNG format to
1253     * memory format).  The transform control must be initialized completely by
1254     * the caller.  This function takes account of transforms which delete
1255     * themselves during the run; it must be used.
1256     */
1257 #endif /* READ */
1258 
1259 #ifdef PNG_WRITE_SUPPORTED
1260 PNG_INTERNAL_FUNCTION(void,png_run_transform_list_backwards,
1261    (png_structp png_ptr, png_transform_controlp tc),PNG_EMPTY);
1262    /* Run the transform list in the backwards direction (from memory format to
1263     * PNG format).  The transform control must be initialized completely by
1264     * the caller.  This function takes account of transforms which delete
1265     * themselves during the run; it must be used.
1266     */
1267 #endif /* WRITE */
1268 
1269 PNG_INTERNAL_FUNCTION(png_transformp,png_add_transform,(png_structrp png_ptr,
1270    size_t size, png_transform_fn fn, unsigned int order),PNG_EMPTY);
1271    /* Add a transform, using the information in 'order' to control the position
1272     * of the transform in the list, returning a pointer to the transform.  The
1273     * top 8 bits of 'order' control the position in the list.  If a transform
1274     * does not already exist in the list with the given value a new transform
1275     * will be created and 'fn' and 'order' set.  If there is a transform with
1276     * that value 'fn' must match and 'order' will be updated by combining the
1277     * new value in with a bitwise or (|).  It is up to the function (fn) or the
1278     * caller of png_add_transform to determine whether the combination is valid.
1279     *
1280     * 'size' is used when creating a new transform, it may be larger than
1281     * (sizeof png_transform) if required to accomodate extra data.
1282     *
1283     * Prior to 1.7.0 transforms were executed in an order hard-wired into the
1284     * code that executed the transform functions.  This was summarized in the
1285     * read case by the following comment from pngrtran.c
1286     * (png_init_read_transformations), note that this has been marked up to
1287     * indicate which PNG formats the transforms in the list apply to:
1288     *
1289     * *: applies to most formats
1290     * A: only formats with alpha
1291     * L: only low-bit-depth (less than 8 bits per component/pixel)
1292     * H: only high-bit-depth (16-bits per component)
1293     *
1294     > From the code of png_do_read_transformations the order is:
1295     *
1296     * GGRR   For example column: . no action
1297     *  AGG                       r acts on read
1298     *   BB                       w acts on write
1299     *    A                       B acts on both read and write
1300     >
1301     > r.r.  1) PNG_EXPAND (including PNG_EXPAND_tRNS)
1302     > .r.r  2) PNG_STRIP_ALPHA (if no compose)
1303     > ..rr  3) PNG_RGB_TO_GRAY
1304     > rr..  4) PNG_GRAY_TO_RGB iff !PNG_FLAG_BACKGROUND_IS_GRAY
1305     > rrrr  5) PNG_COMPOSE
1306     > rrrr  6) PNG_GAMMA
1307     > .r.r  7) PNG_STRIP_ALPHA (if compose)
1308     > .r.r  8) PNG_ENCODE_ALPHA
1309     > rrrr  9) PNG_SCALE_16_TO_8
1310     > rrrr 10) PNG_16_TO_8
1311     > ..rr 11) PNG_QUANTIZE (converts to palette)
1312     > rrrr 12) PNG_EXPAND_16
1313     > rr.. 13) PNG_GRAY_TO_RGB iff PNG_FLAG_BACKGROUND_IS_GRAY
1314     > BB.. 14) PNG_INVERT_MONO
1315     > .B.B 15) PNG_INVERT_ALPHA
1316     > BBBB 16) PNG_SHIFT
1317     *
1318     * Note that transforms from this point on are used in 1.7.0 on palette
1319     * indices as well; a png_set_pack request (for example) packs the palette
1320     * index values if the output will be palettized and the grayscale values
1321     * if it will not be (if the output is low-bit-grayscale, not palette.)
1322     *
1323     > B... 17) PNG_PACK
1324     > ..BB 18) PNG_BGR
1325     > B... 19) PNG_PACKSWAP
1326     > rwrw 20) PNG_FILLER (includes PNG_ADD_ALPHA)
1327     > .B.B 21) PNG_SWAP_ALPHA
1328     > BBBB 22) PNG_SWAP_BYTES
1329     > BBBB 23) PNG_USER_TRANSFORM [must be last]
1330     *
1331     * Finally, outside the set of transforms prior to 1.7.0, the libpng
1332     * interlace handling required the pixels to be replicated to match the pixel
1333     * spacing in the image row; the first part the pre-1.7.0 interlace support,
1334     * this is still the case when reading, but for writing the interlace is now
1335     * a transform:
1336     *
1337     > BBBB 24) png_do_{read,write}_interlace (interlaced images only).
1338     *
1339     * First transforms are grouped according to basic function using the top 3
1340     * bits of the order code:
1341     */
1342 #  define PNG_TR_START         0x0000U /* initial ops on the PNG data */
1343 #  define PNG_TR_ARITHMETIC    0x2000U /* arithmetic linear operations */
1344 #  define PNG_TR_CHANNEL       0x4000U /* PNG conformant format changes */
1345 #  define PNG_TR_QUANTIZE      0x6000U /* quantize and following operations */
1346 #  define PNG_TR_ENCODING      0x8000U /* Row encoding transforms */
1347 #  define PNG_TR_INTERLACE     0xA000U /* write interlace transform */
1348    /*
1349     * In libpng 1.7.0 the check on palette index values is moved to the start
1350     * (of read, end of write, which is where it was before) immediately after
1351     * the MNG filter handling
1352     */
1353 #  define PNG_TR_MNG_INTRAPIXEL (PNG_TR_START + 0x0100U)
1354    /* Perform intra-pixel differencing (write) or un-differencing on read. */
1355 #  define PNG_TR_CHECK_PALETTE  (PNG_TR_START + 0x0200U)
1356    /* Done before at the start on read, at the end on write to give a
1357     * consistent postion:
1358     *
1359     *    PNG_RWTR_CHECK_PALETTE PI W11: happens in pngwrite.c last
1360     */
1361 #  define PNG_TR_START_CACHE    (PNG_TR_START + 0x0300U)
1362    /* Not used on a transform; this is just a marker for the point at which
1363     * palette or low-bit-depth caching can start on read.  (The previous
1364     * operations cannot be cached).
1365     */
1366 #  define PNG_TR_INIT_ALPHA     (PNG_TR_START + 0x0400U)
1367    /* This just handles alpha/tRNS initialization issues to resolve the
1368     * inter-dependencies with tRNS expansion and background composition; it
1369     * doesn't do anything itself, just sets flags and pushes transforms.
1370     */
1371    /*
1372     * Prior to 1.7 the arithmetic operations interleaved with the RGB-to-gray
1373     * and alpha strip byte level ops.  This was done to reduce the amount of
1374     * data processed, i.e. it was an optimization not a requirement.  These
1375     * operations were preceded by the 'expand' operations, which is the
1376     * opposite; it was done to simplify the code and actually slows things down
1377     * in the low bit depth gray case.  The full list of operations after expand,
1378     * in the 1.6 order, is:
1379     *
1380     *    PNG_TR_STRIP_ALPHA     png_do_strip_channel (sometimes)
1381     *    PNG_TR_RGB_TO_GRAY     png_do_rgb_to_gray
1382     *    PNG_TR_GRAY_TO_RGB     png_do_gray_to_rgb (sometimes)
1383     *    PNG_TR_COMPOSE         png_do_compose
1384     *    PNG_TR_GAMMA           png_do_gamma (if no RGB_TO_GRAY)
1385     *    PNG_TR_STRIP_ALPHA     png_do_strip_channel (other times)
1386     *    PNG_TR_ENCODE_ALPHA    png_do_encode_alpha
1387     *
1388     * In 1.7 the operations are moved round somewhat, including moving alpha and
1389     * 16-to-8 bit reduction later.  This leaves the following operations:
1390     *
1391     *    PNG_TR_RGB_TO_GRAY     png_do_rgb_to_gray
1392     *    PNG_TR_COMPOSE         png_do_compose
1393     *    PNG_TR_GAMMA           png_do_gamma (if no RGB_TO_GRAY)
1394     *    PNG_TR_ENCODE_ALPHA    png_do_encode_alpha
1395     *
1396     * Prior to 1.7 some combinations of transforms would do gamma correction
1397     * twice, the actual implementation in 1.7 is to use the following order and
1398     * rely on the cache code to optimize gray 1,2,4,8 and (of course) palette.
1399     */
1400 #  define PNG_TR_COMPOSE          (PNG_TR_ARITHMETIC + 0x0100U)
1401       /* Handle background composition.  This may need to push a gray-to-rgb
1402        * transform if the background is RGB for gray input.  This precedes RGB
1403        * to gray convertion so that it can handle tRNS appropriately when the
1404        * background is in the PNG encoding however, typically, the processing
1405        * happens at PNG_TR_COMPOSE_ALPHA below.
1406        *
1407        * NOTE: this must be the first arithmetic transform because the code in
1408        * png_init_background relies on png_transform_control::gamma being the
1409        * original PNG gamma.
1410        */
1411 #  define PNG_TR_RGB_TO_GRAY      (PNG_TR_ARITHMETIC + 0x0200U) /* to gray */
1412       /* Convert any RGB input (8/16 bit depth, RGB, RGBA) to linear gray
1413        * 16-bit.  This happens first because it cannot be cached; the input data
1414        * has 24 or 48 bits of uncorrelated data so the transform has to happen
1415        * pixel-by-pixel.  Internally the transform may maintain an 8 or 16-bit
1416        * gamma correction table (to 16-bit linear) to speed things up.
1417        *
1418        * NOTE: this transform must follow PNG_TR_COMPOSE with no intervening
1419        * transforms; see the code in png_init_background (pngrtran.c) which
1420        * relies on this during PNG_TC_INIT_FORMAT.
1421        */
1422 #  define PNG_TR_COMPOSE_ALPHA    (PNG_TR_ARITHMETIC + 0x0300U)
1423        /* Compose alpha composition and tRNS handling when the background is a
1424         * screen color.  Pushed by PNG_TR_COMPOSE as required.
1425         */
1426 #  define PNG_TR_GAMMA_ENCODE     (PNG_TR_ARITHMETIC + 0x1F00U) /* last */
1427       /* Gamma encode the input.  This encodes the gray or RGB channels to the
1428        * required bit depth and either scales the alpha channel or encodes it as
1429        * well, depending on the requested alpha encoding.
1430        */
1431    /*
1432     * The 'expand' operations come after the arithmetic ones in libpng 1.7, this
1433     * forces the arithmetic stuff to do the expand, but since arithmetic is (in
1434     * 1.7) normally done in 16-bit linear this avoids spurious expands.
1435     */
1436 #  define PNG_TR_EXPAND        (PNG_TR_CHANNEL    + 0x0100U)
1437    /* Includes:
1438     *
1439     *    PNG_TR_EXPAND_PALETTE  palette images only, includes tRNS
1440     *    PNG_TR_EXPAND_LBP_GRAY grayscale low-bit depth only
1441     *    PNG_TR_EXPAND_tRNS     non-palette images only
1442     */
1443 #  define PNG_TR_SCALE_16_TO_8 (PNG_TR_CHANNEL    + 0x0200U)
1444    /* Comes after the expand and before the chop version; note that it works on
1445     * the pixel values directly, so it is a linear transform on a non-linear
1446     * value.
1447     */
1448    /*
1449     * To handle transforms that affect the palette entries, not the palette
1450     * indices in the row data, libpng 1.7 reorders some of the post-quantize
1451     * transformations to put all the "PC" transforms ahead of all the "PI"
1452     * transforms.  The "PC" transforms that came after png_do_quantize in libpng
1453     * 1.6 cannot be ordered to be before so they are included in the
1454     * PNG_TR_QUANTIZE section.  The PI transforms are all in PNG_TR_ENCODING,
1455     * PNG_GRAY_TO_RGB is moved before PNG_TR_QUANTIZE to avoid the unpredictable
1456     * behavior of png_set_quantize that otherwise arises.
1457     *
1458     * The transforms in the PNG_TR_QUANTIZE section are:
1459     *
1460     *    PNG_TR_EXPAND_16       !P !W
1461     *    PNG_RWTR_INVERT_MONO   !P W10: invert the gray channel
1462     *    PNG_RWTR_INVERT_ALPHA  PC W8: invert the alpha channel
1463     *    PNG_RWTR_SHIFT         PC W6: read: down, write: scale up
1464     *    PNG_RWTR_BGR           !P W9
1465     *    PNG_RWTR_FILLER        !P W2: add on R, remove on W
1466     *    PNG_RWTR_SWAP_ALPHA    !P W7
1467     *    PNG_RWTR_SWAP_16       !P W5
1468     *
1469     * The ones in PNG_TR_ENCODING are:
1470     *
1471     *    PNG_RWTR_PACK          PI W4: R: unpack bytes, W: pack
1472     *    PNG_RWTR_PIXEL_SWAP    PI W3: Swap pixels in a byte
1473     *    PNG_RWTR_USER          PI W1
1474     */
1475 
1476 #  define PNG_TR_CHANNEL_PREQ  (PNG_TR_CHANNEL    + 0x1F00U)
1477    /* The channel swap transforms that must happen before PNG_TR_QUANTIZE:
1478     *
1479     *    PNG_TR_STRIP_ALPHA
1480     *    PNG_TR_CHOP_16_TO_8
1481     *    PNG_TR_GRAY_TO_RGB
1482     */
1483 #  define PNG_TR_CHANNEL_POSTQ (PNG_TR_QUANTIZE   + 0x0100U)
1484    /* The post-quantize channel swap transforms:
1485     *
1486     *    PNG_TR_EXPAND_16       !P !W
1487     *    PNG_RWTR_BGR           !P W9
1488     *    PNG_RWTR_FILLER        !P W2: (filler) add on R, remove on W
1489     *    PNG_RWTR_SWAP_ALPHA    !P W7
1490     *    PNG_RWTR_SWAP_16       !P W5
1491     *
1492     * The 'CHANNEL' operation sets the transform_control channel_add flag for
1493     * use below.
1494     */
1495 #  define PNG_TR_INVERT        (PNG_TR_QUANTIZE   + 0x0200U)
1496    /* Invert MONO and ALPHA.  If the channel_add flag is set in the transform
1497     * control INVERT_ALPHA will not be done; the png_add_alpha/filler APIs
1498     * happened after png_set_invert_alpha in earlier versions so the filler
1499     * value had to include the invert.
1500     *
1501     *    PNG_RWTR_INVERT_MONO   !P W10: invert the gray channel
1502     *    PNG_RWTR_INVERT_ALPHA  PC W8: invert the alpha channel
1503     */
1504 #  define PNG_TR_SHIFT         (PNG_TR_QUANTIZE   + 0x0300U)
1505    /* The channel shift, except that if the channel_add flag has been set the
1506     * alpha channel is not shifted.
1507     *
1508     *    PNG_RWTR_SHIFT         PC W6: read: down, write: scale up
1509     */
1510 #  define PNG_TR_PACK          (PNG_TR_ENCODING   + 0x0200U)
1511    /*    PNG_RWTR_PACK          PI W4: R: unpack bytes, W: pack */
1512 #  define PNG_TR_PIXEL_SWAP    (PNG_TR_ENCODING   + 0x0300U)
1513    /*    PNG_RWTR_PIXEL_SWAP    PI W3: Swap pixels in a byte */
1514 #  define PNG_TR_USER          (PNG_TR_ENCODING   + 0x1F00U)
1515    /* The user transform; must be last before the interlace handling because it
1516     * does unpredictable things to the format.
1517     *
1518     *    PNG_RWTR_USER          PI W1
1519     */
1520 
1521 PNG_INTERNAL_FUNCTION(png_transformp,png_push_transform,(png_structrp png_ptr,
1522    size_t size, png_transform_fn fn, png_transformp *transform,
1523    png_transform_controlp tc),PNG_EMPTY);
1524    /* As png_add_transform except that the new transform is inserted ahead of
1525     * the given transform (*transform).  The new transform is returned, but it
1526     * will also invariably be in *transform.  If 'tc' is not NULL the transform
1527     * callback will also be called; it needs to be called if this function is
1528     * called while transforms are being run.
1529     *
1530     * 'fn' must not be NULL.
1531     *
1532     * The transform is inserted with the same 'order' as the passed in
1533     * *transform, that transform and following transforms are moved up ('order'
1534     * is incremented) as required to make space.  Consequently, unlike with
1535     * png_add_transform, the transform will always be new.  To detect loops
1536     * (*transform)->fn must not be the same as the passed in 'fn'.
1537     */
1538 
1539 PNG_INTERNAL_FUNCTION(png_voidp,png_transform_cast_check,
1540    (png_const_structp png_ptr, unsigned int src_line, png_transformp tr,
1541     size_t size),PNG_EMPTY);
1542    /* Given a pointer to a transform, 'tr' validate that the underlying derived
1543     * class has size 'size' using the tr->size field and return the same
1544     * pointer.  If there is a size mismatch the function does an affirm using
1545     * the given line number.
1546     */
1547 #define png_transform_cast(type, pointer) png_voidcast(type*,\
1548    png_transform_cast_check(png_ptr, PNG_SRC_LINE, (pointer), sizeof (type)))
1549    /* This takes a pointer to a transform and safely returns a pointer to a
1550     * derived transform class (type); type must not have the pointer.  It
1551     * validates the 'size' field.  Derived classes start with a png_transform
1552     * as the first member called 'tr'.
1553     */
1554 #endif /* TRANSFORM_MECH_SUPPORTED */
1555 
1556 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
1557 /* Remove a transform from a list, moving the next transform down into
1558  * *transform.
1559  */
1560 PNG_INTERNAL_FUNCTION(void,png_remove_transform,(png_const_structp png_ptr,
1561    png_transformp *transform),PNG_EMPTY);
1562 
1563 /* Initializer for read transforms that handles caching, palette update and
1564  * palette expansion.
1565  */
1566 PNG_INTERNAL_FUNCTION(unsigned int,png_read_init_transform_mech,
1567    (png_structp png_ptr, png_transform_control *tc),PNG_EMPTY);
1568 
1569 /* Optional call to update the users info structure */
1570 PNG_INTERNAL_FUNCTION(void,png_read_transform_info,(png_structrp png_ptr,
1571    png_inforp info_ptr),PNG_EMPTY);
1572 #endif
1573 
1574 /* APIs which do a tranform on both read and write but where the implementation
1575  * is separate for each; the read and write init functions are in pngrtran.c or
1576  * pngwtran.c, the API is in pngtrans.c
1577  */
1578 #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED)
1579 PNG_INTERNAL_FUNCTION(void,png_init_read_pack,(png_transformp *transform,
1580    png_transform_controlp tc),PNG_EMPTY);
1581 #endif /* READ_PACK || READ_EXPAND */
1582 #ifdef PNG_WRITE_PACK_SUPPORTED
1583 PNG_INTERNAL_FUNCTION(void,png_init_write_pack,(png_transformp *transform,
1584    png_transform_controlp tc),PNG_EMPTY);
1585 #endif /* WRITE_PACK */
1586 
1587 /* Shared transform functions, defined in pngtran.c */
1588 #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
1589     defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
1590 PNG_INTERNAL_FUNCTION(void,png_do_strip_channel,(
1591     png_transform_controlp row_info, png_bytep row, int at_start),PNG_EMPTY);
1592 #endif /* FILLER */
1593 
1594 #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
1595 PNG_INTERNAL_FUNCTION(void,png_do_invert,(png_transform_controlp row_info,
1596     png_bytep row),PNG_EMPTY);
1597 #endif /* INVERT */
1598 
1599 #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) ||\
1600     defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
1601 PNG_INTERNAL_FUNCTION(void,png_do_invert_alpha,(png_transform_controlp row_info,
1602     png_bytep row),PNG_EMPTY);
1603 #endif /* INVERT_ALPHA */
1604 
1605 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
1606 PNG_INTERNAL_FUNCTION(void,png_add_rgb_to_gray_byte_ops,(png_structrp png_ptr,
1607    png_transform_controlp tc, unsigned int index, unsigned int order),
1608    PNG_EMPTY);
1609    /* This is an init-time utility to add appropriate byte ops to select a given
1610     * channel from R/G/B.
1611     */
1612 #endif /* READ_RGB_TO_GRAY */
1613 
1614 #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED) &&\
1615     defined(PNG_READ_BACKGROUND_SUPPORTED)
1616 PNG_INTERNAL_FUNCTION(void,png_push_gray_to_rgb_byte_ops,(png_transformp *tr,
1617    png_transform_controlp tc), PNG_EMPTY);
1618    /* This is an init-time utility to push appropriate byte ops to expand a
1619     * grayscale PNG data set to RGB.  It calls the function callback so 'tc'
1620     * must be non-NULL.
1621     */
1622 #endif /* GRAY_TO_RGB && READ_BACKGROUND */
1623 
1624 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
1625 PNG_INTERNAL_FUNCTION(void,png_add_strip_alpha_byte_ops,(png_structrp png_ptr),
1626    PNG_EMPTY);
1627    /* Called from pngrtran.c to add the relevant byte op. */
1628 #endif /* READ_STRIP_ALPHA */
1629 
1630 /* The following decodes the appropriate chunks, and does error correction,
1631  * then calls the appropriate callback for the chunk if it is valid.
1632  */
1633 
1634 #ifdef PNG_READ_SUPPORTED
1635 PNG_INTERNAL_FUNCTION(png_bytep,png_read_buffer,(png_structrp png_ptr,
1636    png_alloc_size_t new_size, int warn),PNG_EMPTY);
1637    /* Manage the dynamically allocated read buffer */
1638 
1639 /* Shared READ IDAT handling: */
1640 PNG_INTERNAL_FUNCTION(void,png_read_start_IDAT,(png_structrp png_ptr),
1641    PNG_EMPTY);
1642    /* Initialize the row buffers, etc. */
1643 
1644 typedef enum
1645 {
1646    png_row_incomplete,
1647       /* more IDAT data needed for row */
1648    png_row_process,
1649       /* png_struct::row_buffer contains a complete row */
1650    png_row_repeat,
1651       /* row not in this pass, but the existing row may be used */
1652    png_row_skip
1653       /* row not in pass and no appropriate data; skip this row */
1654 }  png_row_op;
1655 PNG_INTERNAL_FUNCTION(png_row_op,png_read_process_IDAT,(png_structrp png_ptr,
1656       png_bytep transformed_row, png_bytep display_row, int save_row),
1657       PNG_EMPTY);
1658    /* Process a block of IDAT data; the routine returns early if it has
1659     * obtained a row.  It is valid to call this routine with no input data;
1660     * it will return png_row_incomplete if it needs input.
1661     *
1662     * transformed_row: The transformed pixels of the input are written here.
1663     *                  For interlaced images only the pixels in the pass will
1664     *                  be written, the other pixels will not be touched.
1665     *
1666     * display_row:     The transformed pixels but replicated to that the entire
1667     *                  buffer will have been initialized.  For passes after the
1668     *                  first the pixels written are determined by the 'block'
1669     *                  algorithm; only those *following* pixels which are
1670     *                  written by *later* passes are written (with a copy of the
1671     *                  pixel from the pass.)
1672     *
1673     * save_row:        A boolean which indicates that the row (unexpanded)
1674     *                  should be saved in png_struct::transformed_row.  This can
1675     *                  be used in a later call to png_combine_row.
1676     *
1677     * During reading the row is built up until png_row_process is returned.  At
1678     * this point png_struct::row_buffer contains the original PNG row from the
1679     * file and, if save_row was set, png_struct::transformed_row contains the
1680     * row after the selected row transforms have been performed.  For interlaced
1681     * images both are the width of the interlace pass.
1682     *
1683     * When png_row_repeat is returned the same is true, except that the buffers
1684     * still contain the contents of the preceding row (the one where this
1685     * funciton returned png_row_pricess).
1686     *
1687     * The row buffers should not be accessed if png_row_skip is returned; this
1688     * row is not modified in the current pass.
1689     */
1690 
1691 PNG_INTERNAL_FUNCTION(void,png_read_free_row_buffers,(png_structrp png_ptr),
1692     PNG_EMPTY);
1693    /* Free allocated row buffers; done as soon as possible to avoid carrying
1694     * around all the memory for longer than necessary.
1695     */
1696 
1697 PNG_INTERNAL_FUNCTION(int,png_read_finish_IDAT,(png_structrp png_ptr),
1698     PNG_EMPTY);
1699    /* Complete reading of the IDAT chunks.  This returns 0 if more data is to
1700     * be read, 1 if the zlib stream has terminated.  Call this routine with
1701     * zstream.avail_in greater than zero unless there is no more input data.
1702     * When zstream_avail_in is 0 on entry and the stream does not terminate
1703     * an "IDAT truncated" error will be output.
1704     *
1705     *    ENTRY: png_ptr->zstream.{next,avail}_in points to more IDAT data, if
1706     *           available, otherwise avail_in should be 0.
1707     *    RET 0: the LZ stream is still active, more IDAT date is required, if
1708     *           available, the routine *must* be called again.
1709     *    RET 1: the LZ stream has been closed and an error may have been output;
1710     *           png_ptr->zstream_error says whether it has.  If not and there
1711     *           is more IDAT data available the caller should output an
1712     *           appropriate (too much IDAT) error message.
1713     */
1714 
1715 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
1716 PNG_INTERNAL_FUNCTION(void,png_cache_known_unknown,(png_structrp png_ptr,
1717    png_const_bytep add, int keep),PNG_EMPTY);
1718    /* Update the png_struct::known_unknown bit cache which stores whether each
1719     * known chunk should be treated as unknown.
1720     */
1721 #endif
1722 
1723 typedef enum
1724 {
1725    png_chunk_skip = 0,    /* Skip this chunk */
1726    png_chunk_unknown,     /* Pass the chunk to png_handle_unknown */
1727    png_chunk_process_all, /* Process the chunk all at once */
1728    png_chunk_process_part /* Process the chunk in parts (for IDAT) */
1729 }  png_chunk_op;
1730 
1731 PNG_INTERNAL_FUNCTION(png_chunk_op,png_find_chunk_op,(png_structrp png_ptr),
1732       PNG_EMPTY);
1733    /* Given a chunk in png_struct::{chunk_name,chunk_length} validate the name
1734     * and work out how it should be handled.  This function checks the chunk
1735     * location using png_struct::mode and will set the mode appropriately for
1736     * the known critical chunks but otherwise makes no changes to the stream
1737     * read state.
1738     */
1739 
1740 PNG_INTERNAL_FUNCTION(void,png_check_chunk_name,(png_const_structrp png_ptr,
1741     const png_uint_32 chunk_name),PNG_EMPTY);
1742 
1743 PNG_INTERNAL_FUNCTION(void,png_check_chunk_length,(png_const_structrp png_ptr,
1744     const png_uint_32 chunk_length),PNG_EMPTY);
1745 
1746 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
1747 PNG_INTERNAL_FUNCTION(void,png_handle_unknown,(png_structrp png_ptr,
1748    png_inforp info_ptr, png_bytep chunk_data),PNG_EMPTY);
1749    /* Handle an unknown chunk that needs to be processed.  It is only valid
1750     * to call this after png_find_chunk_op returns png_chunk_unknown.  The
1751     * data argument points to the png_struct::chunk_length bytes of the chunk
1752     * data.
1753     */
1754 #endif /* READ_UNKNOWN_CHUNKS */
1755 
1756 PNG_INTERNAL_FUNCTION(void,png_handle_chunk,(png_structrp png_ptr,
1757       png_inforp info_ptr),PNG_EMPTY);
1758    /* The chunk to handle is in png_struct::chunk_name,chunk_length.
1759     *
1760     * NOTE: at present it is only valid to call this after png_find_chunk_op
1761     * has returned png_chunk_process_all and all the data is available for
1762     * png_handle_chunk (via the libpng read callback.)
1763     */
1764 #endif /* READ */
1765 
1766 PNG_INTERNAL_FUNCTION(void,png_init_row_info,(png_structrp png_ptr),PNG_EMPTY);
1767    /* Set the png_struct::row_ members from the PNG file information, running
1768     * transforms if required.
1769     */
1770 
1771 /* Added at libpng version 1.6.0 */
1772 #ifdef PNG_GAMMA_SUPPORTED
1773 PNG_INTERNAL_FUNCTION(void,png_colorspace_set_gamma,(png_const_structrp png_ptr,
1774     png_colorspacerp colorspace, png_fixed_point gAMA), PNG_EMPTY);
1775    /* Set the colorspace gamma with a value provided by the application or by
1776     * the gAMA chunk on read.  The value will override anything set by an ICC
1777     * profile.
1778     */
1779 
1780 PNG_INTERNAL_FUNCTION(void,png_colorspace_sync_info,(png_const_structrp png_ptr,
1781     png_inforp info_ptr), PNG_EMPTY);
1782    /* Synchronize the info 'valid' flags with the colorspace */
1783 
1784 PNG_INTERNAL_FUNCTION(void,png_colorspace_sync,(png_const_structrp png_ptr,
1785     png_inforp info_ptr), PNG_EMPTY);
1786    /* Copy the png_struct colorspace to the info_struct and call the above to
1787     * synchronize the flags.  Checks for NULL info_ptr and does nothing.
1788     */
1789 #endif
1790 
1791 /* Added at libpng version 1.4.0 */
1792 #ifdef PNG_COLORSPACE_SUPPORTED
1793 /* These internal functions are for maintaining the colorspace structure within
1794  * a png_info or png_struct (or, indeed, both).
1795  */
1796 PNG_INTERNAL_FUNCTION(int,png_colorspace_set_chromaticities,
1797    (png_const_structrp png_ptr, png_colorspacerp colorspace, const png_xy *xy,
1798     int preferred), PNG_EMPTY);
1799 
1800 PNG_INTERNAL_FUNCTION(int,png_colorspace_set_endpoints,
1801    (png_const_structrp png_ptr, png_colorspacerp colorspace, const png_XYZ *XYZ,
1802     int preferred), PNG_EMPTY);
1803 
1804 #ifdef PNG_sRGB_SUPPORTED
1805 PNG_INTERNAL_FUNCTION(int,png_colorspace_set_sRGB,(png_const_structrp png_ptr,
1806    png_colorspacerp colorspace, int intent), PNG_EMPTY);
1807    /* This does set the colorspace gAMA and cHRM values too, but doesn't set the
1808     * flags to write them, if it returns false there was a problem and an error
1809     * message has already been output (but the colorspace may still need to be
1810     * synced to record the invalid flag).
1811     */
1812 #endif /* sRGB */
1813 
1814 #ifdef PNG_iCCP_SUPPORTED
1815 PNG_INTERNAL_FUNCTION(int,png_colorspace_set_ICC,(png_const_structrp png_ptr,
1816    png_colorspacerp colorspace, png_const_charp name,
1817    png_uint_32 profile_length, png_const_bytep profile, int is_color),
1818    PNG_EMPTY);
1819    /* The 'name' is used for information only */
1820 
1821 /* Routines for checking parts of an ICC profile. */
1822 PNG_INTERNAL_FUNCTION(int,png_icc_check_length,(png_const_structrp png_ptr,
1823    png_colorspacerp colorspace, png_const_charp name,
1824    png_uint_32 profile_length), PNG_EMPTY);
1825 PNG_INTERNAL_FUNCTION(int,png_icc_check_header,(png_const_structrp png_ptr,
1826    png_colorspacerp colorspace, png_const_charp name,
1827    png_uint_32 profile_length,
1828    png_const_bytep profile /* first 132 bytes only */, int is_color),
1829    PNG_EMPTY);
1830 PNG_INTERNAL_FUNCTION(int,png_icc_check_tag_table,(png_const_structrp png_ptr,
1831    png_colorspacerp colorspace, png_const_charp name,
1832    png_uint_32 profile_length,
1833    png_const_bytep profile /* header plus whole tag table */), PNG_EMPTY);
1834 #ifdef PNG_sRGB_SUPPORTED
1835 PNG_INTERNAL_FUNCTION(void,png_icc_set_sRGB,(
1836    png_const_structrp png_ptr, png_colorspacerp colorspace,
1837    png_const_bytep profile, uLong adler), PNG_EMPTY);
1838    /* 'adler' is the Adler32 checksum of the uncompressed profile data. It may
1839     * be zero to indicate that it is not available.  It is used, if provided,
1840     * as a fast check on the profile when checking to see if it is sRGB.
1841     */
1842 #endif /* sRGB */
1843 #endif /* iCCP */
1844 #endif /* COLORSPACE */
1845 
1846 /* Added at libpng version 1.4.0 */
1847 PNG_INTERNAL_FUNCTION(void,png_check_IHDR,(png_const_structrp png_ptr,
1848     png_uint_32 width, png_uint_32 height, int bit_depth,
1849     int color_type, int interlace_type, int compression_type,
1850     int filter_type),PNG_EMPTY);
1851 
1852 #if defined(PNG_FLOATING_POINT_SUPPORTED) && defined(PNG_ERROR_TEXT_SUPPORTED)
1853 PNG_INTERNAL_FUNCTION(void,png_fixed_error,(png_const_structrp png_ptr,
1854    png_const_charp name),PNG_NORETURN);
1855 #endif
1856 
1857 /* Puts 'string' into 'buffer' at buffer[pos], taking care never to overwrite
1858  * the end.  Always leaves the buffer nul terminated.  Never errors out (and
1859  * there is no error code.)
1860  */
1861 PNG_INTERNAL_FUNCTION(size_t,png_safecat,(png_charp buffer, size_t bufsize,
1862    size_t pos, png_const_charp string),PNG_EMPTY);
1863 
1864 /* Various internal functions to handle formatted warning messages, currently
1865  * only implemented for warnings.
1866  */
1867 #if defined(PNG_WARNINGS_SUPPORTED) || defined(PNG_TIME_RFC1123_SUPPORTED)
1868 /* Utility to dump an unsigned value into a buffer, given a start pointer and
1869  * and end pointer (which should point just *beyond* the end of the buffer!)
1870  * Returns the pointer to the start of the formatted string.  This utility only
1871  * does unsigned values.
1872  */
1873 PNG_INTERNAL_FUNCTION(png_charp,png_format_number,(png_const_charp start,
1874    png_charp end, int format, png_alloc_size_t number),PNG_EMPTY);
1875 
1876 /* Convenience macro that takes an array: */
1877 #define PNG_FORMAT_NUMBER(buffer,format,number) \
1878    png_format_number(buffer, buffer + (sizeof buffer), format, number)
1879 
1880 /* Suggested size for a number buffer (enough for 64 bits and a sign!) */
1881 #define PNG_NUMBER_BUFFER_SIZE 24
1882 
1883 /* These are the integer formats currently supported, the name is formed from
1884  * the standard printf(3) format string.
1885  */
1886 #define PNG_NUMBER_FORMAT_u     1 /* chose unsigned API! */
1887 #define PNG_NUMBER_FORMAT_02u   2
1888 #define PNG_NUMBER_FORMAT_d     1 /* chose signed API! */
1889 #define PNG_NUMBER_FORMAT_02d   2
1890 #define PNG_NUMBER_FORMAT_x     3
1891 #define PNG_NUMBER_FORMAT_02x   4
1892 #define PNG_NUMBER_FORMAT_fixed 5 /* choose the signed API */
1893 #endif
1894 
1895 #ifdef PNG_WARNINGS_SUPPORTED
1896 /* New defines and members adding in libpng-1.5.4 */
1897 #  define PNG_WARNING_PARAMETER_SIZE 32
1898 #  define PNG_WARNING_PARAMETER_COUNT 8 /* Maximum 9; see pngerror.c */
1899 
1900 /* An l-value of this type has to be passed to the APIs below to cache the
1901  * values of the parameters to a formatted warning message.
1902  */
1903 typedef char png_warning_parameters[PNG_WARNING_PARAMETER_COUNT][
1904    PNG_WARNING_PARAMETER_SIZE];
1905 
1906 PNG_INTERNAL_FUNCTION(void,png_warning_parameter,(png_warning_parameters p,
1907    int number, png_const_charp string),PNG_EMPTY);
1908    /* Parameters are limited in size to PNG_WARNING_PARAMETER_SIZE characters,
1909     * including the trailing '\0'.
1910     */
1911 PNG_INTERNAL_FUNCTION(void,png_warning_parameter_unsigned,
1912    (png_warning_parameters p, int number, int format, png_alloc_size_t value),
1913    PNG_EMPTY);
1914    /* Use png_alloc_size_t because it is an unsigned type as big as any we
1915     * need to output.  Use the following for a signed value.
1916     */
1917 PNG_INTERNAL_FUNCTION(void,png_warning_parameter_signed,
1918    (png_warning_parameters p, int number, int format, png_int_32 value),
1919    PNG_EMPTY);
1920 
1921 PNG_INTERNAL_FUNCTION(void,png_formatted_warning,(png_const_structrp png_ptr,
1922    png_warning_parameters p, png_const_charp message),PNG_EMPTY);
1923    /* 'message' follows the X/Open approach of using @1, @2 to insert
1924     * parameters previously supplied using the above functions.  Errors in
1925     * specifying the parameters will simply result in garbage substitutions.
1926     */
1927 #endif
1928 
1929 #ifdef PNG_BENIGN_ERRORS_SUPPORTED
1930 /* Application errors (new in 1.6); use these functions (declared below) for
1931  * errors in the parameters or order of API function calls on read.  The
1932  * 'warning' should be used for an error that can be handled completely; the
1933  * 'error' for one which can be handled safely but which may lose application
1934  * information or settings.
1935  *
1936  * By default these both result in a png_error call prior to release, while in a
1937  * released version the 'warning' is just a warning.  However if the application
1938  * explicitly disables benign errors (explicitly permitting the code to lose
1939  * information) they both turn into warnings.
1940  *
1941  * If benign errors aren't supported they end up as the corresponding base call
1942  * (png_warning or png_error.)
1943  */
1944 PNG_INTERNAL_FUNCTION(void,png_app_warning,(png_const_structrp png_ptr,
1945    png_const_charp message),PNG_EMPTY);
1946    /* The application provided invalid parameters to an API function or called
1947     * an API function at the wrong time, libpng can completely recover.
1948     */
1949 
1950 PNG_INTERNAL_FUNCTION(void,png_app_error,(png_const_structrp png_ptr,
1951    png_const_charp message),PNG_EMPTY);
1952    /* As above but libpng will ignore the call, or attempt some other partial
1953     * recovery from the error.
1954     */
1955 #else
1956 #  define png_app_warning(pp,s) png_warning(pp,s)
1957 #  define png_app_error(pp,s) png_error(pp,s)
1958 #endif
1959 
1960 PNG_INTERNAL_FUNCTION(void,png_chunk_report,(png_const_structrp png_ptr,
1961    png_const_charp message, int error),PNG_EMPTY);
1962    /* Report a recoverable issue in chunk data.  On read this is used to report
1963     * a problem found while reading a particular chunk and the
1964     * png_chunk_benign_error or png_chunk_warning function is used as
1965     * appropriate.  On write this is used to report an error that comes from
1966     * data set via an application call to a png_set_ API and png_app_error or
1967     * png_app_warning is used as appropriate.
1968     *
1969     * With PNG_CHUNK_FATAL an error can be marked as unrecoverable, and the
1970     * function will not return.
1971     *
1972     * The 'error' parameter must have one of the following values:
1973     */
1974 #define PNG_CHUNK_WARNING     0 /* never an error */
1975 #define PNG_CHUNK_WRITE_ERROR 1 /* an error only on write */
1976 #define PNG_CHUNK_ERROR       2 /* always an error */
1977 #define PNG_CHUNK_FATAL       3 /* an unrecoverable error */
1978 
1979 #ifndef PNG_ERROR_TEXT_SUPPORTED
1980 #  define png_chunk_report(pp,e,v) png_chunk_report(pp,NULL,v)
1981 #endif
1982 
1983 /* ASCII to FP interfaces, currently only implemented if sCAL
1984  * support is required.
1985  */
1986 #if defined(PNG_sCAL_SUPPORTED)
1987 /* MAX_DIGITS is actually the maximum number of characters in an sCAL
1988  * width or height, derived from the precision (number of significant
1989  * digits - a build time settable option) and assumptions about the
1990  * maximum ridiculous exponent.
1991  */
1992 #define PNG_sCAL_MAX_DIGITS (PNG_sCAL_PRECISION+1/*.*/+1/*E*/+10/*exponent*/)
1993 
1994 #ifdef PNG_FLOATING_POINT_SUPPORTED
1995 PNG_INTERNAL_FUNCTION(void,png_ascii_from_fp,(png_const_structrp png_ptr,
1996    png_charp ascii, png_size_t size, double fp, unsigned int precision),
1997    PNG_EMPTY);
1998 #endif /* FLOATING_POINT */
1999 
2000 #ifdef PNG_FIXED_POINT_SUPPORTED
2001 PNG_INTERNAL_FUNCTION(void,png_ascii_from_fixed,(png_const_structrp png_ptr,
2002    png_charp ascii, png_size_t size, png_fixed_point fp),PNG_EMPTY);
2003 #endif /* FIXED_POINT */
2004 #endif /* sCAL */
2005 
2006 #if defined(PNG_sCAL_SUPPORTED) || defined(PNG_pCAL_SUPPORTED)
2007 /* An internal API to validate the format of a floating point number.
2008  * The result is the index of the next character.  If the number is
2009  * not valid it will be the index of a character in the supposed number.
2010  *
2011  * The format of a number is defined in the PNG extensions specification
2012  * and this API is strictly conformant to that spec, not anyone elses!
2013  *
2014  * The format as a regular expression is:
2015  *
2016  * [+-]?[0-9]+.?([Ee][+-]?[0-9]+)?
2017  *
2018  * or:
2019  *
2020  * [+-]?.[0-9]+(.[0-9]+)?([Ee][+-]?[0-9]+)?
2021  *
2022  * The complexity is that either integer or fraction must be present and the
2023  * fraction is permitted to have no digits only if the integer is present.
2024  *
2025  * NOTE: The dangling E problem.
2026  *   There is a PNG valid floating point number in the following:
2027  *
2028  *       PNG floating point numbers are not greedy.
2029  *
2030  *   Working this out requires *TWO* character lookahead (because of the
2031  *   sign), the parser does not do this - it will fail at the 'r' - this
2032  *   doesn't matter for PNG sCAL chunk values, but it requires more care
2033  *   if the value were ever to be embedded in something more complex.  Use
2034  *   ANSI-C strtod if you need the lookahead.
2035  */
2036 /* State table for the parser. */
2037 #define PNG_FP_INTEGER    0  /* before or in integer */
2038 #define PNG_FP_FRACTION   1  /* before or in fraction */
2039 #define PNG_FP_EXPONENT   2  /* before or in exponent */
2040 #define PNG_FP_STATE      3  /* mask for the above */
2041 #define PNG_FP_SAW_SIGN   4  /* Saw +/- in current state */
2042 #define PNG_FP_SAW_DIGIT  8  /* Saw a digit in current state */
2043 #define PNG_FP_SAW_DOT   16  /* Saw a dot in current state */
2044 #define PNG_FP_SAW_E     32  /* Saw an E (or e) in current state */
2045 #define PNG_FP_SAW_ANY   60  /* Saw any of the above 4 */
2046 
2047 /* These three values don't affect the parser.  They are set but not used.
2048  */
2049 #define PNG_FP_WAS_VALID 64  /* Preceding substring is a valid fp number */
2050 #define PNG_FP_NEGATIVE 128  /* A negative number, including "-0" */
2051 #define PNG_FP_NONZERO  256  /* A non-zero value */
2052 #define PNG_FP_STICKY   448  /* The above three flags */
2053 
2054 /* This is available for the caller to store in 'state' if required.  Do not
2055  * call the parser after setting it (the parser sometimes clears it.)
2056  */
2057 #define PNG_FP_INVALID  512  /* Available for callers as a distinct value */
2058 
2059 /* Result codes for the parser (boolean - true meants ok, false means
2060  * not ok yet.)
2061  */
2062 #define PNG_FP_MAYBE      0  /* The number may be valid in the future */
2063 #define PNG_FP_OK         1  /* The number is valid */
2064 
2065 /* Tests on the sticky non-zero and negative flags.  To pass these checks
2066  * the state must also indicate that the whole number is valid - this is
2067  * achieved by testing PNG_FP_SAW_DIGIT (see the implementation for why this
2068  * is equivalent to PNG_FP_OK above.)
2069  */
2070 #define PNG_FP_NZ_MASK (PNG_FP_SAW_DIGIT | PNG_FP_NEGATIVE | PNG_FP_NONZERO)
2071    /* NZ_MASK: the string is valid and a non-zero negative value */
2072 #define PNG_FP_Z_MASK (PNG_FP_SAW_DIGIT | PNG_FP_NONZERO)
2073    /* Z MASK: the string is valid and a non-zero value. */
2074    /* PNG_FP_SAW_DIGIT: the string is valid. */
2075 #define PNG_FP_IS_ZERO(state) (((state) & PNG_FP_Z_MASK) == PNG_FP_SAW_DIGIT)
2076 #define PNG_FP_IS_POSITIVE(state) (((state) & PNG_FP_NZ_MASK) == PNG_FP_Z_MASK)
2077 #define PNG_FP_IS_NEGATIVE(state) (((state) & PNG_FP_NZ_MASK) == PNG_FP_NZ_MASK)
2078 
2079 /* The actual parser.  This can be called repeatedly. It updates
2080  * the index into the string and the state variable (which must
2081  * be initialized to 0).  It returns a result code, as above.  There
2082  * is no point calling the parser any more if it fails to advance to
2083  * the end of the string - it is stuck on an invalid character (or
2084  * terminated by '\0').
2085  *
2086  * Note that the pointer will consume an E or even an E+ and then leave
2087  * a 'maybe' state even though a preceding integer.fraction is valid.
2088  * The PNG_FP_WAS_VALID flag indicates that a preceding substring was
2089  * a valid number.  It's possible to recover from this by calling
2090  * the parser again (from the start, with state 0) but with a string
2091  * that omits the last character (i.e. set the size to the index of
2092  * the problem character.)  This has not been tested within libpng.
2093  */
2094 PNG_INTERNAL_FUNCTION(int,png_check_fp_number,(png_const_charp string,
2095    png_size_t size, int *statep, png_size_tp whereami),PNG_EMPTY);
2096 
2097 /* This is the same but it checks a complete string and returns true
2098  * only if it just contains a floating point number.  As of 1.5.4 this
2099  * function also returns the state at the end of parsing the number if
2100  * it was valid (otherwise it returns 0.)  This can be used for testing
2101  * for negative or zero values using the sticky flag.
2102  */
2103 PNG_INTERNAL_FUNCTION(int,png_check_fp_string,(png_const_charp string,
2104    png_size_t size),PNG_EMPTY);
2105 #endif /* pCAL || sCAL */
2106 
2107 #if defined(PNG_GAMMA_SUPPORTED) ||\
2108     defined(PNG_INCH_CONVERSIONS_SUPPORTED) || defined(PNG_READ_pHYs_SUPPORTED)
2109 /* Added at libpng version 1.5.0 */
2110 /* This is a utility to provide a*times/div (rounded) and indicate
2111  * if there is an overflow.  The result is a boolean - false (0)
2112  * for overflow, true (1) if no overflow, in which case *res
2113  * holds the result.
2114  */
2115 PNG_INTERNAL_FUNCTION(int,png_muldiv,(png_fixed_point_p res, png_fixed_point a,
2116    png_int_32 multiplied_by, png_int_32 divided_by),PNG_EMPTY);
2117 #endif /* GAMMA || INCH_CONVERSIONS || READ_pHYs */
2118 
2119 #ifdef PNG_READ_GAMMA_SUPPORTED
2120 /* Internal fixed point gamma correction.  These APIs are called as
2121  * required to convert single values - they don't need to be fast,
2122  * they are not used when processing image pixel values.
2123  */
2124 PNG_INTERNAL_FUNCTION(unsigned int,png_gamma_nxmbit_correct,
2125    (unsigned int value, png_fixed_point gamma_val, unsigned int n/*input bits*/,
2126     unsigned int m/*output bits */),PNG_EMPTY);
2127    /* In this case the value must have 'n' bits and the output will have 'm'
2128     * bits.
2129     */
2130 
2131 #if !PNG_RELEASE_BUILD
2132 PNG_INTERNAL_FUNCTION(int,png_gamma_check,(png_const_structrp png_ptr,
2133    png_const_transform_controlp tc),PNG_EMPTY);
2134    /* Debugging only routine to repeat the test used above to determine if the
2135     * gamma was insignificant.
2136     */
2137 #endif /* !RELEASE_BUILD */
2138 #endif /* READ_GAMMA */
2139 
2140 #ifdef PNG_SIMPLIFIED_READ_SUPPORTED
2141 /* Internal check function to saw if the gamma of the PNG data is far enough
2142  * from the given screen gamma to require gamma correction (only needed for a
2143  * bug work-round in the simplified API).
2144  * TODO: it should be possible to remove the bug work-round in 1.7
2145  */
2146 PNG_INTERNAL_FUNCTION(int,png_need_gamma_correction,(png_const_structrp png_ptr,
2147    png_fixed_point gamma, int sRGB_output),PNG_EMPTY);
2148 #endif /* SIMPLIFIED_READ */
2149 
2150 /* This is a utility macro to say whether a gamma value is close enough to sRGB.
2151  * The test is now hardwired:
2152  *
2153  * API CHANGE: prior to 1.7 this would depend on the build-time
2154  * PNG_GAMMA_THRESHOLD_FIXED setting, which would cause inconsistent results
2155  * when the setting was changed.  Since this setting can now be changed at
2156  * run-time it seems more sensible to have a single fixed definition of 'sRGB'.
2157  *
2158  * The test is approximately +/- 1%, it allows any decimal value from 0.45 (the
2159  * two digit rounded version of 1/2.2) to just under 0.46).
2160  */
2161 #define PNG_GAMMA_IS_sRGB(g) ((g) >= 45000 && (g) < 46000)
2162 
2163 /* SIMPLIFIED READ/WRITE SUPPORT */
2164 #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\
2165    defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
2166 /* The internal structure that png_image::opaque points to. */
2167 typedef struct png_control
2168 {
2169    png_structp png_ptr;
2170    png_infop   info_ptr;
2171    png_voidp   error_buf;           /* Always a jmp_buf at present. */
2172 
2173    png_const_bytep memory;          /* Memory buffer. */
2174    png_size_t      size;            /* Size of the memory buffer. */
2175 
2176    unsigned int for_write       :1; /* Otherwise it is a read structure */
2177    unsigned int owned_file      :1; /* We own the file in io_ptr */
2178 } png_control;
2179 
2180 /* Return the pointer to the jmp_buf from a png_control: necessary because C
2181  * does not reveal the type of the elements of jmp_buf.
2182  */
2183 #ifdef __cplusplus
2184 #  define png_control_jmp_buf(pc) (((jmp_buf*)((pc)->error_buf))[0])
2185 #else
2186 #  define png_control_jmp_buf(pc) ((pc)->error_buf)
2187 #endif
2188 
2189 /* Utility to safely execute a piece of libpng code catching and logging any
2190  * errors that might occur.  Returns true on success, false on failure (either
2191  * of the function or as a result of a png_error.)
2192  */
2193 PNG_INTERNAL_CALLBACK(void,png_safe_error,(png_structp png_ptr,
2194    png_const_charp error_message),PNG_NORETURN);
2195 
2196 #ifdef PNG_WARNINGS_SUPPORTED
2197 PNG_INTERNAL_CALLBACK(void,png_safe_warning,(png_structp png_ptr,
2198    png_const_charp warning_message),PNG_EMPTY);
2199 #else
2200 #  define png_safe_warning 0/*dummy argument*/
2201 #endif
2202 
2203 PNG_INTERNAL_FUNCTION(int,png_safe_execute,(png_imagep image,
2204    int (*function)(png_voidp), png_voidp arg),PNG_EMPTY);
2205 
2206 /* Utility to log an error; this also cleans up the png_image; the function
2207  * always returns 0 (false).
2208  */
2209 PNG_INTERNAL_FUNCTION(int,png_image_error,(png_imagep image,
2210    png_const_charp error_message),PNG_EMPTY);
2211 
2212 /* Safely initialize a stdio pointer - used by both the read and the write
2213  * code.
2214  */
2215 #ifdef PNG_STDIO_SUPPORTED
2216 PNG_INTERNAL_FUNCTION(int,png_image_init_io,(png_imagep image, png_FILE_p file),
2217    PNG_EMPTY);
2218 #endif /* STDIO */
2219 
2220 #ifndef PNG_SIMPLIFIED_READ_SUPPORTED
2221 /* png_image_free is used by the write code but not exported */
2222 PNG_INTERNAL_FUNCTION(void, png_image_free, (png_imagep image), PNG_EMPTY);
2223 #endif /* !SIMPLIFIED_READ */
2224 
2225 #endif /* SIMPLIFIED READ/WRITE */
2226 
2227 #ifdef PNG_READ_SUPPORTED
2228 PNG_INTERNAL_FUNCTION(png_int_32, png_read_setting, (png_structrp png_ptr,
2229    png_uint_32 setting, png_uint_32 parameter, png_int_32 value), PNG_EMPTY);
2230 #endif /* READ */
2231 #ifdef PNG_WRITE_SUPPORTED
2232 PNG_INTERNAL_FUNCTION(png_int_32,  png_write_setting, (png_structrp png_ptr,
2233    png_uint_32 setting, png_uint_32 parameter, png_int_32 value), PNG_EMPTY);
2234    /* Implementations of read and write settings, in pngrutil.c and pngwutil.c
2235     * respectively.
2236     */
2237 #endif /* WRITE */
2238 
2239 /* Maintainer: Put new private prototypes here ^ */
2240 
2241 /* These are initialization functions for hardware specific PNG filter
2242  * optimizations; list these here then select the appropriate one at compile
2243  * time using the macro PNG_FILTER_OPTIMIZATIONS.  If the macro is not defined
2244  * the generic code is used.
2245  */
2246 #ifdef PNG_FILTER_OPTIMIZATIONS
2247 PNG_INTERNAL_FUNCTION(void, PNG_FILTER_OPTIMIZATIONS, (png_structrp png_ptr,
2248    unsigned int bpp), PNG_EMPTY);
2249    /* Just declare the optimization that will be used */
2250 #else
2251    /* List *all* the possible optimizations here - this branch is required if
2252     * the builder of libpng passes the definition of PNG_FILTER_OPTIMIZATIONS in
2253     * CFLAGS in place of CPPFLAGS *and* uses symbol prefixing.
2254     */
2255 PNG_INTERNAL_FUNCTION(void, png_init_filter_functions_neon,
2256    (png_structp png_ptr, unsigned int bpp), PNG_EMPTY);
2257 #endif
2258 
2259 #include "pngdebug.h"
2260 
2261 /* EXTENSION SPECIFIC FUNCTIONS */
2262 #include "arm/neon.h"
2263 
2264 #ifdef __cplusplus
2265 }
2266 #endif
2267 
2268 #endif /* PNG_VERSION_INFO_ONLY */
2269 #endif /* PNGPRIV_H */
2270