Bug 841734 - Update libpng to version 1.6.6. r=jmuizelaar
authorGlenn Randers-Pehrson <glennrp+bmo@gmail.com>
Thu, 26 Sep 2013 14:39:44 -0400
changeset 148865 8b84e9b8e24d015d722bed2de782822d3b71eba5
parent 148864 65c4f12212040f9bb0fd9a93154596c222601daf
child 148866 ee1bd7d5dae454c8d4349e04242dbf05ffc26810
push id2853
push userryanvm@gmail.com
push dateFri, 27 Sep 2013 01:39:33 +0000
treeherderfx-team@e4cd2242cc7d [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersjmuizelaar
bugs841734
milestone27.0a1
Bug 841734 - Update libpng to version 1.6.6. r=jmuizelaar
configure.in
media/libpng/CHANGES
media/libpng/LICENSE
media/libpng/MOZCHANGES
media/libpng/README
media/libpng/apng.patch
media/libpng/arm/arm_init.c
media/libpng/arm/filter_neon.S
media/libpng/libpng-manual.txt
media/libpng/mozpngconf.h
media/libpng/png.c
media/libpng/png.h
media/libpng/pngconf.h
media/libpng/pngerror.c
media/libpng/pngget.c
media/libpng/pnginfo.h
media/libpng/pngmem.c
media/libpng/pngpread.c
media/libpng/pngpriv.h
media/libpng/pngread.c
media/libpng/pngrio.c
media/libpng/pngrtran.c
media/libpng/pngrutil.c
media/libpng/pngset.c
media/libpng/pngstruct.h
media/libpng/pngtrans.c
media/libpng/pngwio.c
media/libpng/pngwrite.c
media/libpng/pngwtran.c
media/libpng/pngwutil.c
--- a/configure.in
+++ b/configure.in
@@ -46,17 +46,17 @@ dnl ====================================
 _SUBDIR_HOST_CFLAGS="$HOST_CFLAGS"
 _SUBDIR_HOST_CXXFLAGS="$HOST_CXXFLAGS"
 _SUBDIR_HOST_LDFLAGS="$HOST_LDFLAGS"
 _SUBDIR_CONFIG_ARGS="$ac_configure_args"
 
 dnl Set the version number of the libs included with mozilla
 dnl ========================================================
 MOZJPEG=62
-MOZPNG=10517
+MOZPNG=10606
 NSPR_VERSION=4
 NSS_VERSION=3
 
 dnl Set the minimum version of toolkit libs used by mozilla
 dnl ========================================================
 GLIB_VERSION=1.2.0
 PERL_VERSION=5.006
 CAIRO_VERSION=1.10
--- a/media/libpng/CHANGES
+++ b/media/libpng/CHANGES
@@ -3771,357 +3771,809 @@ Version 1.5.7rc02 [December 5, 2011]
   Put CRLF line endings in the owatcom project files.
 
 Version 1.5.7rc03 [December 7, 2011]
   Updated CMakeLists.txt to account for the relocation of pngvalid.c
 
 Version 1.5.7 [December 15, 2011]
   Minor fixes to pngvalid.c for gcc 4.6.2 compatibility to remove warnings
     reported by earlier versions.
-
-Version 1.5.8beta01 [January 15, 2011]
-  Removed '#include config.h"' from contrib/libtests/pngvalid.c.  It's not
-    needed and causes trouble for VPATH building.
+  Fixed minor memset/sizeof errors in pngvalid.c.
+
+Version 1.6.0beta01 [December 15, 2011]
+  Removed machine-generated configure files from the GIT repository (they will
+    continue to appear in the tarball distributions and in the libpng15 and
+    earlier GIT branches).
+  Restored the new 'simplified' API, which was started in libpng-1.5.7beta02
+    but later deleted from libpng-1.5.7beta05.
+  Added example programs for the new 'simplified' API.
+  Added ANSI-C (C90) headers and require them, and take advantage of the
+    change. Also fixed some of the projects/* and contrib/* files that needed
+    updates for libpng16 and the move of pngvalid.c.
+    With this change the required ANSI-C header files are assumed to exist: the
+    implementation must provide float.h, limits.h, stdarg.h and stddef.h and
+    libpng relies on limits.h and stddef.h existing and behaving as defined
+    (the other two required headers aren't used).  Non-ANSI systems that don't
+    have stddef.h or limits.h will have to provide an appropriate fake
+    containing the relevant types and #defines.
+  The use of FAR/far has been eliminated and the definition of png_alloc_size_t
+    is now controlled by a flag so that 'small size_t' systems can select it
+    if necessary.  Libpng 1.6 may not currently work on such systems -- it
+    seems likely that it will ask 'malloc' for more than 65535 bytes with any
+    image that has a sufficiently large row size (rather than simply failing
+    to read such images).
+  New tools directory containing tools used to generate libpng code.
+  Fixed race conditions in parallel make builds. With higher degrees of
+    parallelism during 'make' the use of the same temporary file names such
+    as 'dfn*' can result in a race where a temporary file from one arm of the
+    build is deleted or overwritten in another arm.  This changes the
+    temporary files for suffix rules to always use $* and ensures that the
+    non-suffix rules use unique file names.
+
+Version 1.6.0beta02 [December 21, 2011]
+  Correct configure builds where build and source directories are separate.
+    The include path of 'config.h' was erroneously made relative in pngvalid.c
+    in libpng 1.5.7.
+
+Version 1.6.0beta03 [December 22, 2011]
+  Start-up code size improvements, error handler flexibility. These changes
+    alter how the tricky allocation of the initial png_struct and png_info
+    structures are handled. png_info is now handled in pretty much the same
+    way as everything else, except that the allocations handle NULL return
+    silently.  png_struct is changed in a similar way on allocation and on
+    deallocation a 'safety' error handler is put in place (which should never
+    be required).  The error handler itself is changed to permit mismatches
+    in the application and libpng error buffer size; however, this means a
+    silent change to the API to return the jmp_buf if the size doesn't match
+    the size from the libpng compilation; libpng now allocates the memory and
+    this may fail.  Overall these changes result in slight code size
+    reductions; however, this is a reduction in code that is always executed
+    so is particularly valuable.  Overall on a 64-bit system the libpng DLL
+    decreases in code size by 1733 bytes.  pngerror.o increases in size by
+    about 465 bytes because of the new functionality.
+  Added png_convert_to_rfc1123_buffer() and deprecated png_convert_to_rfc1123()
+    to avoid including a spurious buffer in the png_struct.
+
+Version 1.6.0beta04 [December 30, 2011]
+  Regenerated configure scripts with automake-1.11.2
+  Eliminated png_info_destroy(). It is now used only in png.c and only calls
+    one other internal function and memset().
+  Enabled png_get_sCAL_fixed() if floating point APIs are enabled. Previously
+    it was disabled whenever internal fixed point arithmetic was selected,
+    which meant it didn't exist even on systems where FP was available but not
+    preferred.
+  Added pngvalid.c compile time checks for const APIs.
+  Implemented 'restrict' for png_info and png_struct. Because of the way
+    libpng works both png_info and png_struct are always accessed via a
+    single pointer.  This means adding C99 'restrict' to the pointer gives
+    the compiler some opportunity to optimize the code.  This change allows
+    that.
   Moved AC_MSG_CHECKING([if libraries can be versioned]) later to the proper
     location in configure.ac (Gilles Espinasse).
+  Changed png_memcpy to C assignment where appropriate. Changed all those
+    uses of png_memcpy that were doing a simple assignment to assignments
+    (all those cases where the thing being copied is a non-array C L-value).
+  Added some error checking to png_set_*() routines.
+  Removed the reference to the non-exported function png_memcpy() from
+    example.c.
+  Fixed the Visual C 64-bit build - it requires jmp_buf to be aligned, but
+    it had become misaligned.
+  Revised contrib/pngminus/pnm2png.c to avoid warnings when png_uint_32
+    and unsigned long are of different sizes.
+
+Version 1.6.0beta05 [January 15, 2012]
+  Updated manual with description of the simplified API (copied from png.h)
   Fix bug in pngerror.c: some long warnings were being improperly truncated
     (CVE-2011-3464, bug introduced in libpng-1.5.3beta05).
 
-Version 1.5.8rc01 [January 21, 2012]
-  No changes.
-
-Version 1.5.8rc02 [January 25, 2012]
+Version 1.6.0beta06 [January 24, 2012]
+  Added palette support to the simplified APIs. This commit
+    changes some of the macro definitions in png.h, app code
+    may need corresponding changes.
+  Increased the formatted warning buffer to 192 bytes.
+  Added color-map support to simplified API. This is an initial version for
+    review; the documentation has not yet been updated.
   Fixed Min/GW uninstall to remove libpng.dll.a
-  Conditionalize the install rules for MINGW and CYGWIN in CMakeLists.txt
-
-Version 1.5.8 [February 1, 2012]
-  No changes.
-
-Version 1.5.9beta01 [February 3, 2012]
-  Rebuilt configure scripts in the tar distributions.
-
-Version 1.5.9beta02 [February 16, 2012]
-  Removed two unused definitions from scripts/pnglibconf.h.prebuilt
+
+Version 1.6.0beta07 [January 28, 2012]
+  Eliminated Intel icc/icl compiler warnings. The Intel (GCC derived)
+    compiler issues slightly different warnings from those issued by the
+    current vesions of GCC. This eliminates those warnings by
+    adding/removing casts and small code rewrites.
+  Updated configure.ac from autoupdate: added --enable-werror option.
+    Also some layout regularization and removal of introduced tab characters
+    (replaced with 3-character indentation).  Obsolete macros identified by
+    autoupdate have been removed; the replacements are all in 2.59 so
+    the pre-req hasn't been changed.  --enable-werror checks for support
+    for -Werror (or the given argument) in the compiler.  This mimics the
+    gcc configure option by allowing -Werror to be turned on safely; without
+    the option the tests written in configure itself fail compilation because
+    they cause compiler warnings.
+  Rewrote autogen.sh to run autoreconf instead of running tools one-by-one.
+  Conditionalize the install rules for MINGW and CYGWIN in CMakeLists.txt and
+    set CMAKE_LIBRARY_OUTPUT_DIRECTORY to "lib" on all platforms (C. Yapp).
+  Freeze libtool files in the 'scripts' directory. This version of autogen.sh
+    attempts to dissuade people from running it when it is not, or should not,
+    be necessary.  In fact, autogen.sh does not work when run in a libpng
+    directory extracted from a tar distribution anymore. You must run it in
+    a GIT clone instead.
+  Added two images to contrib/pngsuite (1-bit and 2-bit transparent grayscale),
+    and renamed three whose names were inconsistent with those in
+    pngsuite/README.txt.
+
+Version 1.6.0beta08 [February 1, 2012]
+  Fixed Image::colormap misalignment in pngstest.c
+  Check libtool/libtoolize version number (2.4.2) in configure.ac
+  Divide test-pngstest.sh into separate pngstest runs for basic and
+    transparent images.
+  Moved automake options to AM_INIT_AUTOMAKE in configure.ac
+  Added color-tests, silent-rules (Not yet implemented in Makefile.am) and
+    version checking to configure.ac
+  Improved pngstest speed by not doing redundant tests and add const to
+    the background parameter of png_image_finish_read. The --background
+    option is now done automagically only when required, so that commandline
+    option no longer exists.
+  Cleaned up pngpriv.h to consistently declare all functions and data.
+    Also eliminated PNG_CONST_DATA, which is apparently not needed but we
+    can't be sure until it is gone.
+  Added symbol prefixing that allows all the libpng external symbols
+    to be prefixed (suggested by Reuben Hawkins).
+  Updated "ftbb*.png" list in the owatcom and vstudio projects.
+  Fixed 'prefix' builds on clean systems. The generation of pngprefix.h
+    should not require itself.
+  Updated INSTALL to explain that autogen.sh must be run in a GIT clone,
+    not in a libpng directory extracted from a tar distribution.
+
+Version 1.6.0beta09 [February 1, 2012]
+  Reverted the prebuilt configure files to libpng-1.6.0beta05 condition.
+
+Version 1.6.0beta10 [February 3, 2012]
+  Added Z_SOLO for zlib-1.2.6+ and correct pngstest tests
+  Updated list of test images in CMakeLists.txt
+  Updated the prebuilt configure files to current condition.
+  Revised INSTALL information about autogen.sh; it works in tar distributions.
+
+Version 1.6.0beta11 [February 16, 2012]
+  Fix character count in pngstest command in projects/owatcom/pngstest.tgt
+  Revised test-pngstest.sh to report PASS/FAIL for each image.
+  Updated documentation about the simplified API.
+  Corrected estimate of error in libpng png_set_rgb_to_gray API.  The API is
+    extremely inaccurate for sRGB conversions because it uses an 8-bit
+    intermediate linear value and it does not use the sRGB transform, so it
+    suffers from the known instability in gamma transforms for values close
+    to 0 (see Poynton).  The net result is that the calculation has a maximum
+    error of 14.99/255; 0.5/255^(1/2.2).  pngstest now uses 15 for the
+    permitted 8-bit error. This may still not be enough because of arithmetic
+    error.
   Removed some unused arrays (with #ifdef) from png_read_push_finish_row().
+  Fixed a memory overwrite bug in simplified read of RGB PNG with
+    non-linear gamma Also bugs in the error checking in pngread.c and changed
+    quite a lot of the checks in pngstest.c to be correct; either correctly
+    written or not over-optimistic.  The pngstest changes are insufficient to
+    allow all possible RGB transforms to be passed; pngstest cmppixel needs
+    to be rewritten to make it clearer which errors it allows and then changed
+    to permit known inaccuracies.
   Removed tests for no-longer-used *_EMPTY_PLTE_SUPPORTED from pngstruct.h
-
-Version 1.5.9rc01 [February 17, 2012]
+  Fixed fixed/float API export conditionals. 1) If FIXED_POINT or
+    FLOATING_POINT options were switched off, png.h ended up with lone ';'
+    characters.  This is not valid ANSI-C outside a function.  The ';'
+    characters have been moved inside the definition of PNG_FP_EXPORT and
+    PNG_FIXED_EXPORT. 2) If either option was switched off, the declaration
+    of the corresponding functions were completely omitted, even though some
+    of them are still used internally.  The result is still valid, but
+    produces warnings from gcc with some warning options (including -Wall). The
+    fix is to cause png.h to declare the functions with PNG_INTERNAL_FUNCTION
+    when png.h is included from pngpriv.h.
+  Check for invalid palette index while reading paletted PNG.  When one is
+    found, issue a warning and increase png_ptr->num_palette accordingly.
+    Apps are responsible for checking to see if that happened.
+
+Version 1.6.0beta12 [February 18, 2012]
+  Do not increase num_palette on invalid_index.
+  Relocated check for invalid palette index to pngrtran.c, after unpacking
+    the sub-8-bit pixels.
   Fixed CVE-2011-3026 buffer overrun bug.  This bug was introduced when
     iCCP chunk support was added at libpng-1.0.6. Deal more correctly with the
     test on iCCP chunk length. Also removed spurious casts that may hide
     problems on 16-bit systems.
 
-Version 1.5.9 [February 18, 2012]
-  No changes.
-
-Version 1.5.10beta01 [February 24, 2012]
-  Removed two useless #ifdef directives from pngread.c and one from pngrutil.c
-  Always put the CMAKE_LIBRARY in "lib" (removed special WIN32 case).
-  Removed empty vstudio/pngstest directory (Clifford Yapp).
+Version 1.6.0beta13 [February 24, 2012]
   Eliminated redundant png_push_read_tEXt|zTXt|iTXt|unknown code from
     pngpread.c and use the sequential png_handle_tEXt, etc., in pngrutil.c;
     now that png_ptr->buffer is inaccessible to applications, the special
     handling is no longer useful.
-  Fixed bug with png_handle_hIST with odd chunk length (Frank Busse).
-  Added PNG_SAFE_LIMITS feature to pnglibconf.dfa and code in pngconf.h
-    to reset the user limits to safe ones if PNG_SAFE_LIMITS is defined.
-    To enable, use "CPPFLAGS=-DPNG_SAFE_LIMITS_SUPPORTED" on the configure
-    command or put "#define PNG_SAFE_LIMITS_SUPPORTED" in pnglibconf.h.
-  Revised the SAFE_LIMITS feature to be the same as the feature in libpng16.
+  Added PNG_SAFE_LIMITS feature to pnglibconf.dfa, pngpriv.h, and new
+    pngusr.dfa to reset the user limits to safe ones if PNG_SAFE_LIMITS is
+    defined.  To enable, use "CPPFLAGS=-DPNG_SAFE_LIMITS_SUPPORTED=1" on the
+    configure command or put #define PNG_SAFE_LIMITS_SUPPORTED in
+    pnglibconf.h.prebuilt and pnglibconf.h.
+
+Version 1.6.0beta14 [February 27, 2012]
   Added information about the new limits in the manual.
-
-Version 1.5.10beta02 [February 27, 2012]
   Updated Makefile.in
 
-Version 1.5.10beta03 [March 6, 2012]
+Version 1.6.0beta15 [March 2, 2012]
   Removed unused "current_text" members of png_struct and the png_free()
     of png_ptr->current_text from pngread.c
-  Added palette-index checking. Issue a png_warning() if an invalid index is
-    found.
-
-Version 1.5.10beta04 [March 10, 2012]
-  Fixed PNG_LIBPNG_BUILD_BASE_TYPE definition.
-  Fixed CMF optimization of non-IDAT compressed chunks, which was added at
-    libpng-1.5.4.  It sometimes produced too small of a window.
-
-Version 1.5.10beta05 [March 10, 2012]
+  Rewrote pngstest.c for substantial speed improvement.
+  Fixed transparent pixel and 16-bit rgb tests in pngstest and removed a
+    spurious check in pngwrite.c
+  Added PNG_IMAGE_FLAG_FAST for the benefit of applications that store
+    intermediate files, or intermediate in-memory data, while processing
+    image data with the simplified API.  The option makes the files larger
+    but faster to write and read.  pngstest now uses this by default; this
+    can be disabled with the --slow option.
+  Improved pngstest fine tuning of error numbers, new test file generator.
+    The generator generates images that test the full range of sample values,
+    allow the error numbers in pngstest to be tuned and checked.  makepng
+    also allows generation of images with extra chunks, although this is
+    still work-in-progress.
+  Added check for invalid palette index while reading.
+  Fixed some bugs in ICC profile writing. The code should now accept
+    all potentially valid ICC profiles and reject obviously invalid ones.
+    It now uses png_error() to do so rather than casually writing a PNG
+    without the necessary color data.
+  Removed whitespace from the end of lines in all source files and scripts.
+
+Version 1.6.0beta16 [March 6, 2012]
+  Relocated palette-index checking function from pngrutil.c to pngtrans.c
+  Added palette-index checking while writing.
+  Changed png_inflate() and calling routines to avoid overflow problems.
+    This is an intermediate check-in that solves the immediate problems and
+    introduces one performance improvement (avoiding a copy via png_ptr->zbuf.)
+    Further changes will be made to make ICC profile handling more secure.
+  Fixed build warnings (MSVC, GCC, GCC v3). Cygwin GCC with default options
+    declares 'index' as a global, causing a warning if it is used as a local
+    variable.  GCC 64-bit warns about assigning a (size_t) (unsigned 64-bit)
+    to an (int) (signed 32-bit).  MSVC, however, warns about using the
+    unary '-' operator on an unsigned value (even though it is well defined
+    by ANSI-C to be ~x+1).  The padding calculation was changed to use a
+    different method.  Removed the tests on png_ptr->pass.
+  Added contrib/libtests/tarith.c to test internal arithmetic functions from
+    png.c. This is a libpng maintainer program used to validate changes to the
+    internal arithmetic functions.
+  Made read 'inflate' handling like write 'deflate' handling. The read
+    code now claims and releases png_ptr->zstream, like the write code.
+    The bug whereby the progressive reader failed to release the zstream
+    is now fixed, all initialization is delayed, and the code checks for
+    changed parameters on deflate rather than always calling
+    deflatedEnd/deflateInit.
+  Validate the zTXt strings in pngvalid.
+  Added code to validate the windowBits value passed to deflateInit2().
+    If the call to deflateInit2() is wrong a png_warning will be issued
+    (in fact this is harmless, but the PNG data produced may be sub-optimal).
+
+Version 1.6.0beta17 [March 10, 2012]
+  Fixed PNG_LIBPNG_BUILD_BASE_TYPE definition. 
   Reject all iCCP chunks after the first, even if the first one is invalid.
+  Deflate/inflate was reworked to move common zlib calls into single
+    functions [rw]util.c.  A new shared keyword check routine was also added
+    and the 'zbuf' is no longer allocated on progressive read.  It is now
+    possible to call png_inflate() incrementally.  A warning is no longer
+    issued if the language tag or translated keyword in the iTXt chunk
+    has zero length.
+  If benign errors are disabled use maximum window on ancilliary inflate.
+    This works round a bug introduced in 1.5.4 where compressed ancillary
+    chunks could end up with a too-small windowBits value in the deflate
+    header.
+
+Version 1.6.0beta18 [March 16, 2012]
   Issue a png_benign_error() instead of png_warning() about bad palette index.
+  In pngtest, treat benign errors as errors if "-strict" is present.
   Fixed an off-by-one error in the palette index checking function.
+  Fixed a compiler warning under Cygwin (Windows-7, 32-bit system)
   Revised example.c to put text strings in a temporary character array
     instead of directly assigning string constants to png_textp members.
     This avoids compiler warnings when -Wwrite-strings is enabled.
-
-Version 1.5.10 [March 29, 2012]
+  Added output flushing to aid debugging under Visual Studio. Unfortunately
+    this is necessary because the VS2010 output window otherwise simply loses
+    the error messages on error (they weren't flushed to the window before
+    the process exited, apparently!)
+  Added configuration support for benign errors and changed the read
+    default. Also changed some warnings in the iCCP and sRGB handling
+    from to benign errors. Configuration now makes read benign
+    errors warnings and write benign errors to errors by default (thus
+    changing the behavior on read).  The simplified API always forces
+    read benign errors to warnings (regardless of the system default, unless
+    this is disabled in which case the simplified API can't be built.)
+
+Version 1.6.0beta19 [March 18, 2012]
+  Work around for duplicate row start calls; added warning messages.
+    This turns on PNG_FLAG_DETECT_UNINITIALIZED to detect app code that
+    fails to call one of the 'start' routines (not enabled in libpng-1.5
+    because it is technically an API change, since it did normally work
+    before.)  It also makes duplicate calls to png_read_start_row (an
+    internal function called at the start of the image read) benign, as
+    they were before changes to use png_inflate_claim. Somehow webkit is
+    causing this to happen; this is probably a mis-feature in the zlib
+    changes so this commit is only a work-round.
+  Removed erroneous setting of DETECT_UNINITIALIZED and added more
+    checks. The code now does a png_error if an attempt is made to do the
+    row initialization twice; this is an application error and it has
+    serious consequences because the transform data in png_struct is
+    changed by each call.
+  Added application error reporting and added chunk names to read
+    benign errors; also added --strict to pngstest - not enabled
+    yet because a warning is produced.
+  Avoid the double gamma correction warning in the simplified API.
+    This allows the --strict option to pass in the pngstest checks
+
+Version 1.6.0beta20 [March 29, 2012]
+  Changed chunk handler warnings into benign errors, incrementally load iCCP
+  Added checksum-icc.c to contrib/tools
   Prevent PNG_EXPAND+PNG_SHIFT doing the shift twice.
+  Recognize known sRGB ICC profiles while reading; prefer writing the
+    iCCP profile over writing the sRGB chunk, controlled by the
+    PNG_sRGB_PROFILE_CHECKS option.
   Revised png_set_text_2() to avoid potential memory corruption (fixes
     CVE-2011-3048, also known as CVE-2012-3425).
 
-Version 1.5.11beta01 [April 28, 2012]
+Version 1.6.0beta21 [April 27, 2012]
   Revised scripts/makefile.darwin: use system zlib; remove quotes around
     architecture list; add missing ppc architecture; add architecture options
     to shared library link; don't try to create a shared lib based on missing
     RELEASE variable.
   Enable png_set_check_for_invalid_index() for both read and write.
-  Removed #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED/#endif in pngpriv.h around
+  Removed #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED in pngpriv.h around
     declaration of png_handle_unknown().
   Added -lssp_nonshared in a comment in scripts/makefile.freebsd
     and changed deprecated NOOBJ and NOPROFILE to NO_OBJ and NO_PROFILE.
 
-Version 1.5.11rc01 [May 23, 2012]
-  No changes.
-
-Version 1.5.11rc02 [May 29, 2012]
-  Fixed some typos in comments.
+Version 1.6.0beta22 [May 23, 2012]
+  Removed need for -Wno-cast-align with clang.  clang correctly warns on
+    alignment increasing pointer casts when -Wcast-align is passed. This
+    fixes the cases that clang warns about either by eliminating the
+    casts from png_bytep to png_uint_16p (pngread.c), or, for pngrutil.c
+    where the cast is previously verified or pngstest.c where it is OK, by
+    introducing new png_aligncast macros to do the cast in a way that clang
+    accepts.
+
+Version 1.6.0beta23 [June 6, 2012]
   Revised CMakeLists.txt to not attempt to make a symlink under mingw.
-  Added two images to contrib/pngsuite (1-bit and 2-bit transparent grayscale),
-    and renamed three whose names were inconsistent with those in
-    pngsuite/README.txt.
-
-Version 1.5.11rc03 [June 4, 2012]
+  Made fixes for new optimization warnings from gcc 4.7.0. The compiler
+    performs an optimization which is safe; however it then warns about it.
+    Changing the type of 'palette_number' in pngvalid.c removes the warning.
   Do not depend upon a GCC feature macro being available for use in generating
     the linker mapfile symbol prefix.
-  Made fixes for new optimization warnings from gcc 4.7.0. The compiler
-    performed an optimization which is safe but then warned about it.
-    Changing the type of 'palette_number' in pngvalid.c removes the warning.
-
-Version 1.5.11rc04 [June 6, 2012]
-  Improved performance of new do_check_palette_indexes() function.
-
-Version 1.5.11rc05 [June 7, 2012]
+  Improved performance of new do_check_palette_indexes() function (only
+    update the value when it actually increases, move test for whether
+    the check is wanted out of the function.
+
+Version 1.6.0beta24 [June 7, 2012]
   Don't check palette indexes if num_palette is 0 (as it can be in MNG files).
 
-Version 1.5.11 [June 14, 2012]
-  Include zlib.h in contrib/gregbook and contrib/visupng examples.
-
-Version 1.5.12 [July 11, 2012]
+Version 1.6.0beta25 [June 16, 2012]
+  Revised png_set_keep_unknown_chunks() so num_chunks < 0 means ignore all
+    unknown chunks and all known chunks except for IHDR, PLTE, tRNS, IDAT,
+    and IEND.  Previously it only meant ignore all unknown chunks, the
+    same as num_chunks == 0. Revised png_image_skip_unused_chunks() to
+    provide a list of chunks to be processed instead of a list of chunks to
+    ignore.  Revised contrib/gregbook/readpng2.c accordingly.
+
+Version 1.6.0beta26 [July 10, 2012]
   Removed scripts/makefile.cegcc from the *.zip and *.7z distributions; it
     depends on configure, which is not included in those archives.
+  Moved scripts/chkfmt to contrib/tools.
   Changed "a+w" to "u+w" in Makefile.in to fix CVE-2012-3386.
 
-Version 1.5.13beta01 [August 8, 2012]
+Version 1.6.0beta27 [August 11, 2012]
   Do not compile PNG_DEPRECATED, PNG_ALLOC and PNG_PRIVATE when __GNUC__ < 3.
+  Do not use __restrict when GNUC is <= 3.1
   Removed references to png_zalloc() and png_zfree() from the manual.
-  Revised PNG_FP_EXPORT and PNG_FIXED_EXPORT macros to avoid generating
-    lone semicolons (patch ported from libpng-1.6.0beta11).
-
-Version 1.5.13beta02 [September 10, 2012]
-  Corrected handling of the image array and the row_pointers array in example.c
-  When png_set_filler is used to strip a filler channel during write, the
-    code prior to 1.5 would ignore the case where the output required an
-    alpha channel or when the output was a palettized PNG.  In libpng-1.5 the
-    ignorance was lost and libpng proceeded to strip the channel resulting
-    in a bad (potential memory overwrite) failure later.  This reverts
-    the behavior to the pre-1.5 state but issues a warning. libpng-1.6 is
-    expected to issue an error on the erroneous png_set_filler call.
-  Use png_memset() consistently (pngmem.c contained some bare "memset" calls).
-
-Version 1.5.13rc01 [September 17, 2012]
-  No changes.
-
-Version 1.5.13 [September 27, 2012]
-  No changes.
-
-Version 1.5.14beta01 [October 24, 2012]
+  Fixed configurations where floating point is completely disabled.  Because
+    of the changes to support symbol prefixing PNG_INTERNAL_FUNCTION declares
+    floating point APIs during libpng builds even if they are completely
+    disabled. This requires the png floating point types (png_double*) to be
+    declared even though the functions are never actually defined.  This
+    change provides a dummy definition so that the declarations work, yet any
+    implementation will fail to compile because of an incomplete type.
+  Re-eliminated the use of strcpy() in pngtest.c.  An unncessary use of
+    strcpy() was accidentally re-introduced in libpng16; this change replaces
+    it with strncpy().
+  Eliminated use of png_sizeof(); use sizeof() instead.
+  Use a consistent style for (sizeof type) and (sizeof (array))
+  Cleanup of png_set_filler().  This function does very different things on
+    read and write.  In libpng 1.6 the two cases can be distinguished and
+    considerable code cleanup, and extra error checking, is possible.  This
+    makes calls on the write side that have no effect be ignored with a
+    png_app_error(), which can be disabled in the app using
+    png_set_benign_errors(), and removes the spurious use of usr_channels
+    on the read side.
+  Insist on autotools 1.12.1 for git builds because there are security issues
+    with 1.12 and insisting on anything less would allow 1.12 to be used.
+  Removed info_ptr->signature[8] from WRITE-only builds.
+  Add some conditions for compiling png_fixed().  This is a small function
+    but it requires "-lm" on some platforms.
+  Cause pngtest --strict to fail on any warning from libpng (not just errors)
+    and cause it not to fail at the comparison step if libpng lacks support
+    for writing chunks that it reads from the input (currently only implemented
+    for compressed text chunks).
+  Make all three "make check" test programs work without READ or WRITE support.
+    Now "make check" will succeed even if libpng is compiled with -DPNG_NO_READ
+    or -DPNG_NO_WRITE.  The tests performed are reduced, but the basic reading
+    and writing of a PNG file is always tested by one or more of the tests.
+  Consistently use strlen(), memset(), memcpy(), and memcmp() instead of the
+    png_strlen(), png_memset(), png_memcpy(), and png_memcmp() macros.
+  Removed the png_sizeof(), png_strlen(), png_memset(), png_memcpy(), and
+    png_memcmp() macros.
+  Work around gcc 3.x and Microsoft Visual Studio 2010 complaints. Both object
+    to the split initialization of num_chunks.
+
+Version 1.6.0beta28 [August 29, 2012]
+  Unknown handling fixes and clean up. This adds more correct option
+    control of the unknown handling, corrects the pre-existing bug where
+    the per-chunk 'keep' setting is ignored and makes it possible to skip
+    IDAT chunks in the sequential reader (broken in earlier 1.6 versions).
+    There is a new test program, test-unknown.c, which is a work in progress
+    (not currently part of the test suite).  Comments in the header files now
+    explain how the unknown handling works.
+  Allow fine grain control of unknown chunk APIs. This change allows
+    png_set_keep_unknown_chunks() to be turned off if not required and causes
+    both read and write to behave appropriately (on read this is only possible
+    if the user callback is used to handle unknown chunks).  The change
+    also removes the support for storing unknown chunks in the info_struct
+    if the only unknown handling enabled is via the callback, allowing libpng
+    to be configured with callback reading and none of the unnecessary code.
+  Corrected fix for unknown handling in pngtest. This reinstates the
+    libpng handling of unknown chunks other than vpAg and sTER (including
+    unsafe-to-copy chunks which were dropped before) and eliminates the
+    repositioning of vpAg and sTER in pngtest.png by changing pngtest.png
+    (so the chunks are where libpng would put them).
+  Added "tunknown" test and corrected a logic error in png_handle_unknown()
+    when SAVE support is absent.  Moved the shell test scripts for
+    contrib/libtests from the libpng top directory to contrib/libtests.
+    png_handle_unknown() must always read or skip the chunk, if
+    SAVE_UNKNOWN_CHUNKS is turned off *and* the application does not set
+    a user callback an unknown chunk will not be read, leading to a read
+    error, which was revealed by the "tunknown" test.
+  Cleaned up and corrected ICC profile handling.
+    contrib/libtests/makepng: corrected 'rgb' and 'gray' cases.  profile_error
+    messages could be truncated; made a correct buffer size calculation and
+    adjusted pngerror.c appropriately. png_icc_check_* checking improved;
+    changed the functions to receive the correct color type of the PNG on read
+    or write and check that it matches the color space of the profile (despite
+    what the comments said before, there is danger in assuming the app will
+    cope correctly with an RGB profile on a grayscale image and, since it
+    violates the PNG spec, allowing it is certain to produce inconsistent
+    app behavior and might even cause app crashes.) Check that profiles
+    contain the tags needed to process the PNG (tags all required by the ICC
+    spec). Removed unused PNG_STATIC from pngpriv.h.
+
+Version 1.6.0beta29 [September 4, 2012]
+  Fixed the simplified API example programs to add the *colormap parameter
+    to several of he API and improved the error message if the version field
+    is not set.
+  Added contrib/examples/* to the *.zip and *.7z distributions.
+  Updated simplified API synopses and description of the png_image structure
+    in the manual.
+  Made makepng and pngtest produce identical PNGs, add "--relaxed" option
+    to pngtest. The "--relaxed" option turns off the benign errors that are
+    enabled by default in pre-RC builds. makepng can now write ICC profiles
+    where the length has not been extended to a multiple of 4, and pngtest
+    now intercepts all libpng errors, allowing the previously-introduced
+    "--strict test" on no warnings to actually work.
+  Improved ICC profile handling including cHRM chunk generation and fixed
+    Cygwin+MSVC build errors. The ICC profile handling now includes more
+    checking.  Several errors that caused rejection of the profile are now
+    handled with a warning in such a way that the invalid profiles will be
+    read by default in release (but not pre-RC) builds but will not be
+    written by default.  The easy part of handling the cHRM chunk is written,
+    where the ICC profile contains the required data.  The more difficult
+    part plus guessing a gAMA value requires code to pass selected RGB values
+    through the profile.
+
+Version 1.6.0beta30 [October 24, 2012]
+  Changed ICC profile matrix/vector types to not depend on array type rules.
+    By the ANSI-C standard the new types should be identical to the previous
+    versions, and all known versions of gcc tested with the previous versions
+    except for GCC-4.2.1 work with this version.  The change makes the ANSI-C
+    rule that const applied to an array of elements applies instead to the
+    elements in the array moot by explicitly applying const to the base
+    elements of the png_icc_matrix and png_icc_vector types. The accidental
+    (harmless) 'const' previously applied to the parameters of two of the
+    functions have also been removed.
+  Added a work around for GCC 4.2 optimization bug.
+  Marked the broken (bad white point) original HP sRGB profiles correctly and
+    correct comments.
   Added -DZ_SOLO to contrib/pngminim/*/makefile to work with zlib-1.2.7
-  Warn about the incorrect runtime library setting for VS2010 debug DLL builds.
+  Use /MDd for vstudio debug builds. Also added pngunkown to the vstudio
+    builds, fixed build errors and corrected a minor exit code error in
+    pngvalid if the 'touch' file name is invalid.
+  Add updated WARNING file to projects/vstudio from libpng 1.5/vstudio
   Fixed build when using #define PNG_NO_READ_GAMMA in png_do_compose() in
     pngrtran.c (Domani Hannes).
 
-Version 1.5.14beta02 [omitted]
-
-Version 1.5.14beta03 [December 15, 2012]
-  Added missing "-" in front of DNO_GZIP in contrib/pngminim/*/makefile.
-  Check for png_ptr==NULL earlier in png_zalloc().
-  Ignore, with a warning, out-of-range value of num_trans in png_set_tRNS().
-  Rearranged building of ARM NEON optimizations. The ARM specific code is
-    split out entirely to the arm subdirectory and changes to configure.ac and
-    Makefile.am to add new stuff are reduced.  Now material code changes,
-    although for build test purposes, --enable-arm-neon now builds on non-ARM
-    systems.
-  Rebuilt Makefile.in, configure, etc., with autoconf-2.69 and automake-1.12.5.
+Version 1.6.0beta31 [November 1, 2012]
+  Undid the erroneous change to vstudio/pngvalid build in libpng-1.6.0beta30.
+  Made pngvalid so that it will build outside the libpng source tree.
+  Made builds -DPNG_NO_READ_GAMMA compile (the unit tests still fail).
+  Made PNG_NO_READ_GAMMA switch off interfaces that depend on READ_GAMMA.
+    Prior to 1.6.0 switching off READ_GAMMA did unpredictable things to the
+    interfaces that use it (specifically, png_do_background in 1.4 would
+    simply display composite for grayscale images but do composition
+    with the incorrect arithmetic for color ones). In 1.6 the semantic
+    of -DPNG_NO_READ_GAMMA is changed to simply disable any interface that
+    depends on it; this obliges people who set it to consider whether they
+    really want it off if they happen to use any of the interfaces in
+    question (typically most users who disable it won't).
+  Fixed GUIDs in projects/vstudio. Some were duplicated or missing,
+    resulting in VS2010 having to update the files.
+  Removed non-working ICC profile support code that was mostly added to
+    libpng-1.6.0beta29 and beta30. There was too much code for too little
+    gain; implementing full ICC color correction may be desireable but is left
+    up to applications.
+
+Version 1.6.0beta32 [November 25, 2012]
+  Fixed an intermittent SEGV in pngstest due to an uninitialized array element.
+  Added the ability for contrib/libtests/makepng.c to make a PNG with just one
+    color. This is useful for debugging pngstest color inaccuracy reports.
+  Fixed error checking in the simplified write API (Olaf van der Spek)
+  Made png_user_version_check() ok to use with libpng version 1.10.x and later.
+
+Version 1.6.0beta33 [December 15, 2012]
+  Fixed typo in png.c (PNG_SET_CHUNK_MALLOC_MAX should be PNG_CHUNK_MALLOC_MAX)
+    that causes the MALLOC_MAX limit not to work (John Bowler)
+  Change png_warning() to png_app_error() in pngwrite.c and comment the
+    fall-through condition.
+  Change png_warning() to png_app_warning() in png_write_tRNS().
+  Rearranged the ARM-NEON optimizations: Isolated the machine specific code
+    to the hardware subdirectory and added comments to pngrutil.c so that
+    implementors of other optimizations know what to do.
   Fixed cases of unquoted DESTDIR in Makefile.am
-  Fixed a minor bug in types to malloc and major bug in handling compressed
-    iTXt. Compressed iTXt could not be handled.
-
-Version 1.5.14beta04 [December 19, 2012]
+  Rebuilt Makefile.in, etc., with autoconf-2.69 and automake-1.12.5.
+
+Version 1.6.0beta34 [December 19, 2012]
   Cleaned up whitespace in the synopsis portion of the manpage "libpng.3"
   Disassembled the version number in scripts/options.awk (necessary for
     building on SunOs).
 
-Version 1.5.14beta05 [December 23, 2012]
+Version 1.6.0beta35 [December 23, 2012]
+  Made default Zlib compression settings be configurable. This adds #defines to
+    pnglibconf.h to control the defaults.
   Fixed Windows build issues, enabled ARM compilation. Various warnings issued
     by earlier versions of GCC fixed for Cygwin and Min/GW (which both use old
     GCCs.) ARM support is enabled by default in zlib.props (unsupported by
     Microsoft) and ARM compilation is made possible by deleting the check for
     x86. The test programs cannot be run because they are not signed.
 
-Version 1.5.14beta06 [January 1, 2013]
-  Discontinued distributing libpng-1.5.14-1.5.13-diff.txt and similar.
+Version 1.6.0beta36 [January 2, 2013]
+  Discontinued distributing libpng-1.x.x.tar.bz2.
+  Discontinued distributing libpng-1.7.0-1.6.0-diff.txt and similar.
+  Rebuilt configure with autoconf-2.69 (inadvertently not done in beta33)
   Fixed 'make distcheck' on SUN OS - libpng.so was not being removed
 
-Version 1.5.14beta07 [January 6, 2012]
-  Replaced AM_CONFIG_HEADER(config.h) with AC_CONFIG_HEADERS([config.h])
-    in configure.ac
-  De-configured build fixes to make a range of deconfiguration options (such
-    as switching off read or write support) work in more cases.  Also upgraded
-    pngtest and pngvalid to the libpng 1.6 versions (with some modifications)
-    which provide more extensive testing.  Replaced pngtest.png because pngtest
-    writes the ancillary chunks in a different order.
-
-Version 1.5.14beta08 [January 10, 2013]
-  Check validity of "num_unknowns" parameter of png_set_unknown_chunks()
-    (Bug report from yuris).
-
-Version 1.5.14rc01 [January 17, 2013]
+Version 1.6.0beta37 [January 10, 2013]
+  Fixed conceivable but difficult to repro overflow. Also added two test
+    programs to generate and test a PNG which should have the problem.
+
+Version 1.6.0beta39 [January 19, 2013]
+  Again corrected attempt at overflow detection in png_set_unknown_chunks().
+  Added overflow detection in png_set_sPLT() and png_set_text_2().
+
+Version 1.6.0beta40 [January 20, 2013]
+  Use consistent handling of overflows in text, sPLT and unknown png_set_* APIs
+
+Version 1.6.0rc01 [January 26, 2013]
   No changes.
 
-Version 1.5.14rc02 [January 17, 2013]
-  Revised test for validity of "num_unknowns" to eliminate compiler warnings.
-
-Version 1.5.14rc03 [January 18, 2013]
-  Check the validity of the "nentries" parameter of png_set_sPLT() and the
-  "num_text" parameter of png_set_text_2().
-
-Version 1.5.14 [January 24, 2013]
-  Removed an obsolete line from the manual.
-
-Version 1.5.15beta01 [February 4, 2013]
-  Enabled renaming of the extern (but not DLL exported) ARM filter functions.
-    Also enabled inclusion of pngpriv.h in non-C files by preventing C/C++
-    specific definitions if PNG_VERSION_INFO_ONLY is defined.
+Version 1.6.0rc02 [February 4, 2013]
   Added png_get_palette_max() function.
 
-Version 1.5.15beta02 [February 5, 2013]
-  Made a probably general fix for the preprocessing used to generate source
-    files. This change might make the check for a special C preprocessor
-    unnecessary, and it also eliminates the requirement for sed in the
-    configure build process.
-  Fix typo in Makefile.am, fix scripts/pnglibconf.mak and makefile.std
-  Rebuilt Makefile.in, configure, etc., with autoconf-2.69 and automake-1.13
-  Fix 'setting' handling in options.awk and fixed palette_max API
-
-Version 1.5.15beta03 [February 7, 2013]
-  Remove SUN OS cc -E workround - no longer required
+Version 1.6.0rc03 [February 5, 2013]
+  Fixed the png_get_palette_max API.
+
+Version 1.6.0rc04 [February 7, 2013]
   Turn serial tests back on (recently turned off by autotools upgrade).
 
-Version 1.5.15beta04 [February 15, 2013]
+Version 1.6.0rc05 [February 8, 2013]
+  Update manual about png_get_palette_max().
+
+Version 1.6.0rc06 [February 9, 2013]
+  Fixed missing dependency in --prefix builds The intermediate
+    internal 'prefix.h' file can only be generated correctly after
+    pnglibconf.h, however the dependency was not in Makefile.am.  The
+    symptoms are unpredictable depending on the order make chooses to
+    build pngprefix.h and pnglibconf.h, often the error goes unnoticed
+    because there is a system pnglibconf.h to use instead.
+
+Version 1.6.0rc07 [February 10, 2013]
   Enclosed the new png_get_palette_max in #ifdef PNG_GET_PALETTE_MAX_SUPPORTED
     block, and revised pnglibconf.h and pnglibconf.h.prebuilt accordingly.
 
-Version 1.5.15beta05 [February 17, 2013]
-  Use approved/supported Android method to check for NEON, use Linux/POSIX
-    1003.1 API to check /proc/self/auxv avoiding buffer allocation and other
-    library calls.
+Version 1.6.0rc08 [February 10, 2013]
+  Fix typo in png.h #ifdef
+
+Version 1.6.0 [February 14, 2013]
+  No changes.
+
+Version 1.6.1beta01 [February 16, 2013]
+  Made symbol prefixing work with the ARM neon optimizations. Also allow
+    pngpriv.h to be included for preprocessor definitions only, so it can
+    be used in non-C/C++ files. Back ported from libpng 1.7.
+  Made sRGB check numbers consistent.
+  Ported libpng 1.5 options.awk/dfn file handling to 1.6, fixed one bug.
+  Removed cc -E workround, corrected png_get_palette_max API Tested on
+    SUN OS cc 5.9, which demonstrates the tokenization problem previously
+    avoided by using /lib/cpp.  Since all .dfn output is now protected in
+    double quotes unless it is to be macro substituted the fix should
+    work everywhere.
+  Enabled parallel tests - back ported from libpng-1.7.
+  scripts/pnglibconf.dfa formatting improvements back ported from libpng17.
   Fixed a race condition in the creation of the build 'scripts' directory
     while building with a parallel make.
+  Use approved/supported Android method to check for NEON, use Linux/POSIX
+    1003.1 API to check /proc/self/auxv avoiding buffer allocation and other
+    library calls (ported from libpng15).
+
+Version 1.6.1beta02 [February 19, 2013]
   Use parentheses more consistently in "#if defined(MACRO)" tests.
-
-Version 1.5.15beta06 [February 22, 2013]
-  Fixed PNG_ALIGN(ED)_MEMORY and add ability to turn off ARM_NEON
-    runtime checks
+  Folded long lines.
+  Reenabled code to allow zero length PLTE chunks for MNG.
+
+Version 1.6.1beta03 [February 22, 2013]
+  Fixed ALIGNED_MEMORY support.
+  Allow run-time ARM NEON checking to be disabled. A new configure option:
+    --enable-arm-neon=always will stop the run-time checks. New checks
+    within arm/arm_init.c will cause the code not to be compiled unless
+    __ARM_NEON__ is set. This should make it fail safe (if someone asks
+    for it on then the build will fail if it can't be done.)
   Updated the INSTALL document.
 
-Version 1.5.15beta07 [February 27, 2013]
+Version 1.6.1beta04 [February 27, 2013]
   Revised INSTALL to recommend using CPPFLAGS instead of INCLUDES.
   Revised scripts/makefile.freebsd to respect ZLIBLIB and ZLIBINC.
   Revised scripts/dfn.awk to work with the buggy MSYS awk that has trouble
     with CRLF line endings.
 
-Version 1.5.15beta08 [March 5, 2013]
+Version 1.6.1beta05 [March 1, 2013]
   Avoid a possible memory leak in contrib/gregbook/readpng.c
-  Made the _SUPPORTED macro definitions consistent. The change made in
-    libpng15 to #define *_SUPPORTED 1, to match the use of -D*_SUPPORTED
-    (which means -D*_SUPPORTED=1) and avoid compiler warnings from GCC was made
-    inconsistently and causes problems as a result, also some additions in
-    pnglibconf.h.prebuilt were inconsistent (omitting the 1). This changes 1.5
-    back to the scheme used both before (1.4) and after (1.6). This might cause
-    some build scripts to issue warnings, and might, in the extreme, cause some
-    applications to fail (but they would fail anyway against 1.6).  It seems
-    safer to go for consistency, given the change in 1.6, not correctness here,
-    particularly as 'make check' currently warns anyway on the symbols.dfn check
-    because of the inconsistencies.
+
+Version 1.6.1beta06 [March 4, 2013]
+  Better documentation of unknown handling API interactions.
   Corrected Android builds and corrected libpng.vers with symbol
     prefixing This adds an API to set optimization options externally,
     providing an alternative and general solution for the non-portable
     run-time tests used by the ARM Neon code.  It also makes those tests
     compile and link on Android.
   The order of settings vs options in pnglibconf.h is reversed to allow
     settings to depend on options and options can now set (or override) the
     defaults for settings.
 
-Version 1.5.15beta09 [March 13, 2013]
+Version 1.6.1beta07 [March 7, 2013]
+  Corrected simplified API default gamma for color-mapped output, added
+    a flag to change default. In 1.6.0 when the simplified API was used
+    to produce color-mapped output from an input image with no gamma
+    information the gamma assumed for the input could be different from
+    that assumed for non-color-mapped output.  In particular 16-bit depth
+    input files were assumed to be sRGB encoded, whereas in the 'direct'
+    case they were assumed to have linear data.  This was an error.  The
+    fix makes the simplified API treat all input files the same way and
+    adds a new flag to the png_image::flags member to allow the
+    application/user to specify that 16-bit files contain sRGB data
+    rather than the default linear.
+  Fixed bugs in the pngpixel and makepng test programs.
+
+Version 1.6.1beta08 [March 7, 2013]
   Fixed CMakelists.txt to allow building a single variant of the library
     (Claudio Bley):
   Introduced a PNG_LIB_TARGETS variable that lists all activated library
     targets.  It is an error if this variable ends up empty, ie. you have
     to build at least one library variant.
   Made the *_COPY targets only depend on library targets actually being build.
   Use PNG_LIB_TARGETS to unify a code path.
   Changed the CREATE_SYMLINK macro to expect the full path to a file as the
     first argument. When symlinking the filename component of that path is
     determined and used as the link target.
   Use copy_if_different in the CREATE_SYMLINK macro.
+
+Version 1.6.1beta09 [March 13, 2013]
   Eliminated two warnings from the Intel C compiler. The warnings are
     technically valid, although a reasonable treatment of division would
     show it to be incorrect.
 
-Version 1.5.15rc01 [March 21, 2013]
+Version 1.6.1rc01 [March 21, 2013]
+  No changes.
+
+Version 1.6.1 [March 28, 2013]
   No changes.
 
-Version 1.5.15 [March 28, 2013]
-  No changes.
-
-Version 1.5.16beta01 [April 25, 2013]
+Version 1.6.2beta01 [April 14, 2013]
+  Updated documentation of 1.5.x to 1.6.x changes in iCCP chunk handling.
+  Fixed incorrect warning of excess deflate data. End condition - the
+    warning would be produced if the end of the deflate stream wasn't read
+    in the last row.  The warning is harmless.
+  Corrected the test on user transform changes on read. It was in the
+    png_set of the transform function, but that doesn't matter unless the
+    transform function changes the rowbuf size, and that is only valid if
+    transform_info is called.
   Corrected a misplaced closing bracket in contrib/libtests/pngvalid.c
     (Flavio Medeiros).
+  Corrected length written to uncompressed iTXt chunks (Samuli Suominen).
+    Bug was introduced in libpng-1.6.0.
+
+Version 1.6.2rc01 [April 18, 2013]
+  Added contrib/tools/fixitxt.c, to repair the erroneous iTXt chunk length
+    written by libpng-1.6.0 and 1.6.1.
+  Disallow storing sRGB information when the sRGB is not supported.
+
+Version 1.6.2rc02 [April 18, 2013]
+  Merge pngtest.c with libpng-1.7.0
+
+Version 1.6.2rc03 [April 22, 2013]
+  Trivial spelling cleanup.
+
+Version 1.6.2rc04 and 1.6.2rc05 [omitted]
+
+Version 1.6.2rc06 [April 24, 2013]
+  Reverted to version 1.6.2rc03.  Recent changes to arm/neon support
+    have been ported to libpng-1.7.0beta09 and will reappear in version
+    1.6.3beta01.
+
+Version 1.6.2 [April 25, 2013]
+  No changes.
+
+Version 1.6.3beta01 [April 25, 2013]
   Revised stack marking in arm/filter_neon.S and configure.ac.
   Ensure that NEON filter stuff is completely disabled when switched 'off'.
     Previously the ARM NEON specific files were still built if the option
     was switched 'off' as opposed to being explicitly disabled.
-  Avoid a compiler warning about unused png_ptr in translate_gamma_flags()
-
-Version 1.5.16beta02 [April 26, 2013]
-  Revise pngtest.c to skip tests of unsupported features.
-  Regenerated configure files.
-
-Version 1.5.16beta03 [April 26, 2013]
+
+Version 1.6.3beta02 [April 26, 2013]
   Test for 'arm*' not just 'arm' in the host_cpu configure variable.
-
-Version 1.5.16beta04 [May 1, 2013]
+  Rebuilt the configure scripts.
+
+Version 1.6.3beta03 [April 30, 2013]
   Expanded manual paragraph about writing private chunks, particularly
     the need to call png_set_keep_unknown_chunks() when writing them.
-
-Version 1.5.16beta05 [May 9, 2013]
+  Avoid dereferencing NULL pointer possibly returned from
+     png_create_write_struct() (Andrew Church).
+
+Version 1.6.3beta05 [May 9, 2013]
+  Calculate our own zlib windowBits when decoding rather than trusting the
+    CMF bytes in the PNG datastream.
+  Added an option to force maximum window size for inflating, which was
+    the behavior of libpng15 and earlier.
+  Added png-fix-itxt and png-fix-too-far-back to the built programs and
+    removed warnings from the source code and timepng that are revealed as
+    a result.
+  Detect wrong libpng versions linked to png-fix-too-far-back, which currently
+    only works with libpng versions that can be made to reliably fail when
+    the deflate data contains an out-of-window reference.  This means only
+    1.6 and later.
+  Fixed gnu issues: g++ needs a static_cast, gcc 4.4.7 has a broken warning
+    message which it is easier to work round than ignore.
   Updated contrib/pngminus/pnm2png.c (Paul Stewart):
     Check for EOF
     Ignore "#" delimited comments in input file to pnm2png.c.
     Fixed whitespace handling
     Added a call to png_set_packing()
     Initialize dimension values so if sscanf fails at least we have known
       invalid values.
-
-Version 1.5.16beta06 [May 12, 2013]
-  Allow contrib/pnminus/pnm2png.c to compile without WRITE_INVERT and WRITE_PACK
-    supported (writes error message that it can't read P1 or P4 PBM files).
-  Revised contrib/pngminim/*/makefile to separate CPPFLAGS and CFLAGS, and
-    to generate pnglibconf.h with the right zlib header files.
-  Ported contrib/pngminus/pnm2png.c changes back from libpng-1.6.3beta06,
-    to use unsigned long, not png_uint_32 arguments to sscanf().
-
-Version 1.5.16rc01 [May 16, 2013]
-  No changes.
-
-Version 1.5.16 [May 23, 2013]
-  No changes.
-
-Version 1.5.17beta01 [June 8, 2013]
-  Removed a redundant test from png_set_IHDR().
+  Attempt to detect configuration issues with png-fix-too-far-back, which
+    requires both the correct libpng and the correct zlib to function
+    correctly.
+  Check ZLIB_VERNUM for mismatches, enclose #error in quotes
+  Added information in the documentation about problems with and fixes for
+    the bad CRC and bad iTXt chunk situations.
+
+Version 1.6.3beta06 [May 12, 2013]
+  Allow contrib/pngminus/pnm2png.c to compile without WRITE_INVERT and
+    WRITE_PACK supported (writes error message that it can't read P1 or
+    P4 PBM files).
+  Improved png-fix-too-far-back usage message, added --suffix option.
+  Revised contrib/pngminim/*/makefile to generate pnglibconf.h with the
+    right zlib header files.
+  Separated CPPFLAGS and CFLAGS in contrib/pngminim/*/makefile
+
+Version 1.6.3beta07 [June 8, 2013]
+  Removed a redundant test in png_set_IHDR().
   Added set(CMAKE_CONFIGURATION_TYPES ...) to CMakeLists.txt (Andrew Hundt)
   Deleted set(CMAKE_BUILD_TYPE) block from CMakeLists.txt
+  Enclose the prototypes for the simplified write API in
+    #ifdef PNG_STDIO_SUPPORTED/#endif
   Make ARM NEON support work at compile time (not just configure time).
     This moves the test on __ARM_NEON__ into pngconf.h to avoid issues when
     using a compiler that compiles for multiple architectures at one time.
   Removed PNG_FILTER_OPTIMIZATIONS and PNG_ARM_NEON_SUPPORTED from
     pnglibconf.h, allowing more of the decisions to be made internally
     (pngpriv.h) during the compile.  Without this, symbol prefixing is broken
     under certain circumstances on ARM platforms.  Now only the API parts of
     the optimizations ('check' vs 'api') are exposed in the public header files
@@ -4131,30 +4583,68 @@ Version 1.5.17beta01 [June 8, 2013]
     Previous iOS/Xcode fixes for the ARM NEON optimizations moved the test
     on __ARM_NEON__ from configure time to compile time.  This breaks symbol
     prefixing because the definition of the special png_init_filter_functions
     call was hidden at configure time if the relevant compiler arguments are
     passed in CFLAGS as opposed to CC.  This change attempts to avoid all
     the confusion that would result by declaring the init function even when
     it is not used, so that it will always get prefixed.
 
-Version 1.5.17rc01 [June 17, 2013]
-  No changes.
-
-Version 1.5.17rc02 [June 18, 2013]
+Version 1.6.3beta08 [June 18, 2013]
   Revised libpng.3 so that "doclifter" can process it.
 
-Version 1.5.17rc03 [June 25, 2013]
+Version 1.6.3beta09 [June 27, 2013]
   Revised example.c to illustrate use of PNG_DEFAULT_sRGB and PNG_GAMMA_MAC_18
     as parameters for png_set_gamma().  These have been available since
     libpng-1.5.4.
-
-Version 1.5.17 [June 27, 2013]
+  Renamed contrib/tools/png-fix-too-far-back.c to pngfix.c and revised it
+    to check all compressed chunks known to libpng.
+
+Version 1.6.3beta10 [July 5, 2013]
+  Updated documentation to show default behavior of benign errors correctly.
+  Only compile ARM code when PNG_READ_SUPPORTED is defined.
+  Fixed undefined behavior in contrib/tools/pngfix.c and added new strip
+    option. pngfix relied on undefined behavior and even a simple change from
+    gcc to g++ caused it to fail.  The new strip option 'unsafe' has been
+    implemented and is the default if --max is given.  Option names have
+    been clarified, with --strip=transform now stripping the bKGD chunk,
+    which was stripped previously with --strip=unused.
+  Added all documented chunk types to pngpriv.h
+  Unified pngfix.c source with libpng17.
+
+Version 1.6.3rc01 [July 11, 2013]
   No changes.
 
+Version 1.6.3 [July 18, 2013]
+  Revised manual about changes in iTXt chunk handling made in libpng-1.6.0.
+  Added "/* SAFE */" comments in pngrutil.c and pngrtran.c where warnings
+    may be erroneously issued by code-checking applications.
+
+Version 1.6.4beta01 [August 21, 2013]
+  Added information about png_set_options() to the manual.
+  Delay calling png_init_filter_functions() until a row with nonzero filter
+    is found.
+
+Version 1.6.4beta02 [August 30, 2013]
+  Fixed inconsistent conditional compilation of png_chunk_unknown_handling()
+    prototype, definition, and usage.  Made it depend on
+    PNG_HANDLE_AS_UNKNOWN_SUPPORTED everywhere.
+
+Version 1.6.4rc01 [September 5, 2013]
+  No changes.
+
+Version 1.6.4 [September 12, 2013]
+  No changes.
+
+Version 1.6.5 [September 14, 2013]
+  Removed two stray lines of code from arm/arm_init.c.
+
+Version 1.6.6beta01 [September 16, 2013]
+  Removed two stray lines of code from arm/arm_init.c, again.
+
 Send comments/corrections/commendations to png-mng-implement at lists.sf.net
 (subscription required; visit
 https://lists.sourceforge.net/lists/listinfo/png-mng-implement
 to subscribe)
 or to glennrp at users.sourceforge.net
 
 Glenn R-P
 #endif
--- a/media/libpng/LICENSE
+++ b/media/libpng/LICENSE
@@ -5,18 +5,18 @@ included in the libpng distribution, the
 
 COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
 
 If you modify libpng you may insert additional notices immediately following
 this sentence.
 
 This code is released under the libpng license.
 
-libpng versions 1.2.6, August 15, 2004, through 1.5.17, June 27, 2013, are
-Copyright (c) 2004, 2006-2012 Glenn Randers-Pehrson, and are
+libpng versions 1.2.6, August 15, 2004, through 1.6.6, September 16, 2013, are
+Copyright (c) 2004, 2006-2013 Glenn Randers-Pehrson, and are
 distributed according to the same disclaimer and license as libpng-1.2.5
 with the following individual added to the list of Contributing Authors
 
    Cosmin Truta
 
 libpng versions 1.0.7, July 1, 2000, through 1.2.5 - October 3, 2002, are
 Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
 distributed according to the same disclaimer and license as libpng-1.0.6
@@ -103,9 +103,9 @@ boxes and the like:
 Also, the PNG logo (in PNG format, of course) is supplied in the
 files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
 
 Libpng is OSI Certified Open Source Software.  OSI Certified Open Source is a
 certification mark of the Open Source Initiative.
 
 Glenn Randers-Pehrson
 glennrp at users.sourceforge.net
-June 27, 2013
+September 16, 2013
--- a/media/libpng/MOZCHANGES
+++ b/media/libpng/MOZCHANGES
@@ -1,11 +1,13 @@
 
 Changes made to pristine png source by mozilla.org developers.
 
+2013/09/21  -- Synced with libpng-1.6.6 (bug #886499).
+
 2013/07/17  -- Synced with libpng-1.5.17 (bug #886499).
 
 2013/06/06  -- Synced with libpng-1.5.16 (bug #873001).
 
 2013/04/11  -- Synced with libpng-1.5.15 (bug #858578).
 
 2013/01/24  -- Synced with libpng-1.5.14 (bug #832487).
 
--- a/media/libpng/README
+++ b/media/libpng/README
@@ -1,17 +1,16 @@
-README for libpng version 1.5.17 - June 27, 2013 (shared library 15.0)
+README for libpng version 1.6.6 - September 16, 2013 (shared library 16.0)
 See the note about version numbers near the top of png.h
 
 See INSTALL for instructions on how to install libpng.
 
-Libpng comes in several distribution formats.  Get libpng-*.tar.gz,
-libpng-*.tar.xz or libpng-*.tar.bz2 if you want UNIX-style line endings
-in the text files, or lpng*.7z or lpng*.zip if you want DOS-style line
-endings.
+Libpng comes in several distribution formats.  Get libpng-*.tar.gz or
+libpng-*.tar.xz or if you want UNIX-style line endings in the text files,
+or lpng*.7z or lpng*.zip if you want DOS-style line endings.
 
 Version 0.89 was the first official release of libpng.  Don't let the
 fact that it's the first release fool you.  The libpng library has been in
 extensive use and testing since mid-1995.  By late 1997 it had
 finally gotten to the stage where there hadn't been significant
 changes to the API in some time, and people have a bad feeling about
 libraries with versions < 1.0.  Version 1.0.0 was released in
 March 1998.
@@ -163,25 +162,27 @@ Files in this distribution:
       pngtest.png   =>  Library test sample image
       pngtrans.c    =>  Common data transformation functions
       pngwio.c      =>  Lowest-level write I/O functions
       pngwrite.c    =>  High-level write functions
       pngwtran.c    =>  Write data transformations
       pngwutil.c    =>  Write utility functions
       arm           =>  Contains optimized code for the ARM platform
       contrib       =>  Contributions
+       examples         =>  Example programs
        gregbook         =>  source code for PNG reading and writing, from
                             Greg Roelofs' "PNG: The Definitive Guide",
                             O'Reilly, 1999
-       libtests         =>  Contains the pngvalid.c test program
+       libtests         =>  Test programs
        pngminim         =>  Minimal decoder, encoder, and progressive decoder
                             programs demonstrating use of pngusr.dfa
        pngminus         =>  Simple pnm2png and png2pnm programs
        pngsuite         =>  Test images
-       visupng          =>  Contains a MSVC workspace for VisualPng
+       tools            =>  Various tools
+       visupng      =>  Contains a MSVC workspace for VisualPng
       projects      =>  Contains project files and workspaces for
                         building a DLL
        owatcom          =>  Contains a WATCOM project for building libpng
        visualc71        =>  Contains a Microsoft Visual C++ (MSVC)
                             workspace for building libpng and zlib
        vstudio          =>  Contains a Microsoft Visual C++ (MSVC)
                             workspace for building libpng and zlib
       scripts       =>  Directory containing scripts for building libpng:
--- a/media/libpng/apng.patch
+++ b/media/libpng/apng.patch
@@ -1,40 +1,41 @@
 Index: pngread.c
 ===================================================================
 --- pngread.c
 +++ pngread.c
-@@ -240,6 +240,9 @@
-              !(png_ptr->mode & PNG_HAVE_PLTE))
-             png_error(png_ptr, "Missing PLTE before IDAT");
+@@ -158,6 +158,9 @@
  
+       else if (chunk_name == png_IDAT)
+       {
 +#ifdef PNG_READ_APNG_SUPPORTED
 +         png_have_info(png_ptr, info_ptr);
 +#endif
           png_ptr->idat_size = length;
-          png_ptr->mode |= PNG_HAVE_IDAT;
           break;
-@@ -330,12 +333,91 @@
+       }
+@@ -247,6 +250,17 @@
           png_handle_iTXt(png_ptr, info_ptr, length);
  #endif
  
 +#ifdef PNG_READ_APNG_SUPPORTED
 +      else if (chunk_name == png_acTL)
 +         png_handle_acTL(png_ptr, info_ptr, length);
 +
 +      else if (chunk_name == png_fcTL)
 +         png_handle_fcTL(png_ptr, info_ptr, length);
 +
 +      else if (chunk_name == png_fdAT)
 +         png_handle_fdAT(png_ptr, info_ptr, length);
 +#endif
 +
        else
-          png_handle_unknown(png_ptr, info_ptr, length);
-    }
+          png_handle_unknown(png_ptr, info_ptr, length,
+             PNG_HANDLE_CHUNK_AS_DEFAULT);
+@@ -254,6 +268,72 @@
  }
  #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */
  
 +#ifdef PNG_READ_APNG_SUPPORTED
 +void PNGAPI
 +png_read_frame_head(png_structp png_ptr, png_infop info_ptr)
 +{
 +    png_byte have_chunk_after_DAT; /* after IDAT or after fdAT */
@@ -44,18 +45,16 @@ Index: pngread.c
 +    if (!(png_ptr->mode & PNG_HAVE_acTL))
 +        png_error(png_ptr, "attempt to png_read_frame_head() but "
 +                           "no acTL present");
 +
 +    /* do nothing for the main IDAT */
 +    if (png_ptr->num_frames_read == 0)
 +        return;
 +
-+    png_crc_finish(png_ptr, 0); /* CRC from last IDAT or fdAT chunk */
-+
 +    png_read_reset(png_ptr);
 +    png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
 +    png_ptr->mode &= ~PNG_HAVE_fcTL;
 +
 +    have_chunk_after_DAT = 0;
 +    for (;;)
 +    {
 +        png_uint_32 length = png_read_chunk_header(png_ptr);
@@ -98,79 +97,22 @@ Index: pngread.c
 +            png_crc_finish(png_ptr, length);
 +        }
 +    }
 +}
 +#endif /* PNG_READ_APNG_SUPPORTED */
 +
  /* Optional call to update the users info_ptr structure */
  void PNGAPI
- png_read_update_info(png_structp png_ptr, png_infop info_ptr)
-@@ -537,6 +619,38 @@
-    {
-       if (!(png_ptr->zstream.avail_in))
-       {
-+#ifdef PNG_READ_APNG_SUPPORTED
-+         png_uint_32 bytes_to_skip = 0;
-+
-+         while (!png_ptr->idat_size || bytes_to_skip != 0)
-+         {
-+            png_crc_finish(png_ptr, bytes_to_skip);
-+            bytes_to_skip = 0;
-+
-+            png_ptr->idat_size = png_read_chunk_header(png_ptr);
-+            if (png_ptr->num_frames_read == 0)
-+            {
-+               if (png_ptr->chunk_name != png_IDAT)
-+                  png_error(png_ptr, "Not enough image data");
-+            }
-+            else
-+            {
-+               if (png_ptr->chunk_name == png_IEND)
-+                  png_error(png_ptr, "Not enough image data");
-+               if (png_ptr->chunk_name != png_fdAT)
-+               {
-+                  png_warning(png_ptr, "Skipped (ignored) a chunk "
-+                                       "between APNG chunks");
-+                  bytes_to_skip = png_ptr->idat_size;
-+                  continue;
-+               }
-+
-+               png_ensure_sequence_number(png_ptr, png_ptr->idat_size);
-+
-+               png_ptr->idat_size -= 4;
-+            }
-+         }
-+#else
-          while (!png_ptr->idat_size)
-          {
-             png_crc_finish(png_ptr, 0);
-@@ -545,6 +659,7 @@
-             if (png_ptr->chunk_name != png_IDAT)
-                png_error(png_ptr, "Not enough image data");
-          }
-+#endif
-          png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
-          png_ptr->zstream.next_in = png_ptr->zbuf;
-          if (png_ptr->zbuf_size > png_ptr->idat_size)
-@@ -563,6 +678,9 @@
-             png_benign_error(png_ptr, "Extra compressed data");
-          png_ptr->mode |= PNG_AFTER_IDAT;
-          png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
-+#ifdef PNG_READ_APNG_SUPPORTED
-+         png_ptr->num_frames_read++;
-+#endif
-          break;
-       }
- 
+ png_read_update_info(png_structrp png_ptr, png_inforp info_ptr)
 Index: pngget.c
 ===================================================================
 --- pngget.c
 +++ pngget.c
-@@ -1140,4 +1140,167 @@
+@@ -1174,4 +1174,166 @@
  #  endif
  #endif
  
 +#ifdef PNG_APNG_SUPPORTED
 +png_uint_32 PNGAPI
 +png_get_acTL(png_structp png_ptr, png_infop info_ptr,
 +             png_uint_32 *num_frames, png_uint_32 *num_plays)
 +{
@@ -326,34 +268,33 @@ Index: pngget.c
 +    if (png_ptr != NULL)
 +       return (png_byte)(png_ptr->apng_flags & PNG_FIRST_FRAME_HIDDEN);
 +
 +    PNG_UNUSED(info_ptr)
 +
 +    return 0;
 +}
 +#endif /* PNG_APNG_SUPPORTED */
-+
  #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
 Index: png.h
 ===================================================================
 --- png.h
 +++ png.h
-@@ -454,6 +454,10 @@
+@@ -443,6 +443,10 @@
  #   include "pnglibconf.h"
  #endif
  
 +#define PNG_APNG_SUPPORTED
 +#define PNG_READ_APNG_SUPPORTED
 +#define PNG_WRITE_APNG_SUPPORTED
 +
  #ifndef PNG_VERSION_INFO_ONLY
- #  ifndef PNG_BUILDING_SYMBOL_TABLE
-   /*
-@@ -561,6 +565,17 @@
+    /* Machine specific configuration. */
+ #  include "pngconf.h"
+@@ -533,6 +537,17 @@
   * See pngconf.h for base types that vary by machine/system
   */
  
 +#ifdef PNG_APNG_SUPPORTED
 +/* dispose_op flags from inside fcTL */
 +#define PNG_DISPOSE_OP_NONE        0x00
 +#define PNG_DISPOSE_OP_BACKGROUND  0x01
 +#define PNG_DISPOSE_OP_PREVIOUS    0x02
@@ -361,17 +302,17 @@ Index: png.h
 +/* blend_op flags from inside fcTL */
 +#define PNG_BLEND_OP_SOURCE        0x00
 +#define PNG_BLEND_OP_OVER          0x01
 +#endif /* PNG_APNG_SUPPORTED */
 +
  /* This triggers a compiler error in png.c, if png.c and png.h
   * do not agree upon the version number.
   */
-@@ -844,6 +859,10 @@
+@@ -852,6 +867,10 @@
  #define PNG_INFO_sPLT 0x2000   /* ESR, 1.0.6 */
  #define PNG_INFO_sCAL 0x4000   /* ESR, 1.0.6 */
  #define PNG_INFO_IDAT 0x8000   /* ESR, 1.0.6 */
 +#ifdef PNG_APNG_SUPPORTED
 +#define PNG_INFO_acTL 0x10000
 +#define PNG_INFO_fcTL 0x20000
 +#endif
  
@@ -383,187 +324,191 @@ Index: png.h
  typedef PNG_CALLBACK(void, *png_progressive_end_ptr, (png_structp, png_infop));
 +#ifdef PNG_APNG_SUPPORTED
 +typedef PNG_CALLBACK(void, *png_progressive_frame_ptr, (png_structp,
 +    png_uint_32));
 +#endif
  
  /* The following callback receives png_uint_32 row_number, int pass for the
   * png_bytep data of the row.  When transforming an interlaced image the
-@@ -2709,6 +2732,75 @@
+@@ -3292,6 +3315,75 @@
   *  END OF HARDWARE OPTIONS
   ******************************************************************************/
  
 +#ifdef PNG_APNG_SUPPORTED
-+PNG_EXPORT(237, png_uint_32, png_get_acTL, (png_structp png_ptr,
++PNG_EXPORT(245, png_uint_32, png_get_acTL, (png_structp png_ptr,
 +   png_infop info_ptr, png_uint_32 *num_frames, png_uint_32 *num_plays));
 +
-+PNG_EXPORT(238, png_uint_32, png_set_acTL, (png_structp png_ptr,
++PNG_EXPORT(246, png_uint_32, png_set_acTL, (png_structp png_ptr,
 +   png_infop info_ptr, png_uint_32 num_frames, png_uint_32 num_plays));
 +
-+PNG_EXPORT(239, png_uint_32, png_get_num_frames, (png_structp png_ptr,
++PNG_EXPORT(247, png_uint_32, png_get_num_frames, (png_structp png_ptr,
 +   png_infop info_ptr));
 +
-+PNG_EXPORT(240, png_uint_32, png_get_num_plays, (png_structp png_ptr,
++PNG_EXPORT(248, png_uint_32, png_get_num_plays, (png_structp png_ptr,
 +   png_infop info_ptr));
 +
-+PNG_EXPORT(241, png_uint_32, png_get_next_frame_fcTL,
++PNG_EXPORT(249, png_uint_32, png_get_next_frame_fcTL,
 +   (png_structp png_ptr, png_infop info_ptr, png_uint_32 *width,
 +   png_uint_32 *height, png_uint_32 *x_offset, png_uint_32 *y_offset,
 +   png_uint_16 *delay_num, png_uint_16 *delay_den, png_byte *dispose_op,
 +   png_byte *blend_op));
 +
-+PNG_EXPORT(242, png_uint_32, png_set_next_frame_fcTL,
++PNG_EXPORT(250, png_uint_32, png_set_next_frame_fcTL,
 +   (png_structp png_ptr, png_infop info_ptr, png_uint_32 width,
 +   png_uint_32 height, png_uint_32 x_offset, png_uint_32 y_offset,
 +   png_uint_16 delay_num, png_uint_16 delay_den, png_byte dispose_op,
 +   png_byte blend_op));
 +
-+PNG_EXPORT(243, png_uint_32, png_get_next_frame_width,
++PNG_EXPORT(251, png_uint_32, png_get_next_frame_width,
 +   (png_structp png_ptr, png_infop info_ptr));
-+PNG_EXPORT(244, png_uint_32, png_get_next_frame_height,
++PNG_EXPORT(252, png_uint_32, png_get_next_frame_height,
 +   (png_structp png_ptr, png_infop info_ptr));
-+PNG_EXPORT(245, png_uint_32, png_get_next_frame_x_offset,
++PNG_EXPORT(253, png_uint_32, png_get_next_frame_x_offset,
 +   (png_structp png_ptr, png_infop info_ptr));
-+PNG_EXPORT(246, png_uint_32, png_get_next_frame_y_offset,
++PNG_EXPORT(254, png_uint_32, png_get_next_frame_y_offset,
 +   (png_structp png_ptr, png_infop info_ptr));
-+PNG_EXPORT(247, png_uint_16, png_get_next_frame_delay_num,
++PNG_EXPORT(255, png_uint_16, png_get_next_frame_delay_num,
 +   (png_structp png_ptr, png_infop info_ptr));
-+PNG_EXPORT(248, png_uint_16, png_get_next_frame_delay_den,
++PNG_EXPORT(256, png_uint_16, png_get_next_frame_delay_den,
 +   (png_structp png_ptr, png_infop info_ptr));
-+PNG_EXPORT(249, png_byte, png_get_next_frame_dispose_op,
++PNG_EXPORT(257, png_byte, png_get_next_frame_dispose_op,
 +   (png_structp png_ptr, png_infop info_ptr));
-+PNG_EXPORT(250, png_byte, png_get_next_frame_blend_op,
++PNG_EXPORT(258, png_byte, png_get_next_frame_blend_op,
 +   (png_structp png_ptr, png_infop info_ptr));
-+PNG_EXPORT(251, png_byte, png_get_first_frame_is_hidden,
++PNG_EXPORT(259, png_byte, png_get_first_frame_is_hidden,
 +   (png_structp png_ptr, png_infop info_ptr));
-+PNG_EXPORT(252, png_uint_32, png_set_first_frame_is_hidden,
++PNG_EXPORT(260, png_uint_32, png_set_first_frame_is_hidden,
 +   (png_structp png_ptr, png_infop info_ptr, png_byte is_hidden));
 +
 +#ifdef PNG_READ_APNG_SUPPORTED
-+PNG_EXPORT(253, void, png_read_frame_head, (png_structp png_ptr,
++PNG_EXPORT(261, void, png_read_frame_head, (png_structp png_ptr,
 +   png_infop info_ptr));
 +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
-+PNG_EXPORT(254, void, png_set_progressive_frame_fn, (png_structp png_ptr,
++PNG_EXPORT(262, void, png_set_progressive_frame_fn, (png_structp png_ptr,
 +   png_progressive_frame_ptr frame_info_fn,
 +   png_progressive_frame_ptr frame_end_fn));
 +#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
 +#endif /* PNG_READ_APNG_SUPPORTED */
 +
 +#ifdef PNG_WRITE_APNG_SUPPORTED
-+PNG_EXPORT(255, void, png_write_frame_head, (png_structp png_ptr,
++PNG_EXPORT(263, void, png_write_frame_head, (png_structp png_ptr,
 +   png_infop info_ptr, png_bytepp row_pointers,
 +   png_uint_32 width, png_uint_32 height,
 +   png_uint_32 x_offset, png_uint_32 y_offset,
 +   png_uint_16 delay_num, png_uint_16 delay_den, png_byte dispose_op,
 +   png_byte blend_op));
 +
-+PNG_EXPORT(256, void, png_write_frame_tail, (png_structp png_ptr,
++PNG_EXPORT(264, void, png_write_frame_tail, (png_structp png_ptr,
 +   png_infop info_ptr));
 +#endif /* PNG_WRITE_APNG_SUPPORTED */
 +#endif /* PNG_APNG_SUPPORTED */
 +
  /* Maintainer: Put new public prototypes here ^, in libpng.3, and project
-  * defs
+  * defs, scripts/pnglibconf.h, and scripts/pnglibconf.h.prebuilt
   */
-@@ -2718,7 +2810,11 @@
+@@ -3301,7 +3393,11 @@
   * scripts/symbols.def as well.
   */
  #ifdef PNG_EXPORT_LAST_ORDINAL
 +#ifdef PNG_APNG_SUPPORTED
-+  PNG_EXPORT_LAST_ORDINAL(256);
++  PNG_EXPORT_LAST_ORDINAL(264);
 +#else
-   PNG_EXPORT_LAST_ORDINAL(236);
+   PNG_EXPORT_LAST_ORDINAL(244);
 +#endif /* PNG_APNG_SUPPORTED */
  #endif
  
  #ifdef __cplusplus
 Index: pngpriv.h
 ===================================================================
 --- pngpriv.h
 +++ pngpriv.h
-@@ -501,6 +501,10 @@
- #define PNG_HAVE_PNG_SIGNATURE    0x1000
+@@ -502,6 +502,10 @@
  #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
- #define PNG_HAVE_iCCP             0x4000
+                    /*             0x4000 (unused) */
+ #define PNG_IS_READ_STRUCT        0x8000 /* Else is a write struct */
 +#ifdef PNG_APNG_SUPPORTED
-+#define PNG_HAVE_acTL             0x8000
-+#define PNG_HAVE_fcTL            0x10000
++#define PNG_HAVE_acTL            0x10000
++#define PNG_HAVE_fcTL            0x20000
 +#endif
  
  /* Flags for the transformations the PNG library does on the image data */
  #define PNG_BGR                 0x0001
-@@ -698,6 +702,16 @@
- #define png_tRNS PNG_CHUNK(116,  82,  78,  83)
- #define png_zTXt PNG_CHUNK(122,  84,  88, 116)
+@@ -723,6 +727,16 @@
+ #define png_tRNS PNG_U32(116,  82,  78,  83)
+ #define png_zTXt PNG_U32(122,  84,  88, 116)
  
 +#ifdef PNG_APNG_SUPPORTED
-+#define png_acTL PNG_CHUNK( 97,  99,  84,  76)
-+#define png_fcTL PNG_CHUNK(102,  99,  84,  76)
-+#define png_fdAT PNG_CHUNK(102, 100,  65,  84)
++#define png_acTL PNG_U32( 97,  99,  84,  76)
++#define png_fcTL PNG_U32(102,  99,  84,  76)
++#define png_fdAT PNG_U32(102, 100,  65,  84)
 +
 +/* For png_struct.apng_flags: */
 +#define PNG_FIRST_FRAME_HIDDEN       0x0001
 +#define PNG_APNG_APP                 0x0002
 +#endif
 +
  /* The following will work on (signed char*) strings, whereas the get_uint_32
   * macro will fail on top-bit-set values because of the sign extension.
   */
-@@ -1389,6 +1403,45 @@
-     png_bytep row));
+@@ -1516,6 +1530,49 @@
+     png_bytep row),PNG_EMPTY);
  #endif
  
 +#ifdef PNG_APNG_SUPPORTED
-+PNG_EXTERN void png_ensure_fcTL_is_valid PNGARG((png_structp png_ptr,
++PNG_INTERNAL_FUNCTION(void,png_ensure_fcTL_is_valid,(png_structp png_ptr,
 +   png_uint_32 width, png_uint_32 height,
 +   png_uint_32 x_offset, png_uint_32 y_offset,
 +   png_uint_16 delay_num, png_uint_16 delay_den,
-+   png_byte dispose_op, png_byte blend_op));
++   png_byte dispose_op, png_byte blend_op),PNG_EMPTY);
 +
 +#ifdef PNG_READ_APNG_SUPPORTED
-+PNG_EXTERN void png_handle_acTL PNGARG((png_structp png_ptr, png_infop info_ptr,
-+   png_uint_32 length));
-+PNG_EXTERN void png_handle_fcTL PNGARG((png_structp png_ptr, png_infop info_ptr,
-+   png_uint_32 length));
-+PNG_EXTERN void png_handle_fdAT PNGARG((png_structp png_ptr, png_infop info_ptr,
-+   png_uint_32 length));
-+PNG_EXTERN void png_have_info PNGARG((png_structp png_ptr, png_infop info_ptr));
-+PNG_EXTERN void png_ensure_sequence_number PNGARG((png_structp png_ptr,
-+   png_uint_32 length));
-+PNG_EXTERN void png_read_reset PNGARG((png_structp png_ptr));
-+PNG_EXTERN void png_read_reinit PNGARG((png_structp png_ptr,
-+   png_infop info_ptr));
++PNG_INTERNAL_FUNCTION(void,png_handle_acTL,(png_structp png_ptr,
++   png_infop info_ptr, png_uint_32 length),PNG_EMPTY);
++PNG_INTERNAL_FUNCTION(void,png_handle_fcTL,(png_structp png_ptr,
++   png_infop info_ptr, png_uint_32 length),PNG_EMPTY);
++PNG_INTERNAL_FUNCTION(void,png_handle_fdAT,(png_structp png_ptr,
++   png_infop info_ptr, png_uint_32 length),PNG_EMPTY);
++PNG_INTERNAL_FUNCTION(void,png_have_info,(png_structp png_ptr,
++   png_infop info_ptr),PNG_EMPTY);
++PNG_INTERNAL_FUNCTION(void,png_ensure_sequence_number,(png_structp png_ptr,
++   png_uint_32 length),PNG_EMPTY);
++PNG_INTERNAL_FUNCTION(void,png_read_reset,(png_structp png_ptr),PNG_EMPTY);
++PNG_INTERNAL_FUNCTION(void,png_read_reinit,(png_structp png_ptr,
++   png_infop info_ptr),PNG_EMPTY);
 +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
-+PNG_EXTERN void png_progressive_read_reset PNGARG((png_structp png_ptr));
++PNG_INTERNAL_FUNCTION(void,png_progressive_read_reset,(png_structp png_ptr),
++   PNG_EMPTY);
 +#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
 +#endif /* PNG_READ_APNG_SUPPORTED */
 +
 +#ifdef PNG_WRITE_APNG_SUPPORTED
-+PNG_EXTERN void png_write_acTL PNGARG((png_structp png_ptr,
-+   png_uint_32 num_frames, png_uint_32 num_plays));
-+PNG_EXTERN void png_write_fcTL PNGARG((png_structp png_ptr,
++PNG_INTERNAL_FUNCTION(void,png_write_acTL,(png_structp png_ptr,
++   png_uint_32 num_frames, png_uint_32 num_plays),PNG_EMPTY);
++PNG_INTERNAL_FUNCTION(void,png_write_fcTL,(png_structp png_ptr,
 +   png_uint_32 width, png_uint_32 height,
 +   png_uint_32 x_offset, png_uint_32 y_offset,
 +   png_uint_16 delay_num, png_uint_16 delay_den,
-+   png_byte dispose_op, png_byte blend_op));
-+PNG_EXTERN void png_write_reset PNGARG((png_structp png_ptr));
-+PNG_EXTERN void png_write_reinit PNGARG((png_structp png_ptr,
-+   png_infop info_ptr, png_uint_32 width, png_uint_32 height));
++   png_byte dispose_op, png_byte blend_op),PNG_EMPTY);
++PNG_INTERNAL_FUNCTION(void,png_write_fdAT,(png_structp png_ptr,
++   png_const_bytep data, png_size_t length),PNG_EMPTY);
++PNG_INTERNAL_FUNCTION(void,png_write_reset,(png_structp png_ptr),PNG_EMPTY);
++PNG_INTERNAL_FUNCTION(void,png_write_reinit,(png_structp png_ptr,
++   png_infop info_ptr, png_uint_32 width, png_uint_32 height),PNG_EMPTY);
 +#endif /* PNG_WRITE_APNG_SUPPORTED */
 +#endif /* PNG_APNG_SUPPORTED */
 +
- /* Added at libpng version 1.4.0 */
- #ifdef PNG_CHECK_cHRM_SUPPORTED
- PNG_EXTERN int png_check_cHRM_fixed PNGARG((png_structp png_ptr,
+ /* Added at libpng version 1.6.0 */
+ #ifdef PNG_GAMMA_SUPPORTED
+ PNG_INTERNAL_FUNCTION(void,png_colorspace_set_gamma,(png_const_structrp png_ptr,
 Index: pnginfo.h
 ===================================================================
 --- pnginfo.h
 +++ pnginfo.h
-@@ -265,5 +265,18 @@
+@@ -256,5 +256,18 @@
     png_bytepp row_pointers;        /* the image bits */
  #endif
  
 +#ifdef PNG_APNG_SUPPORTED
 +   png_uint_32 num_frames; /* including default image */
 +   png_uint_32 num_plays;
 +   png_uint_32 next_frame_width;
 +   png_uint_32 next_frame_height;
@@ -576,17 +521,17 @@ Index: pnginfo.h
 +#endif
 +
  };
  #endif /* PNGINFO_H */
 Index: pngstruct.h
 ===================================================================
 --- pngstruct.h
 +++ pngstruct.h
-@@ -293,6 +293,27 @@
+@@ -409,6 +409,27 @@
     png_byte filter_type;
  #endif
  
 +#ifdef PNG_APNG_SUPPORTED
 +   png_uint_32 apng_flags;
 +   png_uint_32 next_seq_num;         /* next fcTL/fdAT chunk sequence number */
 +   png_uint_32 first_frame_width;
 +   png_uint_32 first_frame_height;
@@ -608,43 +553,43 @@ Index: pngstruct.h
 +
  /* New members added in libpng-1.2.0 */
  
  /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
 Index: pngwrite.c
 ===================================================================
 --- pngwrite.c
 +++ pngwrite.c
-@@ -58,6 +58,10 @@
-    /* The rest of these check to see if the valid field has the appropriate
-     * flag set, and if it does, writes the chunk.
+@@ -127,6 +127,10 @@
+     * application continues writing the PNG.  So check the 'invalid' flag here
+     * too.
      */
 +#ifdef PNG_WRITE_APNG_SUPPORTED
 +   if (info_ptr->valid & PNG_INFO_acTL)
 +      png_write_acTL(png_ptr, info_ptr->num_frames, info_ptr->num_plays);
 +#endif
- #ifdef PNG_WRITE_gAMA_SUPPORTED
-    if (info_ptr->valid & PNG_INFO_gAMA)
-       png_write_gAMA_fixed(png_ptr, info_ptr->gamma);
-@@ -310,6 +314,11 @@
-       png_benign_error(png_ptr, "Wrote palette index exceeding num_palette");
- #endif
+ #ifdef PNG_GAMMA_SUPPORTED
+ #  ifdef PNG_WRITE_gAMA_SUPPORTED
+       if (!(info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) &&
+@@ -352,6 +356,11 @@
+    if (!(png_ptr->mode & PNG_HAVE_IDAT))
+       png_error(png_ptr, "No IDATs written into file");
  
 +#ifdef PNG_WRITE_APNG_SUPPORTED
 +   if (png_ptr->num_frames_written != png_ptr->num_frames_to_write)
 +      png_error(png_ptr, "Not enough frames written");
 +#endif
 +
-    /* See if user wants us to write information chunks */
-    if (info_ptr != NULL)
-    {
-@@ -1667,4 +1676,42 @@
-    PNG_UNUSED(params)
+ #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
+    if (png_ptr->num_palette_max > png_ptr->num_palette)
+       png_benign_error(png_ptr, "Wrote palette index exceeding num_palette");
+@@ -2327,4 +2336,42 @@
  }
- #endif
+ #endif /* PNG_STDIO_SUPPORTED */
+ #endif /* SIMPLIFIED_WRITE */
 +
 +#ifdef PNG_WRITE_APNG_SUPPORTED
 +void PNGAPI
 +png_write_frame_head(png_structp png_ptr, png_infop info_ptr,
 +    png_bytepp row_pointers, png_uint_32 width, png_uint_32 height,
 +    png_uint_32 x_offset, png_uint_32 y_offset,
 +    png_uint_16 delay_num, png_uint_16 delay_den, png_byte dispose_op,
 +    png_byte blend_op)
@@ -678,17 +623,17 @@ Index: pngwrite.c
 +    PNG_UNUSED(info_ptr)
 +}
 +#endif /* PNG_WRITE_APNG_SUPPORTED */
  #endif /* PNG_WRITE_SUPPORTED */
 Index: pngpread.c
 ===================================================================
 --- pngpread.c
 +++ pngpread.c
-@@ -215,6 +215,109 @@
+@@ -217,6 +217,109 @@
  
     chunk_name = png_ptr->chunk_name;
  
 +#ifdef PNG_READ_APNG_SUPPORTED
 +   if (png_ptr->num_frames_read > 0 &&
 +       png_ptr->num_frames_read < info_ptr->num_frames)
 +   {
 +      if (chunk_name == png_IDAT)
@@ -787,76 +732,78 @@ Index: pngpread.c
 +      }
 +
 +      return;
 +   }
 +#endif /* PNG_READ_APNG_SUPPORTED */
 +
     if (chunk_name == png_IDAT)
     {
-       /* This is here above the if/else case statement below because if the
-@@ -318,6 +421,10 @@
-             png_benign_error(png_ptr, "Too many IDATs found");
-       }
+       if (png_ptr->mode & PNG_AFTER_IDAT)
+@@ -299,6 +402,9 @@
  
+    else if (chunk_name == png_IDAT)
+    {
 +#ifdef PNG_READ_APNG_SUPPORTED
 +      png_have_info(png_ptr, info_ptr);
 +#endif
-+
        png_ptr->idat_size = png_ptr->push_length;
-       png_ptr->mode |= PNG_HAVE_IDAT;
        png_ptr->process_mode = PNG_READ_IDAT_MODE;
-@@ -550,6 +657,27 @@
+       png_push_have_info(png_ptr, info_ptr);
+@@ -530,6 +636,30 @@
     }
  
  #endif
 +#ifdef PNG_READ_APNG_SUPPORTED
 +   else if (chunk_name == png_acTL)
 +   {
 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
 +      {
 +         png_push_save_buffer(png_ptr);
 +         return;
 +      }
++
 +      png_handle_acTL(png_ptr, info_ptr, png_ptr->push_length);
 +   }
 +
 +   else if (chunk_name == png_fcTL)
 +   {
 +      if (png_ptr->push_length + 4 > png_ptr->buffer_size)
 +      {
 +         png_push_save_buffer(png_ptr);
 +         return;
 +      }
++
 +      png_handle_fcTL(png_ptr, info_ptr, png_ptr->push_length);
 +   }
++
 +#endif /* PNG_READ_APNG_SUPPORTED */
- 
     else
     {
-@@ -758,7 +886,11 @@
+       if (png_ptr->push_length + 4 > png_ptr->buffer_size)
+@@ -731,7 +861,11 @@
        png_byte chunk_tag[4];
  
        /* TODO: this code can be commoned up with the same code in push_read */
 +#ifdef PNG_READ_APNG_SUPPORTED
 +      if (png_ptr->buffer_size < 12)
 +#else
        if (png_ptr->buffer_size < 8)
 +#endif
        {
           png_push_save_buffer(png_ptr);
           return;
-@@ -771,17 +903,64 @@
+@@ -744,17 +878,64 @@
        png_ptr->chunk_name = PNG_CHUNK_FROM_STRING(chunk_tag);
        png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  
 +#ifdef PNG_READ_APNG_SUPPORTED
 +      if (png_ptr->chunk_name != png_fdAT && png_ptr->num_frames_read > 0)
 +      {
-+          if (png_ptr->flags & PNG_FLAG_ZLIB_FINISHED)
++          if (png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED)
 +          {
 +              png_ptr->process_mode = PNG_READ_CHUNK_MODE;
 +              if (png_ptr->frame_end_fn != NULL)
 +                 (*(png_ptr->frame_end_fn))(png_ptr, png_ptr->num_frames_read);
 +              png_ptr->num_frames_read++;
 +              return;
 +          }
 +          else
@@ -880,17 +827,17 @@ Index: pngpread.c
 +#ifdef PNG_READ_APNG_SUPPORTED
 +      if (png_ptr->chunk_name != png_IDAT && png_ptr->num_frames_read == 0)
 +#else
        if (png_ptr->chunk_name != png_IDAT)
 +#endif
        {
           png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  
-          if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
+          if (!(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
              png_error(png_ptr, "Not enough compressed data");
  
 +#ifdef PNG_READ_APNG_SUPPORTED
 +         if (png_ptr->frame_end_fn != NULL)
 +            (*(png_ptr->frame_end_fn))(png_ptr, png_ptr->num_frames_read);
 +         png_ptr->num_frames_read++;
 +#endif
 +
@@ -904,68 +851,68 @@ Index: pngpread.c
 +      {
 +         png_ensure_sequence_number(png_ptr, 4);
 +         png_ptr->idat_size -= 4;
 +      }
 +#endif
     }
  
     if (png_ptr->idat_size && png_ptr->save_buffer_size)
-@@ -859,6 +1038,15 @@
+@@ -832,6 +1013,15 @@
     if (!(buffer_length > 0) || buffer == NULL)
        png_error(png_ptr, "No IDAT data (internal error)");
  
 +#ifdef PNG_READ_APNG_SUPPORTED
 +   /* If the app is not APNG-aware, decode only the first frame */
 +   if (!(png_ptr->apng_flags & PNG_APNG_APP) && png_ptr->num_frames_read > 0)
 +   {
-+     png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
++     png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
 +     return;
 +   }
 +#endif
 +
     /* This routine must process all the data it has been given
      * before returning, calling the row callback as required to
      * handle the uncompressed results.
-@@ -1304,6 +1492,18 @@
+@@ -1280,6 +1470,18 @@
     png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  }
  
 +#ifdef PNG_READ_APNG_SUPPORTED
 +void PNGAPI
 +png_set_progressive_frame_fn(png_structp png_ptr,
 +   png_progressive_frame_ptr frame_info_fn,
 +   png_progressive_frame_ptr frame_end_fn)
 +{
 +   png_ptr->frame_info_fn = frame_info_fn;
 +   png_ptr->frame_end_fn = frame_end_fn;
 +   png_ptr->apng_flags |= PNG_APNG_APP;
 +}
 +#endif
 +
  png_voidp PNGAPI
- png_get_progressive_ptr(png_const_structp png_ptr)
+ png_get_progressive_ptr(png_const_structrp png_ptr)
  {
 Index: pngset.c
 ===================================================================
 --- pngset.c
 +++ pngset.c
-@@ -253,6 +253,11 @@
+@@ -239,6 +239,11 @@
     info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  
     info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth, width);
 +
 +#ifdef PNG_APNG_SUPPORTED
 +   /* for non-animated png. this may be overwritten from an acTL chunk later */
 +   info_ptr->num_frames = 1;
 +#endif
  }
  
  #ifdef PNG_oFFs_SUPPORTED
-@@ -1039,6 +1044,147 @@
+@@ -1065,6 +1070,147 @@
  }
  #endif /* PNG_sPLT_SUPPORTED */
  
 +#ifdef PNG_APNG_SUPPORTED
 +png_uint_32 PNGAPI
 +png_set_acTL(png_structp png_ptr, png_infop info_ptr,
 +    png_uint_32 num_frames, png_uint_32 num_plays)
 +{
@@ -1100,36 +1047,36 @@ Index: pngset.c
 +        png_ptr->apng_flags &= ~PNG_FIRST_FRAME_HIDDEN;
 +
 +    PNG_UNUSED(info_ptr)
 +
 +    return 1;
 +}
 +#endif /* PNG_APNG_SUPPORTED */
 +
- #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
- void PNGAPI
- png_set_unknown_chunks(png_structp png_ptr,
+ #ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
+ static png_byte
+ check_location(png_const_structrp png_ptr, int location)
 Index: pngrutil.c
 ===================================================================
 --- pngrutil.c
 +++ pngrutil.c
-@@ -545,6 +545,11 @@
+@@ -821,6 +821,11 @@
     filter_type = buf[11];
     interlace_type = buf[12];
  
 +#ifdef PNG_READ_APNG_SUPPORTED
 +   png_ptr->first_frame_width = width;
 +   png_ptr->first_frame_height = height;
 +#endif
 +
     /* Set internal variables */
     png_ptr->width = width;
     png_ptr->height = height;
-@@ -2622,6 +2627,179 @@
+@@ -2695,6 +2700,179 @@
  }
  #endif
  
 +#ifdef PNG_READ_APNG_SUPPORTED
 +void /* PRIVATE */
 +png_handle_acTL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
 +{
 +    png_byte data[8];
@@ -1296,20 +1243,77 @@ Index: pngrutil.c
 +    if (sequence_number != png_ptr->next_seq_num)
 +        png_error(png_ptr, "fcTL or fdAT chunk with out-of-order sequence "
 +                           "number found");
 +
 +    png_ptr->next_seq_num++;
 +}
 +#endif /* PNG_READ_APNG_SUPPORTED */
 +
- /* This function is called when we haven't found a handler for a
-  * chunk.  If there isn't a problem with the chunk itself (ie bad
-  * chunk name, CRC, or a critical chunk), the chunk is silently ignored
-@@ -4112,4 +4290,80 @@
+ #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
+ /* Utility function for png_handle_unknown; set up png_ptr::unknown_chunk */
+ static int
+@@ -3952,6 +4130,38 @@
+          uInt avail_in;
+          png_bytep buffer;
+ 
++#ifdef PNG_READ_APNG_SUPPORTED
++         png_uint_32 bytes_to_skip = 0;
++
++         while (png_ptr->idat_size == 0 || bytes_to_skip != 0)
++         {
++            png_crc_finish(png_ptr, bytes_to_skip);
++            bytes_to_skip = 0;
++
++            png_ptr->idat_size = png_read_chunk_header(png_ptr);
++            if (png_ptr->num_frames_read == 0)
++            {
++               if (png_ptr->chunk_name != png_IDAT)
++                  png_error(png_ptr, "Not enough image data");
++            }
++            else
++            {
++               if (png_ptr->chunk_name == png_IEND)
++                  png_error(png_ptr, "Not enough image data");
++               if (png_ptr->chunk_name != png_fdAT)
++               {
++                  png_warning(png_ptr, "Skipped (ignored) a chunk "
++                                       "between APNG chunks");
++                  bytes_to_skip = png_ptr->idat_size;
++                  continue;
++               }
++
++               png_ensure_sequence_number(png_ptr, png_ptr->idat_size);
++
++               png_ptr->idat_size -= 4;
++            }
++         }
++#else
+          while (png_ptr->idat_size == 0)
+          {
+             png_crc_finish(png_ptr, 0);
+@@ -3963,6 +4173,7 @@
+             if (png_ptr->chunk_name != png_IDAT)
+                png_error(png_ptr, "Not enough image data");
+          }
++#endif /* PNG_READ_APNG_SUPPORTED */
+ 
+          avail_in = png_ptr->IDAT_read_size;
+ 
+@@ -4026,6 +4237,9 @@
+ 
+          png_ptr->mode |= PNG_AFTER_IDAT;
+          png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED;
++#ifdef PNG_READ_APNG_SUPPORTED
++         png_ptr->num_frames_read++;
++#endif
+ 
+          if (png_ptr->zstream.avail_in > 0 || png_ptr->idat_size > 0)
+             png_chunk_benign_error(png_ptr, "Extra compressed data");
+@@ -4471,4 +4685,80 @@
  
     png_ptr->flags |= PNG_FLAG_ROW_INIT;
  }
 +
 +#ifdef PNG_READ_APNG_SUPPORTED
 +/* This function is to be called after the main IDAT set has been read and
 + * before a new IDAT is read. It resets some parts of png_ptr
 + * to make them usable by the read functions again */
@@ -1326,38 +1330,38 @@ Index: pngrutil.c
 +png_read_reinit(png_structp png_ptr, png_infop info_ptr)
 +{
 +    png_ptr->width = info_ptr->next_frame_width;
 +    png_ptr->height = info_ptr->next_frame_height;
 +    png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
 +    png_ptr->info_rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,
 +        png_ptr->width);
 +    if (png_ptr->prev_row)
-+        png_memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
++        memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
 +}
 +
 +#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
 +/* same as png_read_reset() but for the progressive reader */
 +void /* PRIVATE */
 +png_progressive_read_reset(png_structp png_ptr)
 +{
 +#ifdef PNG_READ_INTERLACING_SUPPORTED
-+   /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
++    /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
 +
-+   /* Start of interlace block */
-+    const int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
++    /* Start of interlace block */
++    static PNG_CONST png_byte png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
 +
 +    /* Offset to next interlace block */
-+    const int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
++    static PNG_CONST png_byte png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
 +
 +    /* Start of interlace block in the y direction */
-+    const int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
++    static PNG_CONST png_byte png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
 +
 +    /* Offset to next interlace block in the y direction */
-+    const int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
++    static PNG_CONST png_byte png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
 +
 +    if (png_ptr->interlaced)
 +    {
 +        if (!(png_ptr->transformations & PNG_INTERLACE))
 +            png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
 +                                png_pass_ystart[0]) / png_pass_yinc[0];
 +        else
 +            png_ptr->num_rows = png_ptr->height;
@@ -1368,74 +1372,77 @@ Index: pngrutil.c
 +                           png_pass_inc[png_ptr->pass];
 +    }
 +    else
 +#endif /* PNG_READ_INTERLACING_SUPPORTED */
 +    {
 +        png_ptr->num_rows = png_ptr->height;
 +        png_ptr->iwidth = png_ptr->width;
 +    }
-+    png_ptr->flags &= ~PNG_FLAG_ZLIB_FINISHED;
++    png_ptr->flags &= ~PNG_FLAG_ZSTREAM_ENDED;
 +    if (inflateReset(&(png_ptr->zstream)) != Z_OK)
 +        png_error(png_ptr, "inflateReset failed");
 +    png_ptr->zstream.avail_in = 0;
 +    png_ptr->zstream.next_in = 0;
 +    png_ptr->zstream.next_out = png_ptr->row_buf;
 +    png_ptr->zstream.avail_out = (uInt)PNG_ROWBYTES(png_ptr->pixel_depth,
 +        png_ptr->iwidth) + 1;
 +}
 +#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
 +#endif /* PNG_READ_APNG_SUPPORTED */
  #endif /* PNG_READ_SUPPORTED */
 Index: pngwutil.c
 ===================================================================
 --- pngwutil.c
 +++ pngwutil.c
-@@ -818,6 +818,11 @@
+@@ -898,6 +898,11 @@
     /* Write the chunk */
     png_write_complete_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  
 +#ifdef PNG_WRITE_APNG_SUPPORTED
 +   png_ptr->first_frame_width = width;
 +   png_ptr->first_frame_height = height;
 +#endif
 +
-    /* Initialize zlib with PNG info */
-    png_ptr->zstream.zalloc = png_zalloc;
-    png_ptr->zstream.zfree = png_zfree;
-@@ -1032,7 +1037,28 @@
-    }
- #endif /* PNG_WRITE_OPTIMIZE_CMF_SUPPORTED */
+    if (!(png_ptr->do_filter))
+    {
+       if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
+@@ -1076,7 +1081,15 @@
+                optimize_cmf(data, png_image_size(png_ptr));
+ #        endif
  
-+#ifdef PNG_WRITE_APNG_SUPPORTED
-+   if (png_ptr->num_frames_written == 0)
-+#endif
-    png_write_complete_chunk(png_ptr, png_IDAT, data, length);
-+#ifdef PNG_WRITE_APNG_SUPPORTED
-+   else
-+   {
-+      png_byte buf[4];
++#        ifdef PNG_WRITE_APNG_SUPPORTED
++         if (png_ptr->num_frames_written == 0)
++#        endif
+          png_write_complete_chunk(png_ptr, png_IDAT, data, size);
++#        ifdef PNG_WRITE_APNG_SUPPORTED
++         else
++            png_write_fdAT(png_ptr, data, size);
++#        endif /* PNG_WRITE_APNG_SUPPORTED */
 +
-+      png_write_chunk_header(png_ptr, png_fdAT, (png_uint_32)(4 + length));
-+
-+      png_save_uint_32(buf, png_ptr->next_seq_num);
-+      png_write_chunk_data(png_ptr, buf, 4);
-+
-+      png_write_chunk_data(png_ptr, data, length);
-+
-+      png_write_chunk_end(png_ptr);
+          png_ptr->mode |= PNG_HAVE_IDAT;
+ 
+          png_ptr->zstream.next_out = data;
+@@ -1122,7 +1135,15 @@
+                optimize_cmf(data, png_image_size(png_ptr));
+ #        endif
+ 
++#        ifdef PNG_WRITE_APNG_SUPPORTED
++         if (png_ptr->num_frames_written == 0)
++#        endif
+          png_write_complete_chunk(png_ptr, png_IDAT, data, size);
++#        ifdef PNG_WRITE_APNG_SUPPORTED
++         else
++            png_write_fdAT(png_ptr, data, size);
++#        endif /* PNG_WRITE_APNG_SUPPORTED */
 +
-+      png_ptr->next_seq_num++;
-+   }
-+#endif /* PNG_WRITE_APNG_SUPPORTED */
-+
-    png_ptr->mode |= PNG_HAVE_IDAT;
- 
-    /* Prior to 1.5.4 this code was replicated in every caller (except at the
-@@ -1995,6 +2021,64 @@
+          png_ptr->zstream.avail_out = 0;
+          png_ptr->zstream.next_out = NULL;
+          png_ptr->mode |= PNG_HAVE_IDAT | PNG_AFTER_IDAT;
+@@ -1934,6 +1955,82 @@
  }
  #endif
  
 +#ifdef PNG_WRITE_APNG_SUPPORTED
 +void /* PRIVATE */
 +png_write_acTL(png_structp png_ptr,
 +    png_uint_32 num_frames, png_uint_32 num_plays)
 +{
@@ -1485,22 +1492,40 @@ Index: pngwutil.c
 +    png_save_uint_16(buf + 22, delay_den);
 +    buf[24] = dispose_op;
 +    buf[25] = blend_op;
 +
 +    png_write_complete_chunk(png_ptr, png_fcTL, buf, (png_size_t)26);
 +
 +    png_ptr->next_seq_num++;
 +}
++
++void /* PRIVATE */
++png_write_fdAT(png_structp png_ptr,
++    png_const_bytep data, png_size_t length)
++{
++    png_byte buf[4];
++
++    png_write_chunk_header(png_ptr, png_fdAT, (png_uint_32)(4 + length));
++
++    png_save_uint_32(buf, png_ptr->next_seq_num);
++    png_write_chunk_data(png_ptr, buf, 4);
++
++    png_write_chunk_data(png_ptr, data, length);
++
++    png_write_chunk_end(png_ptr);
++
++    png_ptr->next_seq_num++;
++}
 +#endif /* PNG_WRITE_APNG_SUPPORTED */
 +
  /* Initializes the row writing capability of libpng */
  void /* PRIVATE */
- png_write_start_row(png_structp png_ptr)
-@@ -3174,4 +3258,39 @@
+ png_write_start_row(png_structrp png_ptr)
+@@ -3020,4 +3117,39 @@
     }
  #endif
  }
 +
 +#ifdef PNG_WRITE_APNG_SUPPORTED
 +void /* PRIVATE */
 +png_write_reset(png_structp png_ptr)
 +{
@@ -1534,32 +1559,32 @@ Index: pngwutil.c
 +    png_ptr->usr_width = png_ptr->width;
 +}
 +#endif /* PNG_WRITE_APNG_SUPPORTED */
  #endif /* PNG_WRITE_SUPPORTED */
 Index: scripts/symbols.def
 ===================================================================
 --- scripts/symbols.def
 +++ scripts/symbols.def
-@@ -242,3 +242,23 @@
-  png_set_check_for_invalid_index @234
-  png_get_palette_max @235
-  png_set_option @236
-+ png_get_acTL @237
-+ png_set_acTL @238
-+ png_get_num_frames @239
-+ png_get_num_plays @240
-+ png_get_next_frame_fcTL @241
-+ png_set_next_frame_fcTL @242
-+ png_get_next_frame_width @243
-+ png_get_next_frame_height @244
-+ png_get_next_frame_x_offset @245
-+ png_get_next_frame_y_offset @246
-+ png_get_next_frame_delay_num @247
-+ png_get_next_frame_delay_den @248
-+ png_get_next_frame_dispose_op @249
-+ png_get_next_frame_blend_op @250
-+ png_get_first_frame_is_hidden @251
-+ png_set_first_frame_is_hidden @252
-+ png_read_frame_head @253
-+ png_set_progressive_frame_fn @254
-+ png_write_frame_head @255
-+ png_write_frame_tail @256
+@@ -249,3 +249,23 @@
+  png_set_check_for_invalid_index @242
+  png_get_palette_max @243
+  png_set_option @244
++ png_get_acTL @245
++ png_set_acTL @246
++ png_get_num_frames @247
++ png_get_num_plays @248
++ png_get_next_frame_fcTL @249
++ png_set_next_frame_fcTL @250
++ png_get_next_frame_width @251
++ png_get_next_frame_height @252
++ png_get_next_frame_x_offset @253
++ png_get_next_frame_y_offset @254
++ png_get_next_frame_delay_num @255
++ png_get_next_frame_delay_den @256
++ png_get_next_frame_dispose_op @257
++ png_get_next_frame_blend_op @258
++ png_get_first_frame_is_hidden @259
++ png_set_first_frame_is_hidden @260
++ png_read_frame_head @261
++ png_set_progressive_frame_fn @262
++ png_write_frame_head @263
++ png_write_frame_tail @264
--- a/media/libpng/arm/arm_init.c
+++ b/media/libpng/arm/arm_init.c
@@ -1,26 +1,27 @@
 
 /* arm_init.c - NEON optimised filter functions
  *
  * Copyright (c) 2013 Glenn Randers-Pehrson
  * Written by Mans Rullgard, 2011.
- * Last changed in libpng 1.5.17 [June 27, 2013]
+ * Last changed in libpng 1.6.5 [September 16, 2013]
  *
  * This code is released under the libpng license.
  * For conditions of distribution and use, see the disclaimer
  * and license in png.h
  */
 /* Below, after checking __linux__, various non-C90 POSIX 1003.1 functions are
  * called.
  */
 #define _POSIX_SOURCE 1
 
 #include "../pngpriv.h"
 
+#ifdef PNG_READ_SUPPORTED
 #if PNG_ARM_NEON_OPT > 0
 #ifdef PNG_ARM_NEON_CHECK_SUPPORTED /* Do run-time checks */
 #include <signal.h> /* for sig_atomic_t */
 
 #ifdef __ANDROID__
 /* Linux provides access to information about CPU capabilites via
  * /proc/self/auxv, however Android blocks this while still claiming to be
  * Linux.  The Andoid NDK, however, provides appropriate support.
@@ -212,8 +213,9 @@ png_init_filter_functions_neon(png_struc
    {
       pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub4_neon;
       pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg4_neon;
       pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
           png_read_filter_row_paeth4_neon;
    }
 }
 #endif /* PNG_ARM_NEON_OPT > 0 */
+#endif /* PNG_READ_SUPPORTED */
--- a/media/libpng/arm/filter_neon.S
+++ b/media/libpng/arm/filter_neon.S
@@ -1,30 +1,31 @@
 
 /* filter_neon.S - NEON optimised filter functions
  *
  * Copyright (c) 2013 Glenn Randers-Pehrson
  * Written by Mans Rullgard, 2011.
- * Last changed in libpng 1.5.17 [June 27, 2013]
+ * Last changed in libpng 1.5.17 [July 18, 2013]
  *
  * This code is released under the libpng license.
  * For conditions of distribution and use, see the disclaimer
  * and license in png.h
  */
 
 /* This is required to get the symbol renames, which are #defines, and also
  * includes the definition (or not) of PNG_ARM_NEON_OPT.
  */
 #define PNG_VERSION_INFO_ONLY
 #include "../pngpriv.h"
 
 #if defined(__linux__) && defined(__ELF__)
 .section .note.GNU-stack,"",%progbits /* mark stack as non-executable */
 #endif
 
+#ifdef PNG_READ_SUPPORTED
 #if PNG_ARM_NEON_OPT > 0
 
 #ifdef __ELF__
 #   define ELF
 #else
 #   define ELF @
 #endif
 
@@ -228,8 +229,9 @@ 1:
         vadd.u8         d3,  d3,  d7
         vst1.32         {d3[0]},  [r1], r4
         subs            r12, r12, #12
         bgt             1b
 
         pop             {r4,pc}
 endfunc
 #endif /* PNG_ARM_NEON_OPT > 0 */
+#endif /* PNG_READ_SUPPORTED */
--- a/media/libpng/libpng-manual.txt
+++ b/media/libpng/libpng-manual.txt
@@ -1,38 +1,57 @@
-Libpng-manual.txt - A description on how to use and modify libpng
-
- libpng version 1.5.16 - May 23, 2013
+libpng-manual.txt - A description on how to use and modify libpng
+
+ libpng version 1.6.6 - September 16, 2013
  Updated and distributed by Glenn Randers-Pehrson
  <glennrp at users.sourceforge.net>
  Copyright (c) 1998-2013 Glenn Randers-Pehrson
 
  This document is released under the libpng license.
  For conditions of distribution and use, see the disclaimer
  and license in png.h
 
  Based on:
 
- libpng versions 0.97, January 1998, through 1.5.16 - May 23, 2013
+ libpng versions 0.97, January 1998, through 1.6.6 - September 16, 2013
  Updated and distributed by Glenn Randers-Pehrson
  Copyright (c) 1998-2013 Glenn Randers-Pehrson
 
  libpng 1.0 beta 6  version 0.96 May 28, 1997
  Updated and distributed by Andreas Dilger
  Copyright (c) 1996, 1997 Andreas Dilger
 
  libpng 1.0 beta 2 - version 0.88  January 26, 1996
  For conditions of distribution and use, see copyright
  notice in png.h. Copyright (c) 1995, 1996 Guy Eric
  Schalnat, Group 42, Inc.
 
  Updated/rewritten per request in the libpng FAQ
  Copyright (c) 1995, 1996 Frank J. T. Wojcik
  December 18, 1995 & January 20, 1996
 
+ TABLE OF CONTENTS
+
+    I. Introduction
+   II. Structures
+  III. Reading
+   IV. Writing
+    V. Simplified API
+   VI. Modifying/Customizing libpng
+  VII. MNG support
+ VIII. Changes to Libpng from version 0.88
+   IX. Changes to Libpng from version 1.0.x to 1.2.x
+    X. Changes to Libpng from version 1.0.x/1.2.x to 1.4.x
+   XI. Changes to Libpng from version 1.4.x to 1.5.x
+  XII. Changes to Libpng from version 1.5.x to 1.6.x
+ XIII. Detecting libpng
+  XIV. Source code repository
+   XV. Coding style
+  XVI. Y2K Compliance in libpng
+
 I. Introduction
 
 This file describes how to use and modify the PNG reference library
 (known as libpng) for your own use.  In addition to this
 file, example.c is a good starting point for using the library, as
 it is heavily commented and should include everything most people
 will need.  We assume that libpng is already installed; see the
 INSTALL file for instructions on how to install libpng.
@@ -501,18 +520,24 @@ To inform libpng about your function, us
         read_chunk_callback);
 
 This names not only the callback function, but also a user pointer that
 you can retrieve with
 
     png_get_user_chunk_ptr(png_ptr);
 
 If you call the png_set_read_user_chunk_fn() function, then all unknown
-chunks will be saved when read, in case your callback function will need
-one or more of them.
+chunks which the callback does not handle will be saved when read.  You can
+cause them to be discarded by returning '1' ("handled") instead of '0'.  This
+behavior will change in libpng 1.7 and the default handling set by the
+png_set_keep_unknown_chunks() function, described below, will be used when the
+callback returns 0.  If you want the existing behavior you should set the global
+default to PNG_HANDLE_CHUNK_IF_SAFE now; this is compatible with all current
+versions of libpng and with 1.7.  Libpng 1.6 issues a warning if you keep the
+default, or PNG_HANDLE_CHUNK_NEVER, and the callback returns 0.
 
 At this point, you can set up a callback function that will be
 called after each row has been read, which you can use to control
 a progress meter or the like.  It's demonstrated in pngtest.c.
 You must supply a function
 
     void read_row_callback(png_structp png_ptr,
        png_uint_32 row, int pass);
@@ -545,34 +570,40 @@ Now you get to set the way the library p
 input PNG stream. Both known and unknown chunks will be read.  Normal
 behavior is that known chunks will be parsed into information in
 various info_ptr members while unknown chunks will be discarded. This
 behavior can be wasteful if your application will never use some known
 chunk types. To change this, you can call:
 
     png_set_keep_unknown_chunks(png_ptr, keep,
         chunk_list, num_chunks);
+
     keep       - 0: default unknown chunk handling
                  1: ignore; do not keep
                  2: keep only if safe-to-copy
                  3: keep even if unsafe-to-copy
 
                You can use these definitions:
                  PNG_HANDLE_CHUNK_AS_DEFAULT   0
                  PNG_HANDLE_CHUNK_NEVER        1
                  PNG_HANDLE_CHUNK_IF_SAFE      2
                  PNG_HANDLE_CHUNK_ALWAYS       3
 
     chunk_list - list of chunks affected (a byte string,
                  five bytes per chunk, NULL or '\0' if
-                 num_chunks is 0)
+                 num_chunks is positive; ignored if
+                 numchunks <= 0).
 
     num_chunks - number of chunks affected; if 0, all
-                 unknown chunks are affected.  If nonzero,
-                 only the chunks in the list are affected
+                 unknown chunks are affected.  If positive,
+                 only the chunks in the list are affected,
+                 and if negative all unknown chunks and
+                 all known chunks except for the IHDR,
+                 PLTE, tRNS, IDAT, and IEND chunks are
+                 affected.
 
 Unknown chunks declared in this way will be saved as raw data onto a
 list of png_unknown_chunk structures.  If a chunk that is normally
 known to libpng is named in the list, it will be handled as unknown,
 according to the "keep" directive.  If a chunk is named in successive
 instances of png_set_keep_unknown_chunks(), the final instance will
 take precedence.  The IHDR and IEND chunks should not be named in
 chunk_list; if they are, libpng will process them normally anyway.
@@ -595,29 +626,27 @@ callback function:
         115,  80,  76,  84, (png_byte) '\0',   /* sPLT */
         116,  73,  77,  69, (png_byte) '\0',   /* tIME */
       };
     #endif
 
     ...
 
     #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
-      /* ignore all unknown chunks: */
-    #  if PNG_LIBPNG_VER < 10700
+      /* ignore all unknown chunks
+       * (use global setting "2" for libpng16 and earlier):
+       */
       png_set_keep_unknown_chunks(read_ptr, 2, NULL, 0);
-    #  else
-      png_set_keep_unknown_chunks(read_ptr, 1, NULL, 0);
-    #  endif
 
       /* except for vpAg: */
       png_set_keep_unknown_chunks(read_ptr, 2, vpAg, 1);
 
       /* also ignore unused known chunks: */
       png_set_keep_unknown_chunks(read_ptr, 1, unused_chunks,
-         (int)png_sizeof(unused_chunks)/5);
+         (int)(sizeof unused_chunks)/5);
     #endif
 
 User limits
 
 The PNG specification allows the width and height of an image to be as
 large as 2^31-1 (0x7fffffff), or about 2.147 billion rows and columns.
 Since very few applications really need to process such large images,
 we have imposed an arbitrary 1-million limit on rows and columns.
@@ -682,55 +711,59 @@ You give libpng the encoding expected by
 value.  You can also specify a default encoding for the PNG file in
 case the required information is missing from the file.  By default libpng
 assumes that the PNG data matches your system, to keep this default call:
 
    png_set_gamma(png_ptr, screen_gamma, 1/screen_gamma/*file gamma*/);
 
 or you can use the fixed point equivalent:
 
-   png_set_gamma_fixed(png_ptr, PNG_FP_1*screen_gamma, PNG_FP_1/screen_gamma);
+   png_set_gamma_fixed(png_ptr, PNG_FP_1*screen_gamma,
+      PNG_FP_1/screen_gamma);
 
 If you don't know the gamma for your system it is probably 2.2 - a good
 approximation to the IEC standard for display systems (sRGB).  If images are
 too contrasty or washed out you got the value wrong - check your system
 documentation!
 
 Many systems permit the system gamma to be changed via a lookup table in the
 display driver, a few systems, including older Macs, change the response by
 default.  As of 1.5.4 three special values are available to handle common
 situations:
 
-   PNG_DEFAULT_sRGB: Indicates that the system conforms to the IEC 61966-2-1
-                     standard.  This matches almost all systems.
-   PNG_GAMMA_MAC_18: Indicates that the system is an older (pre Mac OS 10.6)
-                     Apple Macintosh system with the default settings.
-   PNG_GAMMA_LINEAR: Just the fixed point value for 1.0 - indicates that the
-                     system expects data with no gamma encoding.
+   PNG_DEFAULT_sRGB: Indicates that the system conforms to the
+                     IEC 61966-2-1 standard.  This matches almost
+                     all systems.
+   PNG_GAMMA_MAC_18: Indicates that the system is an older
+                     (pre Mac OS 10.6) Apple Macintosh system with
+                     the default settings.
+   PNG_GAMMA_LINEAR: Just the fixed point value for 1.0 - indicates
+                     that the system expects data with no gamma
+                     encoding.
 
 You would use the linear (unencoded) value if you need to process the pixel
-values further because this avoids the need to decode and reencode each
+values further because this avoids the need to decode and re-encode each
 component value whenever arithmetic is performed.  A lot of graphics software
 uses linear values for this reason, often with higher precision component values
 to preserve overall accuracy.
 
 The second thing you may need to tell libpng about is how your system handles
 alpha channel information.  Some, but not all, PNG files contain an alpha
 channel.  To display these files correctly you need to compose the data onto a
 suitable background, as described in the PNG specification.
 
 Libpng only supports composing onto a single color (using png_set_background;
 see below).  Otherwise you must do the composition yourself and, in this case,
 you may need to call png_set_alpha_mode:
 
-    #if PNG_LIBPNG_VER >= 10504
-       png_set_alpha_mode(png_ptr, mode, screen_gamma);
-    #else
-       png_set_gamma(png_ptr, screen_gamma, 1.0/screen_gamma);
-    #endif
+   #if PNG_LIBPNG_VER >= 10504
+      png_set_alpha_mode(png_ptr, mode, screen_gamma);
+   #else
+      png_set_gamma(png_ptr, screen_gamma, 1.0/screen_gamma);
+   #endif
 
 The screen_gamma value is the same as the argument to png_set_gamma; however,
 how it affects the output depends on the mode.  png_set_alpha_mode() sets the
 file gamma default to 1/screen_gamma, so normally you don't need to call
 png_set_gamma.  If you need different defaults call png_set_gamma() before
 png_set_alpha_mode() - if you call it after it will override the settings made
 by png_set_alpha_mode().
 
@@ -955,26 +988,26 @@ with
 
 where row_pointers is an array of pointers to the pixel data for each row:
 
    png_bytep row_pointers[height];
 
 If you know your image size and pixel size ahead of time, you can allocate
 row_pointers prior to calling png_read_png() with
 
-   if (height > PNG_UINT_32_MAX/png_sizeof(png_byte))
+   if (height > PNG_UINT_32_MAX/(sizeof (png_byte)))
       png_error (png_ptr,
           "Image is too tall to process in memory");
 
    if (width > PNG_UINT_32_MAX/pixel_size)
       png_error (png_ptr,
           "Image is too wide to process in memory");
 
    row_pointers = png_malloc(png_ptr,
-       height*png_sizeof(png_bytep));
+       height*(sizeof (png_bytep)));
 
    for (int i=0; i<height, i++)
       row_pointers[i]=NULL;  /* security precaution */
 
    for (int i=0; i<height, i++)
       row_pointers[i]=png_malloc(png_ptr,
           width*pixel_size);
 
@@ -1126,57 +1159,65 @@ has been read.  The png_get_valid(png_pt
 png_get_<chunk>(png_ptr, info_ptr, ...) functions return non-zero if the
 data has been read, or zero if it is missing.  The parameters to the
 png_get_<chunk> are set directly if they are simple data types, or a
 pointer into the info_ptr is returned for any complex types.
 
 The colorspace data from gAMA, cHRM, sRGB, iCCP, and sBIT chunks
 is simply returned to give the application information about how the
 image was encoded.  Libpng itself only does transformations using the file
-gamma when combining semitransparent pixels with the background color.
+gamma when combining semitransparent pixels with the background color, and,
+since libpng-1.6.0, when converting between 8-bit sRGB and 16-bit linear pixels
+within the simplified API.  Libpng also uses the file gamma when converting
+RGB to gray, beginning with libpng-1.0.5, if the application calls
+png_set_rgb_to_gray()).
 
     png_get_PLTE(png_ptr, info_ptr, &palette,
                      &num_palette);
 
     palette        - the palette for the file
                      (array of png_color)
 
     num_palette    - number of entries in the palette
 
     png_get_gAMA(png_ptr, info_ptr, &file_gamma);
     png_get_gAMA_fixed(png_ptr, info_ptr, &int_file_gamma);
 
-    file_gamma     - the gamma at which the file was
+    file_gamma     - the gamma at which the file is
                      written (PNG_INFO_gAMA)
 
     int_file_gamma - 100,000 times the gamma at which the
                      file is written
 
     png_get_cHRM(png_ptr, info_ptr,  &white_x, &white_y, &red_x,
                      &red_y, &green_x, &green_y, &blue_x, &blue_y)
-    png_get_cHRM_XYZ(png_ptr, info_ptr, &red_X, &red_Y, &red_Z, &green_X,
-                     &green_Y, &green_Z, &blue_X, &blue_Y, &blue_Z)
-    png_get_cHRM_fixed(png_ptr, info_ptr, &int_white_x, &int_white_y,
-                     &int_red_x, &int_red_y, &int_green_x, &int_green_y,
-                     &int_blue_x, &int_blue_y)
+    png_get_cHRM_XYZ(png_ptr, info_ptr, &red_X, &red_Y, &red_Z,
+                     &green_X, &green_Y, &green_Z, &blue_X, &blue_Y,
+                     &blue_Z)
+    png_get_cHRM_fixed(png_ptr, info_ptr, &int_white_x,
+                     &int_white_y, &int_red_x, &int_red_y,
+                     &int_green_x, &int_green_y, &int_blue_x,
+                     &int_blue_y)
     png_get_cHRM_XYZ_fixed(png_ptr, info_ptr, &int_red_X, &int_red_Y,
-                     &int_red_Z, &int_green_X, &int_green_Y, &int_green_Z,
-                     &int_blue_X, &int_blue_Y, &int_blue_Z)
+                     &int_red_Z, &int_green_X, &int_green_Y,
+                     &int_green_Z, &int_blue_X, &int_blue_Y,
+                     &int_blue_Z)
 
     {white,red,green,blue}_{x,y}
                      A color space encoding specified using the
                      chromaticities of the end points and the
                      white point. (PNG_INFO_cHRM)
 
     {red,green,blue}_{X,Y,Z}
-                     A color space encoding specified using the encoding end
-                     points - the CIE tristimulus specification of the intended
-                     color of the red, green and blue channels in the PNG RGB
-                     data.  The white point is simply the sum of the three end
-                     points. (PNG_INFO_cHRM)
+                     A color space encoding specified using the
+                     encoding end points - the CIE tristimulus
+                     specification of the intended color of the red,
+                     green and blue channels in the PNG RGB data.
+                     The white point is simply the sum of the three
+                     end points. (PNG_INFO_cHRM)
 
     png_get_sRGB(png_ptr, info_ptr, &srgb_intent);
 
     file_srgb_intent - the rendering intent (PNG_INFO_sRGB)
                      The presence of the sRGB chunk
                      means that the pixel data is in the
                      sRGB color space.  This chunk also
                      implies specific values of gAMA and
@@ -2243,17 +2284,17 @@ your application instead of by libpng, y
              PNG_INFO_pCAL, PNG_INFO_sRGB,
              PNG_INFO_iCCP, PNG_INFO_sPLT,
              PNG_INFO_sCAL, PNG_INFO_IDAT
 
 For a more compact example of reading a PNG image, see the file example.c.
 
 Reading PNG files progressively
 
-The progressive reader is slightly different then the non-progressive
+The progressive reader is slightly different from the non-progressive
 reader.  Instead of calling png_read_info(), png_read_rows(), and
 png_read_end(), you make one call to png_process_data(), which calls
 callbacks when it has the info, a row, or the end of the image.  You
 set up these callbacks with png_set_progressive_read_fn().  You don't
 have to worry about the input/output functions of libpng, as you are
 giving the library the data directly in png_process_data().  I will
 assume that you have read the section on reading PNG files above,
 so I will only highlight the differences (although I will show
@@ -2523,16 +2564,30 @@ section below for more information on th
 If you would rather avoid the complexity of setjmp/longjmp issues,
 you can compile libpng with PNG_NO_SETJMP, in which case
 errors will result in a call to PNG_ABORT() which defaults to abort().
 
 You can #define PNG_ABORT() to a function that does something
 more useful than abort(), as long as your function does not
 return.
 
+Checking for invalid palette index on write was added at libpng
+1.5.10.  If a pixel contains an invalid (out-of-range) index libpng issues
+a benign error.  This is enabled by default because this condition is an
+error according to the PNG specification, Clause 11.3.2, but the error can
+be ignored in each png_ptr with
+
+   png_set_check_for_invalid_index(png_ptr, 0);
+
+If the error is ignored, or if png_benign_error() treats it as a warning,
+any invalid pixels are written as-is by the encoder, resulting in an
+invalid PNG datastream as output.  In this case the application is
+responsible for ensuring that the pixel indexes are in range when it writes
+a PLTE chunk with fewer entries than the bit depth would allow.
+
 Now you need to set up the output code.  The default for libpng is to
 use the C function fwrite().  If you use this, you will need to pass a
 valid FILE * in the function png_init_io().  Be sure that the file is
 opened in binary mode.  Again, if you wish to handle writing data in
 another way, see the discussion on libpng I/O handling in the Customizing
 Libpng section below.
 
     png_init_io(png_ptr, fp);
@@ -3025,18 +3080,19 @@ necessary because the "creation time" of
 depending on whether you mean the PNG file, the time the image was
 created in a non-PNG format, a still photo from which the image was
 scanned, or possibly the subject matter itself.  In order to facilitate
 machine-readable dates, it is recommended that the "Creation Time"
 tEXt chunk use RFC 1123 format dates (e.g. "22 May 1997 18:07:10 GMT"),
 although this isn't a requirement.  Unlike the tIME chunk, the
 "Creation Time" tEXt chunk is not expected to be automatically changed
 by the software.  To facilitate the use of RFC 1123 dates, a function
-png_convert_to_rfc1123(png_ptr, png_timep) is provided to convert
-from PNG time to an RFC 1123 format string.
+png_convert_to_rfc1123_buffer(png_ptr, buffer, png_timep) is provided to
+convert from PNG time to an RFC 1123 format string.  The caller must provide
+a writeable buffer of at least 29 bytes.
 
 Writing unknown chunks
 
 You can use the png_set_unknown_chunks function to queue up private chunks
 for writing.  You give it a chunk name, location, raw data, and a size.  You
 also must use png_set_keep_unknown_chunks() to ensure that libpng will
 handle them.  That's all there is to it.  The chunks will be written by the
 next following png_write_info_before_PLTE, png_write_info, or png_write_end
@@ -3057,19 +3113,21 @@ Here is an example of writing two privat
     unk_chunk[1].data = (unsigned char *) "MY CHUNK DATA";
     unk_chunk[1].size = strlen(unk_chunk[0].data)+1;
     unk_chunk[1].location = PNG_AFTER_IDAT;
     png_set_unknown_chunks(write_ptr, write_info_ptr,
         unk_chunk, 2);
     /* Needed because miNE is not safe-to-copy */
     png_set_keep_unknown_chunks(png, PNG_HANDLE_CHUNK_ALWAYS,
        (png_bytep) "miNE", 1);
-    /* Deal with unknown chunk location bug in 1.5.x and earlier */
-    png_set_unknown_chunk_location(png, info, 0, PNG_HAVE_IHDR);
-    png_set_unknown_chunk_location(png, info, 1, PNG_AFTER_IDAT);
+    # if PNG_LIBPNG_VER < 10600
+      /* Deal with unknown chunk location bug in 1.5.x and earlier */
+      png_set_unknown_chunk_location(png, info, 0, PNG_HAVE_IHDR);
+      png_set_unknown_chunk_location(png, info, 1, PNG_AFTER_IDAT);
+    # endif
     # if PNG_LIBPNG_VER < 10500
       /* PNG_AFTER_IDAT writes two copies of the chunk prior to libpng-1.5.0,
        * one before IDAT and another after IDAT, so don't use it; only use
        * PNG_HAVE_IHDR location.  This call resets the location previously
        * set by assignment and png_set_unknown_chunk_location() for chunk 1.
        */
       png_set_unknown_chunk_location(png, info, 1, PNG_HAVE_IHDR);
     # endif
@@ -3466,17 +3524,374 @@ or png_calloc() to allocate it.
 If you allocated text_ptr.text, text_ptr.lang, and text_ptr.translated_keyword
 separately, do not transfer responsibility for freeing text_ptr to libpng,
 because when libpng fills a png_text structure it combines these members with
 the key member, and png_free_data() will free only text_ptr.key.  Similarly,
 if you transfer responsibility for free'ing text_ptr from libpng to your
 application, your application must not separately free those members.
 For a more compact example of writing a PNG image, see the file example.c.
 
-V. Modifying/Customizing libpng:
+V. Simplified API
+
+The simplified API, which became available in libpng-1.6.0, hides the details
+of both libpng and the PNG file format itself.
+It allows PNG files to be read into a very limited number of
+in-memory bitmap formats or to be written from the same formats.  If these
+formats do not accommodate your needs then you can, and should, use the more
+sophisticated APIs above - these support a wide variety of in-memory formats
+and a wide variety of sophisticated transformations to those formats as well
+as a wide variety of APIs to manipulate ancilliary information.
+
+To read a PNG file using the simplified API:
+
+  1) Declare a 'png_image' structure (see below) on the
+     stack and memset() it to all zero.
+
+  2) Call the appropriate png_image_begin_read... function.
+
+  3) Set the png_image 'format' member to the required
+     format and allocate a buffer for the image.
+
+  4) Call png_image_finish_read to read the image into
+     your buffer.
+
+There are no restrictions on the format of the PNG input itself; all valid
+color types, bit depths, and interlace methods are acceptable, and the
+input image is transformed as necessary to the requested in-memory format
+during the png_image_finish_read() step.
+
+To write a PNG file using the simplified API:
+
+  1) Declare a 'png_image' structure on the stack and memset()
+     it to all zero.
+
+  2) Initialize the members of the structure that describe the
+     image, setting the 'format' member to the format of the
+     image in memory.
+
+  3) Call the appropriate png_image_write... function with a
+     pointer to the image to write the PNG data.
+
+png_image is a structure that describes the in-memory format of an image
+when it is being read or define the in-memory format of an image that you
+need to write.  The "png_image" structure contains the following members:
+
+   png_uint_32  version Set to PNG_IMAGE_VERSION
+   png_uint_32  width   Image width in pixels (columns)
+   png_uint_32  height  Image height in pixels (rows)
+   png_uint_32  format  Image format as defined below
+   png_uint_32  flags   A bit mask containing informational flags
+   png_controlp opaque  Initialize to NULL, free with png_image_free
+   png_uint_32  colormap_entries; Number of entries in the color-map
+   png_uint_32  warning_or_error;
+   char         message[64];
+
+In the event of an error or warning the following field warning_or_error
+field will be set to a non-zero value and the 'message' field will contain
+a '\0' terminated string with the libpng error or warning message.  If both
+warnings and an error were encountered, only the error is recorded.  If there
+are multiple warnings, only the first one is recorded.
+
+The upper 30 bits of this value are reserved; the low two bits contain
+a two bit code such that a value more than 1 indicates a failure in the API
+just called:
+
+   0 - no warning or error
+   1 - warning
+   2 - error
+   3 - error preceded by warning
+
+The pixels (samples) of the image have one to four channels whose components
+have original values in the range 0 to 1.0:
+
+  1: A single gray or luminance channel (G).
+  2: A gray/luminance channel and an alpha channel (GA).
+  3: Three red, green, blue color channels (RGB).
+  4: Three color channels and an alpha channel (RGBA).
+
+The channels are encoded in one of two ways:
+
+  a) As a small integer, value 0..255, contained in a single byte.  For the
+alpha channel the original value is simply value/255.  For the color or
+luminance channels the value is encoded according to the sRGB specification
+and matches the 8-bit format expected by typical display devices.
+
+The color/gray channels are not scaled (pre-multiplied) by the alpha
+channel and are suitable for passing to color management software.
+
+  b) As a value in the range 0..65535, contained in a 2-byte integer.  All
+channels can be converted to the original value by dividing by 65535; all
+channels are linear.  Color channels use the RGB encoding (RGB end-points) of
+the sRGB specification.  This encoding is identified by the
+PNG_FORMAT_FLAG_LINEAR flag below.
+
+When an alpha channel is present it is expected to denote pixel coverage
+of the color or luminance channels and is returned as an associated alpha
+channel: the color/gray channels are scaled (pre-multiplied) by the alpha
+value.
+
+When a color-mapped image is used as a result of calling
+png_image_read_colormap or png_image_write_colormap the channels are encoded
+in the color-map and the descriptions above apply to the color-map entries.
+The image data is encoded as small integers, value 0..255, that index the
+entries in the color-map.  One integer (one byte) is stored for each pixel.
+
+PNG_FORMAT_*
+
+The #defines to be used in png_image::format.  Each #define identifies a
+particular layout of channel data and, if present, alpha values.  There are
+separate defines for each of the two channel encodings.
+
+A format is built up using single bit flag values.  Not all combinations are
+valid: use the bit flag values below for testing a format returned by the
+read APIs, but set formats from the derived values.
+
+When reading or writing color-mapped images the format should be set to the
+format of the entries in the color-map then png_image_{read,write}_colormap
+called to read or write the color-map and set the format correctly for the
+image data.  Do not set the PNG_FORMAT_FLAG_COLORMAP bit directly!
+
+NOTE: libpng can be built with particular features disabled, if you see
+compiler errors because the definition of one of the following flags has been
+compiled out it is because libpng does not have the required support.  It is
+possible, however, for the libpng configuration to enable the format on just
+read or just write; in that case you may see an error at run time.  You can
+guard against this by checking for the definition of:
+
+   PNG_SIMPLIFIED_{READ,WRITE}_{BGR,AFIRST}_SUPPORTED
+
+   PNG_FORMAT_FLAG_ALPHA    0x01 format with an alpha channel
+   PNG_FORMAT_FLAG_COLOR    0x02 color format: otherwise grayscale
+   PNG_FORMAT_FLAG_LINEAR   0x04 png_uint_16 channels else png_byte
+   PNG_FORMAT_FLAG_COLORMAP 0x08 libpng use only
+   PNG_FORMAT_FLAG_BGR      0x10 BGR colors, else order is RGB
+   PNG_FORMAT_FLAG_AFIRST   0x20 alpha channel comes first
+
+Supported formats are as follows.  Future versions of libpng may support more
+formats; for compatibility with older versions simply check if the format
+macro is defined using #ifdef.  These defines describe the in-memory layout
+of the components of the pixels of the image.
+
+First the single byte formats:
+
+   PNG_FORMAT_GRAY 0
+   PNG_FORMAT_GA   PNG_FORMAT_FLAG_ALPHA
+   PNG_FORMAT_AG   (PNG_FORMAT_GA|PNG_FORMAT_FLAG_AFIRST)
+   PNG_FORMAT_RGB  PNG_FORMAT_FLAG_COLOR
+   PNG_FORMAT_BGR  (PNG_FORMAT_FLAG_COLOR|PNG_FORMAT_FLAG_BGR)
+   PNG_FORMAT_RGBA (PNG_FORMAT_RGB|PNG_FORMAT_FLAG_ALPHA)
+   PNG_FORMAT_ARGB (PNG_FORMAT_RGBA|PNG_FORMAT_FLAG_AFIRST)
+   PNG_FORMAT_BGRA (PNG_FORMAT_BGR|PNG_FORMAT_FLAG_ALPHA)
+   PNG_FORMAT_ABGR (PNG_FORMAT_BGRA|PNG_FORMAT_FLAG_AFIRST)
+
+Then the linear 2-byte formats.  When naming these "Y" is used to
+indicate a luminance (gray) channel.  The component order within the pixel
+is always the same - there is no provision for swapping the order of the
+components in the linear format.
+
+   PNG_FORMAT_LINEAR_Y PNG_FORMAT_FLAG_LINEAR
+   PNG_FORMAT_LINEAR_Y_ALPHA
+      (PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_ALPHA)
+   PNG_FORMAT_LINEAR_RGB
+      (PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_COLOR)
+   PNG_FORMAT_LINEAR_RGB_ALPHA
+      (PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_COLOR|
+      PNG_FORMAT_FLAG_ALPHA)
+
+Color-mapped formats are obtained by calling png_image_{read,write}_colormap,
+as appropriate after setting png_image::format to the format of the color-map
+to be read or written.  Applications may check the value of
+PNG_FORMAT_FLAG_COLORMAP to see if they have called the colormap API.  The
+format of the color-map may be extracted using the following macro.
+
+   PNG_FORMAT_OF_COLORMAP(fmt) ((fmt) & ~PNG_FORMAT_FLAG_COLORMAP)
+
+PNG_IMAGE macros
+
+These are convenience macros to derive information from a png_image
+structure.  The PNG_IMAGE_SAMPLE_ macros return values appropriate to the
+actual image sample values - either the entries in the color-map or the
+pixels in the image.  The PNG_IMAGE_PIXEL_ macros return corresponding values
+for the pixels and will always return 1 after a call to
+png_image_{read,write}_colormap.  The remaining macros return information
+about the rows in the image and the complete image.
+
+NOTE: All the macros that take a png_image::format parameter are compile time
+constants if the format parameter is, itself, a constant.  Therefore these
+macros can be used in array declarations and case labels where required.
+Similarly the macros are also pre-processor constants (sizeof is not used) so
+they can be used in #if tests.
+
+First the information about the samples.
+
+  PNG_IMAGE_SAMPLE_CHANNELS(fmt)
+    Returns the total number of channels in a given format: 1..4
+
+  PNG_IMAGE_SAMPLE_COMPONENT_SIZE(fmt)
+    Returns the size in bytes of a single component of a pixel or color-map
+    entry (as appropriate) in the image.
+
+  PNG_IMAGE_SAMPLE_SIZE(fmt)
+    This is the size of the sample data for one sample.  If the image is
+    color-mapped it is the size of one color-map entry (and image pixels are
+    one byte in size), otherwise it is the size of one image pixel.
+
+  PNG_IMAGE_COLORMAP_SIZE(fmt)
+   The size of the color-map required by the format; this is the size of the
+   color-map buffer passed to the png_image_{read,write}_colormap APIs, it is
+   a fixed number determined by the format so can easily be allocated on the
+   stack if necessary.
+
+#define PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(fmt)\
+   (PNG_IMAGE_SAMPLE_CHANNELS(fmt) * 256)
+   /* The maximum size of the color-map required by the format expressed in a
+    * count of components.  This can be used to compile-time allocate a
+    * color-map:
+    *
+    * png_uint_16 colormap[PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(linear_fmt)];
+    *
+    * png_byte colormap[PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(sRGB_fmt)];
+    *
+    * Alternatively use the PNG_IMAGE_COLORMAP_SIZE macro below to use the
+    * information from one of the png_image_begin_read_ APIs and dynamically
+    * allocate the required memory.
+    */
+
+
+Corresponding information about the pixels
+
+  PNG_IMAGE_PIXEL_(test,fmt)
+
+  PNG_IMAGE_PIXEL_CHANNELS(fmt)
+   The number of separate channels (components) in a pixel; 1 for a
+   color-mapped image.
+
+  PNG_IMAGE_PIXEL_COMPONENT_SIZE(fmt)\
+   The size, in bytes, of each component in a pixel; 1 for a color-mapped
+   image.
+
+  PNG_IMAGE_PIXEL_SIZE(fmt)
+   The size, in bytes, of a complete pixel; 1 for a color-mapped image.
+
+Information about the whole row, or whole image
+
+  PNG_IMAGE_ROW_STRIDE(image)
+   Returns the total number of components in a single row of the image; this
+   is the minimum 'row stride', the minimum count of components between each
+   row.  For a color-mapped image this is the minimum number of bytes in a
+   row.
+
+  PNG_IMAGE_BUFFER_SIZE(image, row_stride)
+    Returns the size, in bytes, of an image buffer given a png_image and a row
+    stride - the number of components to leave space for in each row.
+
+  PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB == 0x01
+    This indicates the the RGB values of the in-memory bitmap do not
+    correspond to the red, green and blue end-points defined by sRGB.
+
+  PNG_IMAGE_FLAG_COLORMAP == 0x02
+    The PNG is color-mapped.  If this flag is set png_image_read_colormap
+    can be used without further loss of image information.  If it is not set
+    png_image_read_colormap will cause significant loss if the image has any
+
+READ APIs
+
+   The png_image passed to the read APIs must have been initialized by setting
+   the png_controlp field 'opaque' to NULL (or, better, memset the whole thing.)
+
+   int png_image_begin_read_from_file( png_imagep image,
+     const char *file_name)
+
+     The named file is opened for read and the image header
+     is filled in from the PNG header in the file.
+
+   int png_image_begin_read_from_stdio (png_imagep image,
+     FILE* file)
+
+      The PNG header is read from the stdio FILE object.
+
+   int png_image_begin_read_from_memory(png_imagep image,
+      png_const_voidp memory, png_size_t size)
+
+      The PNG header is read from the given memory buffer.
+
+   int png_image_finish_read(png_imagep image,
+      png_colorp background, void *buffer,
+      png_int_32 row_stride, void *colormap));
+
+      Finish reading the image into the supplied buffer and
+      clean up the png_image structure.
+
+      row_stride is the step, in png_byte or png_uint_16 units
+      as appropriate, between adjacent rows.  A positive stride
+      indicates that the top-most row is first in the buffer -
+      the normal top-down arrangement.  A negative stride
+      indicates that the bottom-most row is first in the buffer.
+
+      background need only be supplied if an alpha channel must
+      be removed from a png_byte format and the removal is to be
+      done by compositing on a solid color; otherwise it may be
+      NULL and any composition will be done directly onto the
+      buffer.  The value is an sRGB color to use for the
+      background, for grayscale output the green channel is used.
+
+      For linear output removing the alpha channel is always done
+      by compositing on black.
+
+   void png_image_free(png_imagep image)
+
+      Free any data allocated by libpng in image->opaque,
+      setting the pointer to NULL.  May be called at any time
+      after the structure is initialized.
+
+When the simplified API needs to convert between sRGB and linear colorspaces,
+the actual sRGB transfer curve defined in the sRGB specification (see the
+article at http://en.wikipedia.org/wiki/SRGB) is used, not the gamma=1/2.2
+approximation used elsewhere in libpng.
+
+WRITE APIS
+
+For write you must initialize a png_image structure to describe the image to
+be written:
+
+   version: must be set to PNG_IMAGE_VERSION
+   opaque: must be initialized to NULL
+   width: image width in pixels
+   height: image height in rows
+   format: the format of the data you wish to write
+   flags: set to 0 unless one of the defined flags applies; set
+      PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB for color format images
+      where the RGB values do not correspond to the colors in sRGB.
+   colormap_entries: set to the number of entries in the color-map (0 to 256)
+
+   int png_image_write_to_file, (png_imagep image,
+      const char *file, int convert_to_8bit, const void *buffer,
+      png_int_32 row_stride, const void *colormap));
+
+      Write the image to the named file.
+
+   int png_image_write_to_stdio(png_imagep image, FILE *file,
+      int convert_to_8_bit, const void *buffer,
+      png_int_32 row_stride, const void *colormap)
+
+      Write the image to the given (FILE*).
+
+With all write APIs if image is in one of the linear formats with
+(png_uint_16) data then setting convert_to_8_bit will cause the output to be
+a (png_byte) PNG gamma encoded according to the sRGB specification, otherwise
+a 16-bit linear encoded PNG file is written.
+
+With all APIs row_stride is handled as in the read APIs - it is the spacing
+from one row to the next in component sized units (float) and if negative
+indicates a bottom-up row layout in the buffer.
+
+Note that the write API does not support interlacing, sub-8-bit pixels,
+and indexed (paletted) images.
+
+VI. Modifying/Customizing libpng
 
 There are two issues here.  The first is changing how libpng does
 standard things like memory allocation, input/output, and error handling.
 The second deals with more complicated things like adding new chunks,
 adding new transformations, and generally changing how libpng works.
 Both of those are compile-time issues; that is, they are generally
 determined at the time the code is written, and there is rarely a need
 to provide the user with a means of changing them.
@@ -3600,16 +4015,28 @@ catch exception handling methods.  This 
 as there is no need to check every return code of every function call.
 However, there are some uncertainties about the status of local variables
 after a longjmp, so the user may want to be careful about doing anything
 after setjmp returns non-zero besides returning itself.  Consult your
 compiler documentation for more details.  For an alternative approach, you
 may wish to use the "cexcept" facility (see http://cexcept.sourceforge.net),
 which is illustrated in pngvalid.c and in contrib/visupng.
 
+Beginning in libpng-1.4.0, the png_set_benign_errors() API became available.
+You can use this to handle certain errors (normally handled as errors)
+as warnings.
+
+    png_set_benign_errors (png_ptr, int allowed);
+
+    allowed: 0: treat png_benign_error() as an error.
+             1: treat png_benign_error() as a warning.
+
+As of libpng-1.6.0, the default condition is to treat benign errors as
+warnings while reading and as errors while writing.
+
 Custom chunks
 
 If you need to read or write custom chunks, you may need to get deeper
 into the libpng code.  The library now has mechanisms for storing
 and writing chunks of unknown type; you can even declare callbacks
 for custom chunks.  However, this may not be good enough if the
 library code itself needs to know about interactions between your
 chunk and existing `intrinsic' chunks.
@@ -3870,17 +4297,17 @@ When PNG_DEBUG > 0, the following functi
    png_debug1(level, message, p1)
    png_debug2(level, message, p1, p2)
 
 in which "level" is compared to PNG_DEBUG to decide whether to print
 the message, "message" is the formatted string to be printed,
 and p1 and p2 are parameters that are to be embedded in the string
 according to printf-style formatting directives.  For example,
 
-   png_debug1(2, "foo=%d\n", foo);
+   png_debug1(2, "foo=%d", foo);
 
 is expanded to
 
    if (PNG_DEBUG > 2)
       fprintf(PNG_DEBUG_FILE, "foo=%d\n", foo);
 
 When PNG_DEBUG is defined but is zero, the macros aren't defined, but you
 can still use PNG_DEBUG to control your own debugging:
@@ -3888,17 +4315,28 @@ can still use PNG_DEBUG to control your 
    #ifdef PNG_DEBUG
        fprintf(stderr, ...
    #endif
 
 When PNG_DEBUG = 1, the macros are defined, but only png_debug statements
 having level = 0 will be printed.  There aren't any such statements in
 this version of libpng, but if you insert some they will be printed.
 
-VI.  MNG support
+Prepending a prefix to exported symbols
+
+Starting with libpng-1.6.0, you can configure libpng (when using the
+"configure" script) to prefix all exported symbols by means of the
+configuration option "--with-libpng-prefix=FOO_", where FOO_ can be any
+string beginning with a letter and containing only uppercase
+and lowercase letters, digits, and the underscore (i.e., a C language
+identifier).  This creates a set of macros in pnglibconf.h, so this is
+transparent to applications; their function calls get transformed by
+the macros to use the modified names.
+
+VII.  MNG support
 
 The MNG specification (available at http://www.libpng.org/pub/mng) allows
 certain extensions to PNG for PNG images that are embedded in MNG datastreams.
 Libpng can support some of these extensions.  To enable them, use the
 png_permit_mng_features() function:
 
    feature_set = png_permit_mng_features(png_ptr, mask)
 
@@ -3915,17 +4353,17 @@ png_permit_mng_features() function:
 It is an error to use this function when reading or writing a standalone
 PNG file with the PNG 8-byte signature.  The PNG datastream must be wrapped
 in a MNG datastream.  As a minimum, it must have the MNG 8-byte signature
 and the MHDR and MEND chunks.  Libpng does not provide support for these
 or any other MNG chunks; your application must provide its own support for
 them.  You may wish to consider using libmng (available at
 http://www.libmng.com) instead.
 
-VII.  Changes to Libpng from version 0.88
+VIII.  Changes to Libpng from version 0.88
 
 It should be noted that versions of libpng later than 0.96 are not
 distributed by the original libpng author, Guy Schalnat, nor by
 Andreas Dilger, who had taken over from Guy during 1996 and 1997, and
 distributed versions 0.89 through 0.96, but rather by another member
 of the original PNG Group, Glenn Randers-Pehrson.  Guy and Andreas are
 still alive and well, but they have moved on to other things.
 
@@ -3967,17 +4405,17 @@ version with leading zero, and release n
 Note that this function does not take a png_ptr, so you can call it
 before you've created one.
 
 You can also check which version of png.h you used when compiling your
 application:
 
    png_uint_32 application_vn = PNG_LIBPNG_VER;
 
-VIII.  Changes to Libpng from version 1.0.x to 1.2.x
+IX.  Changes to Libpng from version 1.0.x to 1.2.x
 
 Support for user memory management was enabled by default.  To
 accomplish this, the functions png_create_read_struct_2(),
 png_create_write_struct_2(), png_set_mem_fn(), png_get_mem_ptr(),
 png_malloc_default(), and png_free_default() were added.
 
 Support for the iTXt chunk has been enabled by default as of
 version 1.2.41.
@@ -4064,17 +4502,17 @@ was replaced with
 It has been deprecated since libpng-0.90.
 
 The function
     png_set_gray_1_2_4_to_8()
 which also expands tRNS to alpha was replaced with
     png_set_expand_gray_1_2_4_to_8()
 which does not. It has been deprecated since libpng-1.0.18 and 1.2.9.
 
-IX.  Changes to Libpng from version 1.0.x/1.2.x to 1.4.x
+X.  Changes to Libpng from version 1.0.x/1.2.x to 1.4.x
 
 Private libpng prototypes and macro definitions were moved from
 png.h and pngconf.h into a new pngpriv.h header file.
 
 Functions png_set_benign_errors(), png_benign_error(), and
 png_chunk_benign_error() were added.
 
 Support for setting the maximum amount of memory that the application
@@ -4119,18 +4557,18 @@ The png_permit_empty_plte() was removed.
 since libpng-1.0.9.  Use png_permit_mng_features() instead.
 
 We removed the obsolete stub functions png_get_mmx_flagmask(),
 png_set_mmx_thresholds(), png_get_asm_flags(),
 png_get_mmx_bitdepth_threshold(), png_get_mmx_rowbytes_threshold(),
 png_set_asm_flags(), and png_mmx_supported()
 
 We removed the obsolete png_check_sig(), png_memcpy_check(), and
-png_memset_check() functions.  Instead use !png_sig_cmp(), png_memcpy(),
-and png_memset(), respectively.
+png_memset_check() functions.  Instead use !png_sig_cmp(), memcpy(),
+and memset(), respectively.
 
 The function png_set_gray_1_2_4_to_8() was removed. It has been
 deprecated since libpng-1.0.18 and 1.2.9, when it was replaced with
 png_set_expand_gray_1_2_4_to_8() because the former function also
 expanded any tRNS chunk to an alpha channel.
 
 Macros for png_get_uint_16, png_get_uint_32, and png_get_int_32
 were added and are used by default instead of the corresponding
@@ -4166,38 +4604,47 @@ allocates.  Applications that called png
 can call png_calloc(png_ptr, number*size) instead, and can call
 png_free() instead of png_zfree().
 
 Support for dithering was disabled by default in libpng-1.4.0, because
 it has not been well tested and doesn't actually "dither".
 The code was not
 removed, however, and could be enabled by building libpng with
 PNG_READ_DITHER_SUPPORTED defined.  In libpng-1.4.2, this support
-was reenabled, but the function was renamed png_set_quantize() to
+was re-enabled, but the function was renamed png_set_quantize() to
 reflect more accurately what it actually does.  At the same time,
 the PNG_DITHER_[RED,GREEN_BLUE]_BITS macros were also renamed to
 PNG_QUANTIZE_[RED,GREEN,BLUE]_BITS, and PNG_READ_DITHER_SUPPORTED
 was renamed to PNG_READ_QUANTIZE_SUPPORTED.
 
 We removed the trailing '.' from the warning and error messages.
 
-X.  Changes to Libpng from version 1.4.x to 1.5.x
+XI.  Changes to Libpng from version 1.4.x to 1.5.x
 
 From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the
 function) incorrectly returned a value of type png_uint_32.
 
 Checking for invalid palette index on read or write was added at libpng
 1.5.10.  When an invalid index is found, libpng issues a benign error.
-This is enabled by default but can be disabled in each png_ptr with
+This is enabled by default because this condition is an error according
+to the PNG specification, Clause 11.3.2, but the error can be ignored in
+each png_ptr with
 
    png_set_check_for_invalid_index(png_ptr, allowed);
 
       allowed  - one of
-                 0: disable
-                 1: enable
+                 0: disable benign error (accept the
+                    invalid data without warning).
+                 1: enable benign error (treat the
+                    invalid data as an error or a
+                    warning).
+
+If the error is ignored, or if png_benign_error() treats it as a warning,
+any invalid pixels are decoded as opaque black by the decoder and written
+as-is by the encoder.
 
 Retrieving the maximum palette index found was added at libpng-1.5.15.
 This statement must appear after png_read_png() or png_read_image() while
 reading, and after png_write_png() or png_write_image() while writing.
 
    int max_palette = png_get_palette_max(png_ptr, info_ptr);
 
 This will return the maximum palette index found in the image, or "-1" if
@@ -4209,19 +4656,20 @@ palette index actually used.
 A. Changes that affect users of libpng
 
 There are no substantial API changes between the non-deprecated parts of
 the 1.4.5 API and the 1.5.0 API; however, the ability to directly access
 members of the main libpng control structures, png_struct and png_info,
 deprecated in earlier versions of libpng, has been completely removed from
 libpng 1.5.
 
-We no longer include zlib.h in png.h.  Applications that need access
-to information in zlib.h will need to add the '#include "zlib.h"'
-directive.  It does not matter whether it is placed prior to or after
+We no longer include zlib.h in png.h.  The include statement has been moved
+to pngstruct.h, where it is not accessible by applications. Applications that
+need access to information in zlib.h will need to add the '#include "zlib.h"'
+directive.  It does not matter whether this is placed prior to or after
 the '"#include png.h"' directive.
 
 The png_sprintf(), png_strcpy(), and png_strncpy() macros are no longer used
 and were removed.
 
 We moved the png_strlen(), png_memcpy(), png_memset(), and png_memcmp()
 macros into a private header file (pngpriv.h) that is not accessible to
 applications.
@@ -4300,17 +4748,17 @@ of macro redefinition.
 From libpng-1.4.0 until 1.4.4, the png_get_uint_16 macro (but not the
 function) incorrectly returned a value of type png_uint_32.  libpng 1.5.0
 is consistent with the implementation in 1.4.5 and 1.2.x (where the macro
 did not exist.)
 
 Applications can now choose whether to use these macros or to call the
 corresponding function by defining PNG_USE_READ_MACROS or
 PNG_NO_USE_READ_MACROS before including png.h.  Notice that this is
-only supported from 1.5.0 -defining PNG_NO_USE_READ_MACROS prior to 1.5.0
+only supported from 1.5.0; defining PNG_NO_USE_READ_MACROS prior to 1.5.0
 will lead to a link failure.
 
 Prior to libpng-1.5.4, the zlib compressor used the same set of parameters
 when compressing the IDAT data and textual data such as zTXt and iCCP.
 In libpng-1.5.4 we reinitialized the zlib stream for each type of data.
 We added five png_set_text_*() functions for setting the parameters to
 use with textual data.
 
@@ -4336,16 +4784,19 @@ in libpng-1.5.10 the default width and h
 from 1,000,000 to 0x7ffffff (i.e., made unlimited).  Therefore, the
 limits are now
                                default      safe
    png_user_width_max        0x7fffffff    1,000,000
    png_user_height_max       0x7fffffff    1,000,000
    png_user_chunk_cache_max  0 (unlimited)   128
    png_user_chunk_malloc_max 0 (unlimited) 8,000,000
 
+The png_set_option() function (and the "options" member of the png struct) was
+added to libpng-1.5.15.
+
 B. Changes to the build and configuration of libpng
 
 Details of internal changes to the library code can be found in the CHANGES
 file and in the GIT repository logs.  These will be of no concern to the vast
 majority of library users or builders; however, the few who configure libpng
 to a non-default feature set may need to change how this is done.
 
 There should be no need for library builders to alter build scripts if
@@ -4502,50 +4953,159 @@ Configuration options are now documented
 file also includes dependency information that ensures a configuration is
 consistent; that is, if a feature is switched off dependent features are
 also removed.  As a recommended alternative to using feature macros in
 pngusr.h a system builder may also define equivalent options in pngusr.dfa
 (or, indeed, any file) and add that to the configuration by setting
 DFA_XTRA to the file name.  The makefiles in contrib/pngminim illustrate
 how to do this, and a case where pngusr.h is still required.
 
-XI. Detecting libpng
+XII.  Changes to Libpng from version 1.5.x to 1.6.x
+
+A "simplified API" has been added (see documentation in png.h and a simple
+example in contrib/examples/pngtopng.c).  The new publicly visible API
+includes the following:
+
+   macros:
+     PNG_FORMAT_*
+     PNG_IMAGE_*
+   structures:
+     png_control
+     png_image
+   read functions
+     png_image_begin_read_from_file()
+     png_image_begin_read_from_stdio()
+     png_image_begin_read_from_memory()
+     png_image_finish_read()
+     png_image_free()
+   write functions
+     png_image_write_to_file()
+     png_image_write_to_stdio()
+
+Starting with libpng-1.6.0, you can configure libpng to prefix all exported
+symbols, using the PNG_PREFIX macro.
+
+We no longer include string.h in png.h.  The include statement has been moved
+to pngpriv.h, where it is not accessible by applications.  Applications that
+need access to information in string.h must add an '#include <string.h>'
+directive.  It does not matter whether this is placed prior to or after
+the '#include "png.h"' directive.
+
+The following API are now DEPRECATED:
+   png_info_init_3()
+   png_convert_to_rfc1123() which has been replaced
+     with png_convert_to_rfc1123_buffer()
+   png_data_freer()
+   png_malloc_default()
+   png_free_default()
+   png_reset_zstream()
+
+The following have been removed:
+   png_get_io_chunk_name(), which has been replaced
+     with png_get_io_chunk_type().  The new
+     function returns a 32-bit integer instead of
+     a string.
+   The png_sizeof(), png_strlen(), png_memcpy(), png_memcmp(), and
+     png_memset() macros are no longer used in the libpng sources and
+     have been removed.  These had already been made invisible to applications
+     (i.e., defined in the private pngpriv.h header file) since libpng-1.5.0.
+
+The signatures of many exported functions were changed, such that
+   png_structp became png_structrp or png_const_structrp
+   png_infop became png_inforp or png_const_inforp
+where "rp" indicates a "restricted pointer".
+
+Error detection in some chunks has improved; in particular the iCCP chunk
+reader now does pretty complete validation of the basic format.  Some bad
+profiles that were previously accepted are now rejected, in particular the
+very old broken Microsoft/HP sRGB profile.  The PNG spec requirement that
+only grayscale profiles may appear in images with color type 0 or 4 and that
+even if the image only contains gray pixels, only RGB profiles may appear
+in images with color type 2, 3, or 6, is now enforced.  The sRGB chunk
+is allowed to appear in images with any color type.
+
+Prior to libpng-1.6.0 a warning would be issued if the iTXt chunk contained
+an empty language field or an empty translated keyword.  Both of these
+are allowed by the PNG specification, so these warnings are no longer issued.
+
+The library now issues an error if the application attempts to set a
+transform after it calls png_read_update_info().
+
+The default condition for benign_errors is now to treat benign errors as
+warnings while reading and as errors while writing.
+
+The library now issues a warning if both background processing and RGB to
+gray are used when gamma correction happens. As with previous versions of
+the library the results are numerically very incorrect in this case.
+
+There are some minor arithmetic changes in some transforms such as
+png_set_background(), that might be detected by certain regression tests.
+
+Unknown chunk handling has been improved internally, without any API change.
+This adds more correct option control of the unknown handling, corrects
+a pre-existing bug where the per-chunk 'keep' setting is ignored, and makes
+it possible to skip IDAT chunks in the sequential reader.
+
+The machine-generated configure files are no longer included in branches
+libpng16 and later of the GIT repository.  They continue to be included
+in the tarball releases, however.
+
+Libpng-1.6.0 and later use the CMF bytes at the beginning of the IDAT stream
+to set the size of the sliding window for reading instead of using the default
+32-kbyte sliding window size.  It was discovered that there are hundreds of PNG
+files in the wild that have incorrect CMF bytes that cause libpng to now issue
+a "too far back" error and reject the file.  Libpng-1.6.3 provides a way to
+revert to the libpng-1.5.x behavior (ignoring the CMF bytes and using a
+32-kbyte sliding window), by using
+
+    png_set_option(png_ptr, PNG_MAXIMUM_INFLATE_WINDOW,
+        PNG_OPTION_ON);
+
+and provides a tool (contrib/tools/pngfix) for optimizing the CMF bytes
+correctly.
+
+Libpng-1.6.0 and libpng-1.6.1 wrote uncompressed iTXt chunks with the wrong
+length, which resulted in PNG files that cannot be read beyond the bad iTXt
+chunk.  This error was fixed in libpng-1.6.3, and a tool (called
+contrib/tools/png-fix-itxt) has been added to the libpng distribution.
+
+XIII.  Detecting libpng
 
 The png_get_io_ptr() function has been present since libpng-0.88, has never
 changed, and is unaffected by conditional compilation macros.  It is the
 best choice for use in configure scripts for detecting the presence of any
 libpng version since 0.88.  In an autoconf "configure.in" you could use
 
     AC_CHECK_LIB(png, png_get_io_ptr, ...
 
-XII. Source code repository
+XV. Source code repository
 
 Since about February 2009, version 1.2.34, libpng has been under "git" source
 control.  The git repository was built from old libpng-x.y.z.tar.gz files
 going back to version 0.70.  You can access the git repository (read only)
 at
 
     git://git.code.sf.net/p/libpng/code
 
 or you can browse it with a web browser by selecting the "code" button at
 
-    https://sourceforge.net/projects/libpng/
+    https://sourceforge.net/projects/libpng
 
 Patches can be sent to glennrp at users.sourceforge.net or to
 png-mng-implement at lists.sourceforge.net or you can upload them to
 the libpng bug tracker at
 
     http://libpng.sourceforge.net
 
 We also accept patches built from the tar or zip distributions, and
 simple verbal discriptions of bug fixes, reported either to the
 SourceForge bug tracker, to the png-mng-implement at lists.sf.net
 mailing list, or directly to glennrp.
 
-XIII. Coding style
+XV. Coding style
 
 Our coding style is similar to the "Allman" style, with curly
 braces on separate lines:
 
     if (condition)
     {
        action;
     }
@@ -4620,16 +5180,27 @@ We mark all non-exported functions with 
 
 The prototypes for non-exported functions (except for those in
 pngtest) appear in
 pngpriv.h
 above the comment that says
 
   /* Maintainer: Put new private prototypes here ^ */
 
+We put a space after the "sizeof" operator and we omit the
+optional parentheses around its argument when the argument
+is an expression, not a type name, and we always enclose the
+sizeof operator, with its argument, in parentheses:
+
+  (sizeof (png_uint_32))
+  (sizeof array)
+
+Prior to libpng-1.6.0 we used a "png_sizeof()" macro, formatted as
+though it were a function.
+
 To avoid polluting the global namespace, the names of all exported
 functions and variables begin with "png_", and all publicly visible C
 preprocessor macros begin with "PNG".  We request that applications that
 use libpng *not* begin any of their own symbols with either of these strings.
 
 We put a space after each comma and after each semicolon
 in "for" statements, and we put spaces before and after each
 C binary operator and after "for" or "while", and before
@@ -4642,43 +5213,46 @@ left parenthesis that follows it:
 
 We prefer #ifdef and #ifndef to #if defined() and #if !defined()
 when there is only one macro being tested.  We always use parentheses
 with "defined".
 
 We prefer to express integers that are used as bit masks in hex format,
 with an even number of lower-case hex digits (e.g., 0x00, 0xff, 0x0100).
 
+We prefer to use underscores in variable names rather than camelCase, except
+for a few type names that we inherit from zlib.h.
+
 We do not use the TAB character for indentation in the C sources.
 
 Lines do not exceed 80 characters.
 
 Other rules can be inferred by inspecting the libpng source.
 
-XIV. Y2K Compliance in libpng
-
-May 23, 2013
+XVI. Y2K Compliance in libpng
+
+September 16, 2013
 
 Since the PNG Development group is an ad-hoc body, we can't make
 an official declaration.
 
 This is your unofficial assurance that libpng from version 0.71 and
-upward through 1.5.16 are Y2K compliant.  It is my belief that earlier
+upward through 1.6.6 are Y2K compliant.  It is my belief that earlier
 versions were also Y2K compliant.
 
-Libpng only has two year fields.  One is a 2-byte unsigned integer that
-will hold years up to 65535.  The other holds the date in text
-format, and will hold years up to 9999.
+Libpng only has two year fields.  One is a 2-byte unsigned integer
+that will hold years up to 65535.  The other, which is deprecated,
+holds the date in text format, and will hold years up to 9999.
 
 The integer is
     "png_uint_16 year" in png_time_struct.
 
 The string is
-    "char time_buffer[29]" in png_struct.  This will no
-longer be used in libpng-1.6.x and will be removed from libpng-1.7.0.
+    "char time_buffer[29]" in png_struct.  This is no longer used
+in libpng-1.6.x and will be removed from libpng-1.7.0.
 
 There are seven time-related functions:
 
     png_convert_to_rfc_1123() in png.c
       (formerly png_convert_to_rfc_1152() in error)
     png_convert_from_struct_tm() in pngwrite.c, called
       in pngwrite.c
     png_convert_from_time_t() in pngwrite.c
--- a/media/libpng/mozpngconf.h
+++ b/media/libpng/mozpngconf.h
@@ -1,38 +1,45 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef MOZPNGCONF_H
 #define MOZPNGCONF_H
+#define PNGLCONF_H /* So we don't try to use libpng's pnglibconf.h */
 
 #define PNG_API_RULE 0
 #define PNG_COST_SHIFT 3
 #define PNG_GAMMA_THRESHOLD_FIXED 5000
 #define PNG_MAX_GAMMA_8 11
 #define PNG_USER_CHUNK_CACHE_MAX 128
 #define PNG_USER_CHUNK_MALLOC_MAX 4000000L
 #define PNG_USER_HEIGHT_MAX 1000000
 #define PNG_USER_WIDTH_MAX 1000000
 #define PNG_WEIGHT_SHIFT 8
 #define PNG_ZBUF_SIZE 8192
+#define PNG_IDAT_READ_SIZE PNG_ZBUF_SIZE
+#define PNG_INFLATE_BUF_SIZE 1024
+#define PNG_Z_DEFAULT_COMPRESSION (-1)
+#define PNG_Z_DEFAULT_NOFILTER_STRATEGY 0
+#define PNG_Z_DEFAULT_STRATEGY 1
+
 
 #ifdef _MSC_VER
 /* The PNG_PEDANTIC_WARNINGS (attributes) fail to build with some MSC
  * compilers; we'll play it safe and disable them for all MSC compilers.
  */
 #define PNG_NO_PEDANTIC_WARNINGS
 #endif
 
-#ifdef __ARM_NEON__
-#  define PNG_ALIGNED_MEMORY_SUPPORTED
-#endif
+#undef PNG_ARM_NEON_OPT /* This may have been defined in pngpriv.h */
+#define PNG_ARM_NEON_OPT 0
 
 #ifdef MOZ_PNG_READ
+#define PNG_BENIGN_READ_ERRORS_SUPPORTED
 #define PNG_READ_SUPPORTED
 #define PNG_READ_APNG_SUPPORTED
 #define PNG_READ_cHRM_SUPPORTED
 #define PNG_READ_gAMA_SUPPORTED
 #define PNG_READ_iCCP_SUPPORTED
 #define PNG_READ_sRGB_SUPPORTED
 #define PNG_READ_tRNS_SUPPORTED
 #define PNG_READ_16BIT_SUPPORTED
@@ -45,18 +52,21 @@
 #define PNG_READ_INTERLACING_SUPPORTED
 #define PNG_READ_SCALE_16_TO_8_SUPPORTED
 #define PNG_READ_TRANSFORMS_SUPPORTED
 #endif
 
 /* necessary for boot animation code */
 #ifdef MOZ_WIDGET_GONK
 #define PNG_EASY_ACCESS_SUPPORTED
+#define PNG_UNKNOWN_CHUNKS_SUPPORTED
+#define PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
 #define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
 #define PNG_READ_BGR_SUPPORTED
+#define PNG_BENIGN_READ_ERRORS_SUPPORTED
 #define PNG_READ_EXPAND_SUPPORTED
 #define PNG_READ_FILLER_SUPPORTED
 #define PNG_READ_GRAY_TO_RGB_SUPPORTED
 #define PNG_READ_STRIP_16_TO_8_SUPPORTED
 #define PNG_READ_STRIP_ALPHA_SUPPORTED
 #define PNG_READ_USER_TRANSFORM_SUPPORTED
 #define PNG_SEQUENTIAL_READ_SUPPORTED
 #endif
@@ -68,34 +78,36 @@
 #define PNG_WRITE_16BIT_SUPPORTED
 #define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
 #define PNG_WRITE_FLUSH_SUPPORTED
 #define PNG_WRITE_OPTIMIZE_CMF_SUPPORTED
 #define PNG_WRITE_INT_FUNCTIONS_SUPPORTED
 #endif
 
 #define PNG_APNG_SUPPORTED
+#define PNG_BENIGN_ERRORS_SUPPORTED
 #define PNG_cHRM_SUPPORTED
+#define PNG_COLORSPACE_SUPPORTED
 #define PNG_gAMA_SUPPORTED
+#define PNG_GAMMA_SUPPORTED
 #define PNG_iCCP_SUPPORTED
 #define PNG_sRGB_SUPPORTED
 #define PNG_tRNS_SUPPORTED
 #define PNG_16BIT_SUPPORTED
 #define PNG_CHECK_cHRM_SUPPORTED
 #define PNG_FIXED_POINT_SUPPORTED
 #define PNG_FLOATING_ARITHMETIC_SUPPORTED
 #define PNG_FLOATING_POINT_SUPPORTED
 #define PNG_POINTER_INDEXING_SUPPORTED
 #define PNG_PROGRESSIVE_READ_SUPPORTED
 #define PNG_SETJMP_SUPPORTED
 #define PNG_STDIO_SUPPORTED
 #define PNG_TEXT_SUPPORTED
 
 #ifdef PR_LOGGING
-#define PNG_BENIGN_ERRORS_SUPPORTED
 #define PNG_ERROR_TEXT_SUPPORTED
 #define PNG_WARNINGS_SUPPORTED
 #endif
 
 /* Mangle names of exported libpng functions so different libpng versions
    can coexist. It is recommended that if you do this, you give your
    library a different name such as "mozlibpng" instead of "libpng". */
 
--- a/media/libpng/png.c
+++ b/media/libpng/png.c
@@ -1,35 +1,35 @@
 
 /* png.c - location for general purpose libpng functions
  *
- * Last changed in libpng 1.5.15 [March 28, 2013]
+ * Last changed in libpng 1.6.2 [April 25, 2013]
  * Copyright (c) 1998-2013 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
  * This code is released under the libpng license.
  * For conditions of distribution and use, see the disclaimer
  * and license in png.h
  */
 
 #include "pngpriv.h"
 
 /* Generate a compiler error if there is an old png.h in the search path. */
-typedef png_libpng_version_1_5_17 Your_png_h_is_not_version_1_5_17;
+typedef png_libpng_version_1_6_6 Your_png_h_is_not_version_1_6_6;
 
 /* Tells libpng that we have already handled the first "num_bytes" bytes
  * of the PNG file signature.  If the PNG data is embedded into another
  * stream we can set num_bytes = 8 so that libpng will not attempt to read
  * or write any of the magic bytes before it starts on the IHDR.
  */
 
 #ifdef PNG_READ_SUPPORTED
 void PNGAPI
-png_set_sig_bytes(png_structp png_ptr, int num_bytes)
+png_set_sig_bytes(png_structrp png_ptr, int num_bytes)
 {
    png_debug(1, "in png_set_sig_bytes");
 
    if (png_ptr == NULL)
       return;
 
    if (num_bytes > 8)
       png_error(png_ptr, "Too many bytes for PNG signature");
@@ -57,127 +57,118 @@ png_sig_cmp(png_const_bytep sig, png_siz
       return (-1);
 
    if (start > 7)
       return (-1);
 
    if (start + num_to_check > 8)
       num_to_check = 8 - start;
 
-   return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
+   return ((int)(memcmp(&sig[start], &png_signature[start], num_to_check)));
 }
 
 #endif /* PNG_READ_SUPPORTED */
 
 #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
 /* Function to allocate memory for zlib */
 PNG_FUNCTION(voidpf /* PRIVATE */,
 png_zalloc,(voidpf png_ptr, uInt items, uInt size),PNG_ALLOCATED)
 {
-   png_voidp ptr;
-   png_structp p;
-   png_uint_32 save_flags;
-   png_alloc_size_t num_bytes;
+   png_alloc_size_t num_bytes = size;
 
    if (png_ptr == NULL)
-      return (NULL);
-
-   p=(png_structp)png_ptr;
-   save_flags=p->flags;
-
-   if (items > PNG_UINT_32_MAX/size)
+      return NULL;
+
+   if (items >= (~(png_alloc_size_t)0)/size)
    {
-     png_warning (p, "Potential overflow in png_zalloc()");
-     return (NULL);
+      png_warning (png_voidcast(png_structrp, png_ptr),
+         "Potential overflow in png_zalloc()");
+      return NULL;
    }
-   num_bytes = (png_alloc_size_t)items * size;
-
-   p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
-   ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
-   p->flags=save_flags;
-
-   return ((voidpf)ptr);
+
+   num_bytes *= items;
+   return png_malloc_warn(png_voidcast(png_structrp, png_ptr), num_bytes);
 }
 
 /* Function to free memory for zlib */
 void /* PRIVATE */
 png_zfree(voidpf png_ptr, voidpf ptr)
 {
-   png_free((png_structp)png_ptr, (png_voidp)ptr);
+   png_free(png_voidcast(png_const_structrp,png_ptr), ptr);
 }
 
 /* Reset the CRC variable to 32 bits of 1's.  Care must be taken
  * in case CRC is > 32 bits to leave the top bits 0.
  */
 void /* PRIVATE */
-png_reset_crc(png_structp png_ptr)
+png_reset_crc(png_structrp png_ptr)
 {
    /* The cast is safe because the crc is a 32 bit value. */
    png_ptr->crc = (png_uint_32)crc32(0, Z_NULL, 0);
 }
 
 /* Calculate the CRC over a section of data.  We can only pass as
  * much data to this routine as the largest single buffer size.  We
  * also check that this data will actually be used before going to the
  * trouble of calculating it.
  */
 void /* PRIVATE */
-png_calculate_crc(png_structp png_ptr, png_const_bytep ptr, png_size_t length)
+png_calculate_crc(png_structrp png_ptr, png_const_bytep ptr, png_size_t length)
 {
    int need_crc = 1;
 
-   if (PNG_CHUNK_ANCILLIARY(png_ptr->chunk_name))
+   if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name))
    {
       if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
           (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
          need_crc = 0;
    }
 
    else /* critical */
    {
       if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
          need_crc = 0;
    }
 
-   /* 'uLong' is defined as unsigned long, this means that on some systems it is
-    * a 64 bit value.  crc32, however, returns 32 bits so the following cast is
-    * safe.  'uInt' may be no more than 16 bits, so it is necessary to perform a
-    * loop here.
+   /* 'uLong' is defined in zlib.h as unsigned long; this means that on some
+    * systems it is a 64 bit value.  crc32, however, returns 32 bits so the
+    * following cast is safe.  'uInt' may be no more than 16 bits, so it is
+    * necessary to perform a loop here.
     */
    if (need_crc && length > 0)
    {
       uLong crc = png_ptr->crc; /* Should never issue a warning */
 
       do
       {
-         uInt safeLength = (uInt)length;
-         if (safeLength == 0)
-            safeLength = (uInt)-1; /* evil, but safe */
-
-         crc = crc32(crc, ptr, safeLength);
-
-         /* The following should never issue compiler warnings, if they do the
+         uInt safe_length = (uInt)length;
+         if (safe_length == 0)
+            safe_length = (uInt)-1; /* evil, but safe */
+
+         crc = crc32(crc, ptr, safe_length);
+
+         /* The following should never issue compiler warnings; if they do the
           * target system has characteristics that will probably violate other
           * assumptions within the libpng code.
           */
-         ptr += safeLength;
-         length -= safeLength;
+         ptr += safe_length;
+         length -= safe_length;
       }
       while (length > 0);
 
       /* And the following is always safe because the crc is only 32 bits. */
       png_ptr->crc = (png_uint_32)crc;
    }
 }
 
 /* Check a user supplied version number, called from both read and write
- * functions that create a png_struct
+ * functions that create a png_struct.
  */
 int
-png_user_version_check(png_structp png_ptr, png_const_charp user_png_ver)
+png_user_version_check(png_structrp png_ptr, png_const_charp user_png_ver)
 {
    if (user_png_ver)
    {
       int i = 0;
 
       do
       {
          if (user_png_ver[i] != png_libpng_ver[i])
@@ -188,154 +179,269 @@ png_user_version_check(png_structp png_p
    else
       png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
 
    if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
    {
      /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
       * we must recompile any applications that use any older library version.
       * For versions after libpng 1.0, we will be compatible, so we need
-      * only check the first digit.
+      * only check the first and third digits (note that when we reach version
+      * 1.10 we will need to check the fourth symbol, namely user_png_ver[3]).
       */
       if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
-          (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
+          (user_png_ver[0] == '1' && (user_png_ver[2] != png_libpng_ver[2] ||
+          user_png_ver[3] != png_libpng_ver[3])) ||
           (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
       {
 #ifdef PNG_WARNINGS_SUPPORTED
          size_t pos = 0;
          char m[128];
 
-         pos = png_safecat(m, sizeof m, pos, "Application built with libpng-");
-         pos = png_safecat(m, sizeof m, pos, user_png_ver);
-         pos = png_safecat(m, sizeof m, pos, " but running with ");
-         pos = png_safecat(m, sizeof m, pos, png_libpng_ver);
+         pos = png_safecat(m, (sizeof m), pos,
+             "Application built with libpng-");
+         pos = png_safecat(m, (sizeof m), pos, user_png_ver);
+         pos = png_safecat(m, (sizeof m), pos, " but running with ");
+         pos = png_safecat(m, (sizeof m), pos, png_libpng_ver);
 
          png_warning(png_ptr, m);
 #endif
 
 #ifdef PNG_ERROR_NUMBERS_SUPPORTED
          png_ptr->flags = 0;
 #endif
 
          return 0;
       }
    }
 
    /* Success return. */
    return 1;
 }
 
-/* Allocate the memory for an info_struct for the application.  We don't
- * really need the png_ptr, but it could potentially be useful in the
- * future.  This should be used in favour of malloc(png_sizeof(png_info))
- * and png_info_init() so that applications that want to use a shared
- * libpng don't have to be recompiled if png_info changes size.
+/* Generic function to create a png_struct for either read or write - this
+ * contains the common initialization.
  */
+PNG_FUNCTION(png_structp /* PRIVATE */,
+png_create_png_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
+    png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
+    png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
+{
+   png_struct create_struct;
+#  ifdef PNG_SETJMP_SUPPORTED
+      jmp_buf create_jmp_buf;
+#  endif
+
+   /* This temporary stack-allocated structure is used to provide a place to
+    * build enough context to allow the user provided memory allocator (if any)
+    * to be called.
+    */
+   memset(&create_struct, 0, (sizeof create_struct));
+
+   /* Added at libpng-1.2.6 */
+#  ifdef PNG_USER_LIMITS_SUPPORTED
+      create_struct.user_width_max = PNG_USER_WIDTH_MAX;
+      create_struct.user_height_max = PNG_USER_HEIGHT_MAX;
+
+#     ifdef PNG_USER_CHUNK_CACHE_MAX
+         /* Added at libpng-1.2.43 and 1.4.0 */
+         create_struct.user_chunk_cache_max = PNG_USER_CHUNK_CACHE_MAX;
+#     endif
+
+#     ifdef PNG_USER_CHUNK_MALLOC_MAX
+         /* Added at libpng-1.2.43 and 1.4.1, required only for read but exists
+          * in png_struct regardless.
+          */
+         create_struct.user_chunk_malloc_max = PNG_USER_CHUNK_MALLOC_MAX;
+#     endif
+#  endif
+
+   /* The following two API calls simply set fields in png_struct, so it is safe
+    * to do them now even though error handling is not yet set up.
+    */
+#  ifdef PNG_USER_MEM_SUPPORTED
+      png_set_mem_fn(&create_struct, mem_ptr, malloc_fn, free_fn);
+#  endif
+
+   /* (*error_fn) can return control to the caller after the error_ptr is set,
+    * this will result in a memory leak unless the error_fn does something
+    * extremely sophisticated.  The design lacks merit but is implicit in the
+    * API.
+    */
+   png_set_error_fn(&create_struct, error_ptr, error_fn, warn_fn);
+
+#  ifdef PNG_SETJMP_SUPPORTED
+      if (!setjmp(create_jmp_buf))
+      {
+         /* Temporarily fake out the longjmp information until we have
+          * successfully completed this function.  This only works if we have
+          * setjmp() support compiled in, but it is safe - this stuff should
+          * never happen.
+          */
+         create_struct.jmp_buf_ptr = &create_jmp_buf;
+         create_struct.jmp_buf_size = 0; /*stack allocation*/
+         create_struct.longjmp_fn = longjmp;
+#  else
+      {
+#  endif
+         /* Call the general version checker (shared with read and write code):
+          */
+         if (png_user_version_check(&create_struct, user_png_ver))
+         {
+            png_structrp png_ptr = png_voidcast(png_structrp,
+               png_malloc_warn(&create_struct, (sizeof *png_ptr)));
+
+            if (png_ptr != NULL)
+            {
+               /* png_ptr->zstream holds a back-pointer to the png_struct, so
+                * this can only be done now:
+                */
+               create_struct.zstream.zalloc = png_zalloc;
+               create_struct.zstream.zfree = png_zfree;
+               create_struct.zstream.opaque = png_ptr;
+
+#              ifdef PNG_SETJMP_SUPPORTED
+                  /* Eliminate the local error handling: */
+                  create_struct.jmp_buf_ptr = NULL;
+                  create_struct.jmp_buf_size = 0;
+                  create_struct.longjmp_fn = 0;
+#              endif
+
+               *png_ptr = create_struct;
+
+               /* This is the successful return point */
+               return png_ptr;
+            }
+         }
+      }
+
+   /* A longjmp because of a bug in the application storage allocator or a
+    * simple failure to allocate the png_struct.
+    */
+   return NULL;
+}
+
+/* Allocate the memory for an info_struct for the application. */
 PNG_FUNCTION(png_infop,PNGAPI
-png_create_info_struct,(png_structp png_ptr),PNG_ALLOCATED)
+png_create_info_struct,(png_const_structrp png_ptr),PNG_ALLOCATED)
 {
-   png_infop info_ptr;
+   png_inforp info_ptr;
 
    png_debug(1, "in png_create_info_struct");
 
    if (png_ptr == NULL)
-      return (NULL);
-
-#ifdef PNG_USER_MEM_SUPPORTED
-   info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
-      png_ptr->malloc_fn, png_ptr->mem_ptr);
-#else
-   info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
-#endif
+      return NULL;
+
+   /* Use the internal API that does not (or at least should not) error out, so
+    * that this call always returns ok.  The application typically sets up the
+    * error handling *after* creating the info_struct because this is the way it
+    * has always been done in 'example.c'.
+    */
+   info_ptr = png_voidcast(png_inforp, png_malloc_base(png_ptr,
+      (sizeof *info_ptr)));
+
    if (info_ptr != NULL)
-      png_info_init_3(&info_ptr, png_sizeof(png_info));
-
-   return (info_ptr);
+      memset(info_ptr, 0, (sizeof *info_ptr));
+
+   return info_ptr;
 }
 
 /* This function frees the memory associated with a single info struct.
  * Normally, one would use either png_destroy_read_struct() or
  * png_destroy_write_struct() to free an info struct, but this may be
- * useful for some applications.
+ * useful for some applications.  From libpng 1.6.0 this function is also used
+ * internally to implement the png_info release part of the 'struct' destroy
+ * APIs.  This ensures that all possible approaches free the same data (all of
+ * it).
  */
 void PNGAPI
-png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
+png_destroy_info_struct(png_const_structrp png_ptr, png_infopp info_ptr_ptr)
 {
-   png_infop info_ptr = NULL;
+   png_inforp info_ptr = NULL;
 
    png_debug(1, "in png_destroy_info_struct");
 
    if (png_ptr == NULL)
       return;
 
    if (info_ptr_ptr != NULL)
       info_ptr = *info_ptr_ptr;
 
    if (info_ptr != NULL)
    {
-      png_info_destroy(png_ptr, info_ptr);
-
-#ifdef PNG_USER_MEM_SUPPORTED
-      png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
-          png_ptr->mem_ptr);
-#else
-      png_destroy_struct((png_voidp)info_ptr);
-#endif
+      /* Do this first in case of an error below; if the app implements its own
+       * memory management this can lead to png_free calling png_error, which
+       * will abort this routine and return control to the app error handler.
+       * An infinite loop may result if it then tries to free the same info
+       * ptr.
+       */
       *info_ptr_ptr = NULL;
+
+      png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
+      memset(info_ptr, 0, (sizeof *info_ptr));
+      png_free(png_ptr, info_ptr);
    }
 }
 
 /* Initialize the info structure.  This is now an internal function (0.89)
  * and applications using it are urged to use png_create_info_struct()
- * instead.
+ * instead.  Use deprecated in 1.6.0, internal use removed (used internally it
+ * is just a memset).
+ *
+ * NOTE: it is almost inconceivable that this API is used because it bypasses
+ * the user-memory mechanism and the user error handling/warning mechanisms in
+ * those cases where it does anything other than a memset.
  */
-
-void PNGAPI
-png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
+PNG_FUNCTION(void,PNGAPI
+png_info_init_3,(png_infopp ptr_ptr, png_size_t png_info_struct_size),
+   PNG_DEPRECATED)
 {
-   png_infop info_ptr = *ptr_ptr;
+   png_inforp info_ptr = *ptr_ptr;
 
    png_debug(1, "in png_info_init_3");
 
    if (info_ptr == NULL)
       return;
 
-   if (png_sizeof(png_info) > png_info_struct_size)
+   if ((sizeof (png_info)) > png_info_struct_size)
    {
-      png_destroy_struct(info_ptr);
-      info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
+      *ptr_ptr = NULL;
+      /* The following line is why this API should not be used: */
+      free(info_ptr);
+      info_ptr = png_voidcast(png_inforp, png_malloc_base(NULL,
+         (sizeof *info_ptr)));
       *ptr_ptr = info_ptr;
    }
 
    /* Set everything to 0 */
-   png_memset(info_ptr, 0, png_sizeof(png_info));
+   memset(info_ptr, 0, (sizeof *info_ptr));
 }
 
+/* The following API is not called internally */
 void PNGAPI
-png_data_freer(png_structp png_ptr, png_infop info_ptr,
+png_data_freer(png_const_structrp png_ptr, png_inforp info_ptr,
    int freer, png_uint_32 mask)
 {
    png_debug(1, "in png_data_freer");
 
    if (png_ptr == NULL || info_ptr == NULL)
       return;
 
    if (freer == PNG_DESTROY_WILL_FREE_DATA)
       info_ptr->free_me |= mask;
 
    else if (freer == PNG_USER_WILL_FREE_DATA)
       info_ptr->free_me &= ~mask;
 
    else
-      png_warning(png_ptr,
-         "Unknown freer parameter in png_data_freer");
+      png_error(png_ptr, "Unknown freer parameter in png_data_freer");
 }
 
 void PNGAPI
-png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
+png_free_data(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 mask,
    int num)
 {
    png_debug(1, "in png_free_data");
 
    if (png_ptr == NULL || info_ptr == NULL)
       return;
 
 #ifdef PNG_TEXT_SUPPORTED
@@ -390,31 +496,31 @@ png_free_data(png_structp png_ptr, png_i
    if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
    {
       png_free(png_ptr, info_ptr->pcal_purpose);
       png_free(png_ptr, info_ptr->pcal_units);
       info_ptr->pcal_purpose = NULL;
       info_ptr->pcal_units = NULL;
       if (info_ptr->pcal_params != NULL)
          {
-            int i;
-            for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
+            unsigned int i;
+            for (i = 0; i < info_ptr->pcal_nparams; i++)
             {
                png_free(png_ptr, info_ptr->pcal_params[i]);
                info_ptr->pcal_params[i] = NULL;
             }
             png_free(png_ptr, info_ptr->pcal_params);
             info_ptr->pcal_params = NULL;
          }
       info_ptr->valid &= ~PNG_INFO_pCAL;
    }
 #endif
 
 #ifdef PNG_iCCP_SUPPORTED
-   /* Free any iCCP entry */
+   /* Free any profile entry */
    if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
    {
       png_free(png_ptr, info_ptr->iccp_name);
       png_free(png_ptr, info_ptr->iccp_profile);
       info_ptr->iccp_name = NULL;
       info_ptr->iccp_profile = NULL;
       info_ptr->valid &= ~PNG_INFO_iCCP;
    }
@@ -435,35 +541,29 @@ png_free_data(png_structp png_ptr, png_i
          }
       }
 
       else
       {
          if (info_ptr->splt_palettes_num)
          {
             int i;
-            for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
-               png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
+            for (i = 0; i < info_ptr->splt_palettes_num; i++)
+               png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, (int)i);
 
             png_free(png_ptr, info_ptr->splt_palettes);
             info_ptr->splt_palettes = NULL;
             info_ptr->splt_palettes_num = 0;
          }
          info_ptr->valid &= ~PNG_INFO_sPLT;
       }
    }
 #endif
 
-#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
-   if (png_ptr->unknown_chunk.data)
-   {
-      png_free(png_ptr, png_ptr->unknown_chunk.data);
-      png_ptr->unknown_chunk.data = NULL;
-   }
-
+#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
    if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
    {
       if (num != -1)
       {
           if (info_ptr->unknown_chunks)
           {
              png_free(png_ptr, info_ptr->unknown_chunks[num].data);
              info_ptr->unknown_chunks[num].data = NULL;
@@ -472,17 +572,17 @@ png_free_data(png_structp png_ptr, png_i
 
       else
       {
          int i;
 
          if (info_ptr->unknown_chunks_num)
          {
             for (i = 0; i < info_ptr->unknown_chunks_num; i++)
-               png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
+               png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, (int)i);
 
             png_free(png_ptr, info_ptr->unknown_chunks);
             info_ptr->unknown_chunks = NULL;
             info_ptr->unknown_chunks_num = 0;
          }
       }
    }
 #endif
@@ -495,140 +595,127 @@ png_free_data(png_structp png_ptr, png_i
       info_ptr->hist = NULL;
       info_ptr->valid &= ~PNG_INFO_hIST;
    }
 #endif
 
    /* Free any PLTE entry that was internally allocated */
    if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
    {
-      png_zfree(png_ptr, info_ptr->palette);
+      png_free(png_ptr, info_ptr->palette);
       info_ptr->palette = NULL;
       info_ptr->valid &= ~PNG_INFO_PLTE;
       info_ptr->num_palette = 0;
    }
 
 #ifdef PNG_INFO_IMAGE_SUPPORTED
    /* Free any image bits attached to the info structure */
    if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
    {
       if (info_ptr->row_pointers)
       {
-         int row;
-         for (row = 0; row < (int)info_ptr->height; row++)
+         png_uint_32 row;
+         for (row = 0; row < info_ptr->height; row++)
          {
             png_free(png_ptr, info_ptr->row_pointers[row]);
             info_ptr->row_pointers[row] = NULL;
          }
          png_free(png_ptr, info_ptr->row_pointers);
          info_ptr->row_pointers = NULL;
       }
       info_ptr->valid &= ~PNG_INFO_IDAT;
    }
 #endif
 
    if (num != -1)
       mask &= ~PNG_FREE_MUL;
 
    info_ptr->free_me &= ~mask;
 }
-
-/* This is an internal routine to free any memory that the info struct is
- * pointing to before re-using it or freeing the struct itself.  Recall
- * that png_free() checks for NULL pointers for us.
- */
-void /* PRIVATE */
-png_info_destroy(png_structp png_ptr, png_infop info_ptr)
-{
-   png_debug(1, "in png_info_destroy");
-
-   png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
-
-#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
-   if (png_ptr->num_chunk_list)
-   {
-      png_free(png_ptr, png_ptr->chunk_list);
-      png_ptr->chunk_list = NULL;
-      png_ptr->num_chunk_list = 0;
-   }
-#endif
-
-   png_info_init_3(&info_ptr, png_sizeof(png_info));
-}
 #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
 
 /* This function returns a pointer to the io_ptr associated with the user
  * functions.  The application should free any memory associated with this
  * pointer before png_write_destroy() or png_read_destroy() are called.
  */
 png_voidp PNGAPI
-png_get_io_ptr(png_structp png_ptr)
+png_get_io_ptr(png_const_structrp png_ptr)
 {
    if (png_ptr == NULL)
       return (NULL);
 
    return (png_ptr->io_ptr);
 }
 
 #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
 #  ifdef PNG_STDIO_SUPPORTED
 /* Initialize the default input/output functions for the PNG file.  If you
  * use your own read or write routines, you can call either png_set_read_fn()
  * or png_set_write_fn() instead of png_init_io().  If you have defined
  * PNG_NO_STDIO or otherwise disabled PNG_STDIO_SUPPORTED, you must use a
  * function of your own because "FILE *" isn't necessarily available.
  */
 void PNGAPI
-png_init_io(png_structp png_ptr, png_FILE_p fp)
+png_init_io(png_structrp png_ptr, png_FILE_p fp)
 {
    png_debug(1, "in png_init_io");
 
    if (png_ptr == NULL)
       return;
 
    png_ptr->io_ptr = (png_voidp)fp;
 }
 #  endif
 
+#ifdef PNG_SAVE_INT_32_SUPPORTED
+/* The png_save_int_32 function assumes integers are stored in two's
+ * complement format.  If this isn't the case, then this routine needs to
+ * be modified to write data in two's complement format.  Note that,
+ * the following works correctly even if png_int_32 has more than 32 bits
+ * (compare the more complex code required on read for sign extension.)
+ */
+void PNGAPI
+png_save_int_32(png_bytep buf, png_int_32 i)
+{
+   buf[0] = (png_byte)((i >> 24) & 0xff);
+   buf[1] = (png_byte)((i >> 16) & 0xff);
+   buf[2] = (png_byte)((i >> 8) & 0xff);
+   buf[3] = (png_byte)(i & 0xff);
+}
+#endif
+
 #  ifdef PNG_TIME_RFC1123_SUPPORTED
 /* Convert the supplied time into an RFC 1123 string suitable for use in
  * a "Creation Time" or other text-based time string.
  */
-png_const_charp PNGAPI
-png_convert_to_rfc1123(png_structp png_ptr, png_const_timep ptime)
+int PNGAPI
+png_convert_to_rfc1123_buffer(char out[29], png_const_timep ptime)
 {
    static PNG_CONST char short_months[12][4] =
         {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
 
-   if (png_ptr == NULL)
-      return (NULL);
+   if (out == NULL)
+      return 0;
 
    if (ptime->year > 9999 /* RFC1123 limitation */ ||
        ptime->month == 0    ||  ptime->month > 12  ||
        ptime->day   == 0    ||  ptime->day   > 31  ||
        ptime->hour  > 23    ||  ptime->minute > 59 ||
        ptime->second > 60)
-   {
-      png_warning(png_ptr, "Ignoring invalid time value");
-      return (NULL);
-   }
+      return 0;
 
    {
       size_t pos = 0;
       char number_buf[5]; /* enough for a four-digit year */
 
-#     define APPEND_STRING(string)\
-         pos = png_safecat(png_ptr->time_buffer, sizeof png_ptr->time_buffer,\
-            pos, (string))
+#     define APPEND_STRING(string) pos = png_safecat(out, 29, pos, (string))
 #     define APPEND_NUMBER(format, value)\
          APPEND_STRING(PNG_FORMAT_NUMBER(number_buf, format, (value)))
-#     define APPEND(ch)\
-         if (pos < (sizeof png_ptr->time_buffer)-1)\
-            png_ptr->time_buffer[pos++] = (ch)
+#     define APPEND(ch) if (pos < 28) out[pos++] = (ch)
 
       APPEND_NUMBER(PNG_NUMBER_FORMAT_u, (unsigned)ptime->day);
       APPEND(' ');
       APPEND_STRING(short_months[(ptime->month - 1)]);
       APPEND(' ');
       APPEND_NUMBER(PNG_NUMBER_FORMAT_u, ptime->year);
       APPEND(' ');
       APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->hour);
@@ -638,278 +725,468 @@ png_convert_to_rfc1123(png_structp png_p
       APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->second);
       APPEND_STRING(" +0000"); /* This reliably terminates the buffer */
 
 #     undef APPEND
 #     undef APPEND_NUMBER
 #     undef APPEND_STRING
    }
 
-   return png_ptr->time_buffer;
+   return 1;
 }
+
+#     if PNG_LIBPNG_VER < 10700
+/* To do: remove the following from libpng-1.7 */
+/* Original API that uses a private buffer in png_struct.
+ * Deprecated because it causes png_struct to carry a spurious temporary
+ * buffer (png_struct::time_buffer), better to have the caller pass this in.
+ */
+png_const_charp PNGAPI
+png_convert_to_rfc1123(png_structrp png_ptr, png_const_timep ptime)
+{
+   if (png_ptr != NULL)
+   {
+      /* The only failure above if png_ptr != NULL is from an invalid ptime */
+      if (!png_convert_to_rfc1123_buffer(png_ptr->time_buffer, ptime))
+         png_warning(png_ptr, "Ignoring invalid time value");
+
+      else
+         return png_ptr->time_buffer;
+   }
+
+   return NULL;
+}
+#     endif
 #  endif /* PNG_TIME_RFC1123_SUPPORTED */
 
 #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
 
 png_const_charp PNGAPI
-png_get_copyright(png_const_structp png_ptr)
+png_get_copyright(png_const_structrp png_ptr)
 {
    PNG_UNUSED(png_ptr)  /* Silence compiler warning about unused png_ptr */
 #ifdef PNG_STRING_COPYRIGHT
    return PNG_STRING_COPYRIGHT
 #else
 #  ifdef __STDC__
    return PNG_STRING_NEWLINE \
-     "libpng version 1.5.17 - June 27, 2013" PNG_STRING_NEWLINE \
+     "libpng version 1.6.6 - September 16, 2013" PNG_STRING_NEWLINE \
      "Copyright (c) 1998-2013 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \
      "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
      "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
      PNG_STRING_NEWLINE;
 #  else
-      return "libpng version 1.5.17 - June 27, 2013\
+      return "libpng version 1.6.6 - September 16, 2013\
       Copyright (c) 1998-2013 Glenn Randers-Pehrson\
       Copyright (c) 1996-1997 Andreas Dilger\
       Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.";
 #  endif
 #endif
 }
 
 /* The following return the library version as a short string in the
  * format 1.0.0 through 99.99.99zz.  To get the version of *.h files
  * used with your application, print out PNG_LIBPNG_VER_STRING, which
  * is defined in png.h.
  * Note: now there is no difference between png_get_libpng_ver() and
  * png_get_header_ver().  Due to the version_nn_nn_nn typedef guard,
  * it is guaranteed that png.c uses the correct version of png.h.
  */
 png_const_charp PNGAPI
-png_get_libpng_ver(png_const_structp png_ptr)
+png_get_libpng_ver(png_const_structrp png_ptr)
 {
    /* Version of *.c files used when building libpng */
    return png_get_header_ver(png_ptr);
 }
 
 png_const_charp PNGAPI
-png_get_header_ver(png_const_structp png_ptr)
+png_get_header_ver(png_const_structrp png_ptr)
 {
    /* Version of *.h files used when building libpng */
    PNG_UNUSED(png_ptr)  /* Silence compiler warning about unused png_ptr */
    return PNG_LIBPNG_VER_STRING;
 }
 
 png_const_charp PNGAPI
-png_get_header_version(png_const_structp png_ptr)
+png_get_header_version(png_const_structrp png_ptr)
 {
    /* Returns longer string containing both version and date */
    PNG_UNUSED(png_ptr)  /* Silence compiler warning about unused png_ptr */
 #ifdef __STDC__
    return PNG_HEADER_VERSION_STRING
 #  ifndef PNG_READ_SUPPORTED
    "     (NO READ SUPPORT)"
 #  endif
    PNG_STRING_NEWLINE;
 #else
    return PNG_HEADER_VERSION_STRING;
 #endif
 }
 
-#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
+#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
 int PNGAPI
-png_handle_as_unknown(png_structp png_ptr, png_const_bytep chunk_name)
+png_handle_as_unknown(png_const_structrp png_ptr, png_const_bytep chunk_name)
 {
    /* Check chunk_name and return "keep" value if it's on the list, else 0 */
    png_const_bytep p, p_end;
 
-   if (png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list <= 0)
+   if (png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list == 0)
       return PNG_HANDLE_CHUNK_AS_DEFAULT;
 
    p_end = png_ptr->chunk_list;
    p = p_end + png_ptr->num_chunk_list*5; /* beyond end */
 
    /* The code is the fifth byte after each four byte string.  Historically this
-    * code was always searched from the end of the list, so it should continue
-    * to do so in case there are duplicated entries.
+    * code was always searched from the end of the list, this is no longer
+    * necessary because the 'set' routine handles duplicate entries correcty.
     */
    do /* num_chunk_list > 0, so at least one */
    {
       p -= 5;
-      if (!png_memcmp(chunk_name, p, 4))
+
+      if (!memcmp(chunk_name, p, 4))
          return p[4];
    }
    while (p > p_end);
 
+   /* This means that known chunks should be processed and unknown chunks should
+    * be handled according to the value of png_ptr->unknown_default; this can be
+    * confusing because, as a result, there are two levels of defaulting for
+    * unknown chunks.
+    */
    return PNG_HANDLE_CHUNK_AS_DEFAULT;
 }
 
+#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
 int /* PRIVATE */
-png_chunk_unknown_handling(png_structp png_ptr, png_uint_32 chunk_name)
+png_chunk_unknown_handling(png_const_structrp png_ptr, png_uint_32 chunk_name)
 {
    png_byte chunk_string[5];
 
    PNG_CSTRING_FROM_CHUNK(chunk_string, chunk_name);
    return png_handle_as_unknown(png_ptr, chunk_string);
 }
-#endif
+#endif /* HANDLE_AS_UNKNOWN */
+#endif /* SET_UNKNOWN_CHUNKS */
 
 #ifdef PNG_READ_SUPPORTED
 /* This function, added to libpng-1.0.6g, is untested. */
 int PNGAPI
-png_reset_zstream(png_structp png_ptr)
+png_reset_zstream(png_structrp png_ptr)
 {
    if (png_ptr == NULL)
       return Z_STREAM_ERROR;
 
+   /* WARNING: this resets the window bits to the maximum! */
    return (inflateReset(&png_ptr->zstream));
 }
 #endif /* PNG_READ_SUPPORTED */
 
 /* This function was added to libpng-1.0.7 */
 png_uint_32 PNGAPI
 png_access_version_number(void)
 {
    /* Version of *.c files used when building libpng */
    return((png_uint_32)PNG_LIBPNG_VER);
 }
 
 
 
 #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
+/* Ensure that png_ptr->zstream.msg holds some appropriate error message string.
+ * If it doesn't 'ret' is used to set it to something appropriate, even in cases
+ * like Z_OK or Z_STREAM_END where the error code is apparently a success code.
+ */
+void /* PRIVATE */
+png_zstream_error(png_structrp png_ptr, int ret)
+{
+   /* Translate 'ret' into an appropriate error string, priority is given to the
+    * one in zstream if set.  This always returns a string, even in cases like
+    * Z_OK or Z_STREAM_END where the error code is a success code.
+    */
+   if (png_ptr->zstream.msg == NULL) switch (ret)
+   {
+      default:
+      case Z_OK:
+         png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected zlib return code");
+         break;
+
+      case Z_STREAM_END:
+         /* Normal exit */
+         png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected end of LZ stream");
+         break;
+
+      case Z_NEED_DICT:
+         /* This means the deflate stream did not have a dictionary; this
+          * indicates a bogus PNG.
+          */
+         png_ptr->zstream.msg = PNGZ_MSG_CAST("missing LZ dictionary");
+         break;
+
+      case Z_ERRNO:
+         /* gz APIs only: should not happen */
+         png_ptr->zstream.msg = PNGZ_MSG_CAST("zlib IO error");
+         break;
+
+      case Z_STREAM_ERROR:
+         /* internal libpng error */
+         png_ptr->zstream.msg = PNGZ_MSG_CAST("bad parameters to zlib");
+         break;
+
+      case Z_DATA_ERROR:
+         png_ptr->zstream.msg = PNGZ_MSG_CAST("damaged LZ stream");
+         break;
+
+      case Z_MEM_ERROR:
+         png_ptr->zstream.msg = PNGZ_MSG_CAST("insufficient memory");
+         break;
+
+      case Z_BUF_ERROR:
+         /* End of input or output; not a problem if the caller is doing
+          * incremental read or write.
+          */
+         png_ptr->zstream.msg = PNGZ_MSG_CAST("truncated");
+         break;
+
+      case Z_VERSION_ERROR:
+         png_ptr->zstream.msg = PNGZ_MSG_CAST("unsupported zlib version");
+         break;
+
+      case PNG_UNEXPECTED_ZLIB_RETURN:
+         /* Compile errors here mean that zlib now uses the value co-opted in
+          * pngpriv.h for PNG_UNEXPECTED_ZLIB_RETURN; update the switch above
+          * and change pngpriv.h.  Note that this message is "... return",
+          * whereas the default/Z_OK one is "... return code".
+          */
+         png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected zlib return");
+         break;
+   }
+}
+
 /* png_convert_size: a PNGAPI but no longer in png.h, so deleted
  * at libpng 1.5.5!
  */
 
 /* Added at libpng version 1.2.34 and 1.4.0 (moved from pngset.c) */
-#  ifdef PNG_CHECK_cHRM_SUPPORTED
-
-int /* PRIVATE */
-png_check_cHRM_fixed(png_structp png_ptr,
-   png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
-   png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
-   png_fixed_point blue_x, png_fixed_point blue_y)
+#ifdef PNG_GAMMA_SUPPORTED /* always set if COLORSPACE */
+static int
+png_colorspace_check_gamma(png_const_structrp png_ptr,
+   png_colorspacerp colorspace, png_fixed_point gAMA, int from)
+   /* This is called to check a new gamma value against an existing one.  The
+    * routine returns false if the new gamma value should not be written.
+    *
+    * 'from' says where the new gamma value comes from:
+    *
+    *    0: the new gamma value is the libpng estimate for an ICC profile
+    *    1: the new gamma value comes from a gAMA chunk
+    *    2: the new gamma value comes from an sRGB chunk
+    */
 {
-   int ret = 1;
-   unsigned long xy_hi,xy_lo,yx_hi,yx_lo;
-
-   png_debug(1, "in function png_check_cHRM_fixed");
-
-   if (png_ptr == NULL)
-      return 0;
-
-   /* (x,y,z) values are first limited to 0..100000 (PNG_FP_1), the white
-    * y must also be greater than 0.  To test for the upper limit calculate
-    * (PNG_FP_1-y) - x must be <= to this for z to be >= 0 (and the expression
-    * cannot overflow.)  At this point we know x and y are >= 0 and (x+y) is
-    * <= PNG_FP_1.  The previous test on PNG_MAX_UINT_31 is removed because it
-    * pointless (and it produces compiler warnings!)
+   png_fixed_point gtest;
+
+   if ((colorspace->flags & PNG_COLORSPACE_HAVE_GAMMA) != 0 &&
+      (!png_muldiv(&gtest, colorspace->gamma, PNG_FP_1, gAMA) ||
+      png_gamma_significant(gtest)))
+   {
+      /* Either this is an sRGB image, in which case the calculated gamma
+       * approximation should match, or this is an image with a profile and the
+       * value libpng calculates for the gamma of the profile does not match the
+       * value recorded in the file.  The former, sRGB, case is an error, the
+       * latter is just a warning.
+       */
+      if ((colorspace->flags & PNG_COLORSPACE_FROM_sRGB) != 0 || from == 2)
+      {
+         png_chunk_report(png_ptr, "gamma value does not match sRGB",
+            PNG_CHUNK_ERROR);
+         /* Do not overwrite an sRGB value */
+         return from == 2;
+      }
+
+      else /* sRGB tag not involved */
+      {
+         png_chunk_report(png_ptr, "gamma value does not match libpng estimate",
+            PNG_CHUNK_WARNING);
+         return from == 1;
+      }
+   }
+
+   return 1;
+}
+
+void /* PRIVATE */
+png_colorspace_set_gamma(png_const_structrp png_ptr,
+   png_colorspacerp colorspace, png_fixed_point gAMA)
+{
+   /* Changed in libpng-1.5.4 to limit the values to ensure overflow can't
+    * occur.  Since the fixed point representation is assymetrical it is
+    * possible for 1/gamma to overflow the limit of 21474 and this means the
+    * gamma value must be at least 5/100000 and hence at most 20000.0.  For
+    * safety the limits here are a little narrower.  The values are 0.00016 to
+    * 6250.0, which are truly ridiculous gamma values (and will produce
+    * displays that are all black or all white.)
+    *
+    * In 1.6.0 this test replaces the ones in pngrutil.c, in the gAMA chunk
+    * handling code, which only required the value to be >0.
     */
-   if (white_x < 0 || white_y <= 0 ||
-         red_x < 0 ||   red_y <  0 ||
-       green_x < 0 || green_y <  0 ||
-        blue_x < 0 ||  blue_y <  0)
-   {
-      png_warning(png_ptr,
-        "Ignoring attempt to set negative chromaticity value");
-      ret = 0;
-   }
-   /* And (x+y) must be <= PNG_FP_1 (so z is >= 0) */
-   if (white_x > PNG_FP_1 - white_y)
+   png_const_charp errmsg;
+
+   if (gAMA < 16 || gAMA > 625000000)
+      errmsg = "gamma value out of range";
+
+#  ifdef PNG_READ_gAMA_SUPPORTED
+      /* Allow the application to set the gamma value more than once */
+      else if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0 &&
+         (colorspace->flags & PNG_COLORSPACE_FROM_gAMA) != 0)
+         errmsg = "duplicate";
+#  endif
+
+   /* Do nothing if the colorspace is already invalid */
+   else if (colorspace->flags & PNG_COLORSPACE_INVALID)
+      return;
+
+   else
    {
-      png_warning(png_ptr, "Invalid cHRM white point");
-      ret = 0;
-   }
-
-   if (red_x > PNG_FP_1 - red_y)
-   {
-      png_warning(png_ptr, "Invalid cHRM red point");
-      ret = 0;
+      if (png_colorspace_check_gamma(png_ptr, colorspace, gAMA, 1/*from gAMA*/))
+      {
+         /* Store this gamma value. */
+         colorspace->gamma = gAMA;
+         colorspace->flags |=
+            (PNG_COLORSPACE_HAVE_GAMMA | PNG_COLORSPACE_FROM_gAMA);
+      }
+
+      /* At present if the check_gamma test fails the gamma of the colorspace is
+       * not updated however the colorspace is not invalidated.  This
+       * corresponds to the case where the existing gamma comes from an sRGB
+       * chunk or profile.  An error message has already been output.
+       */
+      return;
    }
 
-   if (green_x > PNG_FP_1 - green_y)
+   /* Error exit - errmsg has been set. */
+   colorspace->flags |= PNG_COLORSPACE_INVALID;
+   png_chunk_report(png_ptr, errmsg, PNG_CHUNK_WRITE_ERROR);
+}
+
+void /* PRIVATE */
+png_colorspace_sync_info(png_const_structrp png_ptr, png_inforp info_ptr)
+{
+   if (info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID)
    {
-      png_warning(png_ptr, "Invalid cHRM green point");
-      ret = 0;
+      /* Everything is invalid */
+      info_ptr->valid &= ~(PNG_INFO_gAMA|PNG_INFO_cHRM|PNG_INFO_sRGB|
+         PNG_INFO_iCCP);
+
+#     ifdef PNG_COLORSPACE_SUPPORTED
+         /* Clean up the iCCP profile now if it won't be used. */
+         png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, -1/*not used*/);
+#     else
+         PNG_UNUSED(png_ptr)
+#     endif
    }
 
-   if (blue_x > PNG_FP_1 - blue_y)
+   else
    {
-      png_warning(png_ptr, "Invalid cHRM blue point");
-      ret = 0;
+#     ifdef PNG_COLORSPACE_SUPPORTED
+         /* Leave the INFO_iCCP flag set if the pngset.c code has already set
+          * it; this allows a PNG to contain a profile which matches sRGB and
+          * yet still have that profile retrievable by the application.
+          */
+         if (info_ptr->colorspace.flags & PNG_COLORSPACE_MATCHES_sRGB)
+            info_ptr->valid |= PNG_INFO_sRGB;
+
+         else
+            info_ptr->valid &= ~PNG_INFO_sRGB;
+
+         if (info_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_ENDPOINTS)
+            info_ptr->valid |= PNG_INFO_cHRM;
+
+         else
+            info_ptr->valid &= ~PNG_INFO_cHRM;
+#     endif
+
+      if (info_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_GAMMA)
+         info_ptr->valid |= PNG_INFO_gAMA;
+
+      else
+         info_ptr->valid &= ~PNG_INFO_gAMA;
    }
-
-   png_64bit_product(green_x - red_x, blue_y - red_y, &xy_hi, &xy_lo);
-   png_64bit_product(green_y - red_y, blue_x - red_x, &yx_hi, &yx_lo);
-
-   if (xy_hi == yx_hi && xy_lo == yx_lo)
-   {
-      png_warning(png_ptr,
-         "Ignoring attempt to set cHRM RGB triangle with zero area");
-      ret = 0;
-   }
-
-   return ret;
 }
-#  endif /* PNG_CHECK_cHRM_SUPPORTED */
-
-#ifdef PNG_cHRM_SUPPORTED
+
+#ifdef PNG_READ_SUPPORTED
+void /* PRIVATE */
+png_colorspace_sync(png_const_structrp png_ptr, png_inforp info_ptr)
+{
+   if (info_ptr == NULL) /* reduce code size; check here not in the caller */
+      return;
+
+   info_ptr->colorspace = png_ptr->colorspace;
+   png_colorspace_sync_info(png_ptr, info_ptr);
+}
+#endif
+#endif
+
+#ifdef PNG_COLORSPACE_SUPPORTED
 /* Added at libpng-1.5.5 to support read and write of true CIEXYZ values for
  * cHRM, as opposed to using chromaticities.  These internal APIs return
  * non-zero on a parameter error.  The X, Y and Z values are required to be
  * positive and less than 1.0.
  */
-int png_xy_from_XYZ(png_xy *xy, png_XYZ XYZ)
+static int
+png_xy_from_XYZ(png_xy *xy, const png_XYZ *XYZ)
 {
    png_int_32 d, dwhite, whiteX, whiteY;
 
-   d = XYZ.redX + XYZ.redY + XYZ.redZ;
-   if (!png_muldiv(&xy->redx, XYZ.redX, PNG_FP_1, d)) return 1;
-   if (!png_muldiv(&xy->redy, XYZ.redY, PNG_FP_1, d)) return 1;
+   d = XYZ->red_X + XYZ->red_Y + XYZ->red_Z;
+   if (!png_muldiv(&xy->redx, XYZ->red_X, PNG_FP_1, d)) return 1;
+   if (!png_muldiv(&xy->redy, XYZ->red_Y, PNG_FP_1, d)) return 1;
    dwhite = d;
-   whiteX = XYZ.redX;
-   whiteY = XYZ.redY;
-
-   d = XYZ.greenX + XYZ.greenY + XYZ.greenZ;
-   if (!png_muldiv(&xy->greenx, XYZ.greenX, PNG_FP_1, d)) return 1;
-   if (!png_muldiv(&xy->greeny, XYZ.greenY, PNG_FP_1, d)) return 1;
+   whiteX = XYZ->red_X;
+   whiteY = XYZ->red_Y;
+
+   d = XYZ->green_X + XYZ->green_Y + XYZ->green_Z;
+   if (!png_muldiv(&xy->greenx, XYZ->green_X, PNG_FP_1, d)) return 1;
+   if (!png_muldiv(&xy->greeny, XYZ->green_Y, PNG_FP_1, d)) return 1;
    dwhite += d;
-   whiteX += XYZ.greenX;
-   whiteY += XYZ.greenY;
-
-   d = XYZ.blueX + XYZ.blueY + XYZ.blueZ;
-   if (!png_muldiv(&xy->bluex, XYZ.blueX, PNG_FP_1, d)) return 1;
-   if (!png_muldiv(&xy->bluey, XYZ.blueY, PNG_FP_1, d)) return 1;
+   whiteX += XYZ->green_X;
+   whiteY += XYZ->green_Y;
+
+   d = XYZ->blue_X + XYZ->blue_Y + XYZ->blue_Z;
+   if (!png_muldiv(&xy->bluex, XYZ->blue_X, PNG_FP_1, d)) return 1;
+   if (!png_muldiv(&xy->bluey, XYZ->blue_Y, PNG_FP_1, d)) return 1;
    dwhite += d;
-   whiteX += XYZ.blueX;
-   whiteY += XYZ.blueY;
-
-   /* The reference white is simply the same of the end-point (X,Y,Z) vectors,
+   whiteX += XYZ->blue_X;
+   whiteY += XYZ->blue_Y;
+
+   /* The reference white is simply the sum of the end-point (X,Y,Z) vectors,
     * thus:
     */
    if (!png_muldiv(&xy->whitex, whiteX, PNG_FP_1, dwhite)) return 1;
    if (!png_muldiv(&xy->whitey, whiteY, PNG_FP_1, dwhite)) return 1;
 
    return 0;
 }
 
-int png_XYZ_from_xy(png_XYZ *XYZ, png_xy xy)
+static int
+png_XYZ_from_xy(png_XYZ *XYZ, const png_xy *xy)
 {
    png_fixed_point red_inverse, green_inverse, blue_scale;
    png_fixed_point left, right, denominator;
 
    /* Check xy and, implicitly, z.  Note that wide gamut color spaces typically
     * have end points with 0 tristimulus values (these are impossible end
     * points, but they are used to cover the possible colors.)
     */
-   if (xy.redx < 0 || xy.redx > PNG_FP_1) return 1;
-   if (xy.redy < 0 || xy.redy > PNG_FP_1-xy.redx) return 1;
-   if (xy.greenx < 0 || xy.greenx > PNG_FP_1) return 1;
-   if (xy.greeny < 0 || xy.greeny > PNG_FP_1-xy.greenx) return 1;
-   if (xy.bluex < 0 || xy.bluex > PNG_FP_1) return 1;
-   if (xy.bluey < 0 || xy.bluey > PNG_FP_1-xy.bluex) return 1;
-   if (xy.whitex < 0 || xy.whitex > PNG_FP_1) return 1;
-   if (xy.whitey < 0 || xy.whitey > PNG_FP_1-xy.whitex) return 1;
+   if (xy->redx < 0 || xy->redx > PNG_FP_1) return 1;
+   if (xy->redy < 0 || xy->redy > PNG_FP_1-xy->redx) return 1;
+   if (xy->greenx < 0 || xy->greenx > PNG_FP_1) return 1;
+   if (xy->greeny < 0 || xy->greeny > PNG_FP_1-xy->greenx) return 1;
+   if (xy->bluex < 0 || xy->bluex > PNG_FP_1) return 1;
+   if (xy->bluey < 0 || xy->bluey > PNG_FP_1-xy->bluex) return 1;
+   if (xy->whitex < 0 || xy->whitex > PNG_FP_1) return 1;
+   if (xy->whitey < 0 || xy->whitey > PNG_FP_1-xy->whitex) return 1;
 
    /* The reverse calculation is more difficult because the original tristimulus
     * value had 9 independent values (red,green,blue)x(X,Y,Z) however only 8
     * derived values were recorded in the cHRM chunk;
     * (red,green,blue,white)x(x,y).  This loses one degree of freedom and
     * therefore an arbitrary ninth value has to be introduced to undo the
     * original transformations.
     *
@@ -1080,101 +1357,1011 @@ int png_XYZ_from_xy(png_XYZ *XYZ, png_xy
     *  Adobe RGB
     *    0.297344975250536 0.627363566255466 0.075291458493998
     *  Adobe Wide Gamut RGB
     *    0.258728243040113 0.724682314948566 0.016589442011321
     */
    /* By the argument, above overflow should be impossible here. The return
     * value of 2 indicates an internal error to the caller.
     */
-   if (!png_muldiv(&left, xy.greenx-xy.bluex, xy.redy - xy.bluey, 7)) return 2;
-   if (!png_muldiv(&right, xy.greeny-xy.bluey, xy.redx - xy.bluex, 7)) return 2;
+   if (!png_muldiv(&left, xy->greenx-xy->bluex, xy->redy - xy->bluey, 7))
+      return 2;
+   if (!png_muldiv(&right, xy->greeny-xy->bluey, xy->redx - xy->bluex, 7))
+      return 2;
    denominator = left - right;
 
    /* Now find the red numerator. */
-   if (!png_muldiv(&left, xy.greenx-xy.bluex, xy.whitey-xy.bluey, 7)) return 2;
-   if (!png_muldiv(&right, xy.greeny-xy.bluey, xy.whitex-xy.bluex, 7)) return 2;
+   if (!png_muldiv(&left, xy->greenx-xy->bluex, xy->whitey-xy->bluey, 7))
+      return 2;
+   if (!png_muldiv(&right, xy->greeny-xy->bluey, xy->whitex-xy->bluex, 7))
+      return 2;
 
    /* Overflow is possible here and it indicates an extreme set of PNG cHRM
     * chunk values.  This calculation actually returns the reciprocal of the
     * scale value because this allows us to delay the multiplication of white-y
     * into the denominator, which tends to produce a small number.
     */
-   if (!png_muldiv(&red_inverse, xy.whitey, denominator, left-right) ||
-       red_inverse <= xy.whitey /* r+g+b scales = white scale */)
+   if (!png_muldiv(&red_inverse, xy->whitey, denominator, left-right) ||
+       red_inverse <= xy->whitey /* r+g+b scales = white scale */)
       return 1;
 
    /* Similarly for green_inverse: */
-   if (!png_muldiv(&left, xy.redy-xy.bluey, xy.whitex-xy.bluex, 7)) return 2;
-   if (!png_muldiv(&right, xy.redx-xy.bluex, xy.whitey-xy.bluey, 7)) return 2;
-   if (!png_muldiv(&green_inverse, xy.whitey, denominator, left-right) ||
-       green_inverse <= xy.whitey)
+   if (!png_muldiv(&left, xy->redy-xy->bluey, xy->whitex-xy->bluex, 7))
+      return 2;
+   if (!png_muldiv(&right, xy->redx-xy->bluex, xy->whitey-xy->bluey, 7))
+      return 2;
+   if (!png_muldiv(&green_inverse, xy->whitey, denominator, left-right) ||
+       green_inverse <= xy->whitey)
       return 1;
 
    /* And the blue scale, the checks above guarantee this can't overflow but it
     * can still produce 0 for extreme cHRM values.
     */
-   blue_scale = png_reciprocal(xy.whitey) - png_reciprocal(red_inverse) -
+   blue_scale = png_reciprocal(xy->whitey) - png_reciprocal(red_inverse) -
       png_reciprocal(green_inverse);
    if (blue_scale <= 0) return 1;
 
 
    /* And fill in the png_XYZ: */
-   if (!png_muldiv(&XYZ->redX, xy.redx, PNG_FP_1, red_inverse)) return 1;
-   if (!png_muldiv(&XYZ->redY, xy.redy, PNG_FP_1, red_inverse)) return 1;
-   if (!png_muldiv(&XYZ->redZ, PNG_FP_1 - xy.redx - xy.redy, PNG_FP_1,
+   if (!png_muldiv(&XYZ->red_X, xy->redx, PNG_FP_1, red_inverse)) return 1;
+   if (!png_muldiv(&XYZ->red_Y, xy->redy, PNG_FP_1, red_inverse)) return 1;
+   if (!png_muldiv(&XYZ->red_Z, PNG_FP_1 - xy->redx - xy->redy, PNG_FP_1,
       red_inverse))
       return 1;
 
-   if (!png_muldiv(&XYZ->greenX, xy.greenx, PNG_FP_1, green_inverse)) return 1;
-   if (!png_muldiv(&XYZ->greenY, xy.greeny, PNG_FP_1, green_inverse)) return 1;
-   if (!png_muldiv(&XYZ->greenZ, PNG_FP_1 - xy.greenx - xy.greeny, PNG_FP_1,
+   if (!png_muldiv(&XYZ->green_X, xy->greenx, PNG_FP_1, green_inverse))
+      return 1;
+   if (!png_muldiv(&XYZ->green_Y, xy->greeny, PNG_FP_1, green_inverse))
+      return 1;
+   if (!png_muldiv(&XYZ->green_Z, PNG_FP_1 - xy->greenx - xy->greeny, PNG_FP_1,
       green_inverse))
       return 1;
 
-   if (!png_muldiv(&XYZ->blueX, xy.bluex, blue_scale, PNG_FP_1)) return 1;
-   if (!png_muldiv(&XYZ->blueY, xy.bluey, blue_scale, PNG_FP_1)) return 1;
-   if (!png_muldiv(&XYZ->blueZ, PNG_FP_1 - xy.bluex - xy.bluey, blue_scale,
+   if (!png_muldiv(&XYZ->blue_X, xy->bluex, blue_scale, PNG_FP_1)) return 1;
+   if (!png_muldiv(&XYZ->blue_Y, xy->bluey, blue_scale, PNG_FP_1)) return 1;
+   if (!png_muldiv(&XYZ->blue_Z, PNG_FP_1 - xy->bluex - xy->bluey, blue_scale,
       PNG_FP_1))
       return 1;
 
    return 0; /*success*/
 }
 
-int png_XYZ_from_xy_checked(png_structp png_ptr, png_XYZ *XYZ, png_xy xy)
+static int
+png_XYZ_normalize(png_XYZ *XYZ)
+{
+   png_int_32 Y;
+
+   if (XYZ->red_Y < 0 || XYZ->green_Y < 0 || XYZ->blue_Y < 0 ||
+      XYZ->red_X < 0 || XYZ->green_X < 0 || XYZ->blue_X < 0 ||
+      XYZ->red_Z < 0 || XYZ->green_Z < 0 || XYZ->blue_Z < 0)
+      return 1;
+
+   /* Normalize by scaling so the sum of the end-point Y values is PNG_FP_1.
+    * IMPLEMENTATION NOTE: ANSI requires signed overflow not to occur, therefore
+    * relying on addition of two positive values producing a negative one is not
+    * safe.
+    */
+   Y = XYZ->red_Y;
+   if (0x7fffffff - Y < XYZ->green_X) return 1;
+   Y += XYZ->green_Y;
+   if (0x7fffffff - Y < XYZ->blue_X) return 1;
+   Y += XYZ->blue_Y;
+
+   if (Y != PNG_FP_1)
+   {
+      if (!png_muldiv(&XYZ->red_X, XYZ->red_X, PNG_FP_1, Y)) return 1;
+      if (!png_muldiv(&XYZ->red_Y, XYZ->red_Y, PNG_FP_1, Y)) return 1;
+      if (!png_muldiv(&XYZ->red_Z, XYZ->red_Z, PNG_FP_1, Y)) return 1;
+
+      if (!png_muldiv(&XYZ->green_X, XYZ->green_X, PNG_FP_1, Y)) return 1;
+      if (!png_muldiv(&XYZ->green_Y, XYZ->green_Y, PNG_FP_1, Y)) return 1;
+      if (!png_muldiv(&XYZ->green_Z, XYZ->green_Z, PNG_FP_1, Y)) return 1;
+
+      if (!png_muldiv(&XYZ->blue_X, XYZ->blue_X, PNG_FP_1, Y)) return 1;
+      if (!png_muldiv(&XYZ->blue_Y, XYZ->blue_Y, PNG_FP_1, Y)) return 1;
+      if (!png_muldiv(&XYZ->blue_Z, XYZ->blue_Z, PNG_FP_1, Y)) return 1;
+   }
+
+   return 0;
+}
+
+static int
+png_colorspace_endpoints_match(const png_xy *xy1, const png_xy *xy2, int delta)
+{
+   /* Allow an error of +/-0.01 (absolute value) on each chromaticity */
+   return !(PNG_OUT_OF_RANGE(xy1->whitex, xy2->whitex,delta) ||
+      PNG_OUT_OF_RANGE(xy1->whitey, xy2->whitey,delta) ||
+      PNG_OUT_OF_RANGE(xy1->redx,   xy2->redx,  delta) ||
+      PNG_OUT_OF_RANGE(xy1->redy,   xy2->redy,  delta) ||
+      PNG_OUT_OF_RANGE(xy1->greenx, xy2->greenx,delta) ||
+      PNG_OUT_OF_RANGE(xy1->greeny, xy2->greeny,delta) ||
+      PNG_OUT_OF_RANGE(xy1->bluex,  xy2->bluex, delta) ||
+      PNG_OUT_OF_RANGE(xy1->bluey,  xy2->bluey, delta));
+}
+
+/* Added in libpng-1.6.0, a different check for the validity of a set of cHRM
+ * chunk chromaticities.  Earlier checks used to simply look for the overflow
+ * condition (where the determinant of the matrix to solve for XYZ ends up zero
+ * because the chromaticity values are not all distinct.)  Despite this it is
+ * theoretically possible to produce chromaticities that are apparently valid
+ * but that rapidly degrade to invalid, potentially crashing, sets because of
+ * arithmetic inaccuracies when calculations are performed on them.  The new
+ * check is to round-trip xy -> XYZ -> xy and then check that the result is
+ * within a small percentage of the original.
+ */
+static int
+png_colorspace_check_xy(png_XYZ *XYZ, const png_xy *xy)
 {
-   switch (png_XYZ_from_xy(XYZ, xy))
+   int result;
+   png_xy xy_test;
+
+   /* As a side-effect this routine also returns the XYZ endpoints. */
+   result = png_XYZ_from_xy(XYZ, xy);
+   if (result) return result;
+
+   result = png_xy_from_XYZ(&xy_test, XYZ);
+   if (result) return result;
+
+   if (png_colorspace_endpoints_match(xy, &xy_test,
+      5/*actually, the math is pretty accurate*/))
+      return 0;
+
+   /* Too much slip */
+   return 1;
+}
+
+/* This is the check going the other way.  The XYZ is modified to normalize it
+ * (another side-effect) and the xy chromaticities are returned.
+ */
+static int
+png_colorspace_check_XYZ(png_xy *xy, png_XYZ *XYZ)
+{
+   int result;
+   png_XYZ XYZtemp;
+
+   result = png_XYZ_normalize(XYZ);
+   if (result) return result;
+
+   result = png_xy_from_XYZ(xy, XYZ);
+   if (result) return result;
+
+   XYZtemp = *XYZ;
+   return png_colorspace_check_xy(&XYZtemp, xy);
+}
+
+/* Used to check for an endpoint match against sRGB */
+static const png_xy sRGB_xy = /* From ITU-R BT.709-3 */
+{
+   /* color      x       y */
+   /* red   */ 64000, 33000,
+   /* green */ 30000, 60000,
+   /* blue  */ 15000,  6000,
+   /* white */ 31270, 32900
+};
+
+static int
+png_colorspace_set_xy_and_XYZ(png_const_structrp png_ptr,
+   png_colorspacerp colorspace, const png_xy *xy, const png_XYZ *XYZ,
+   int preferred)
+{
+   if (colorspace->flags & PNG_COLORSPACE_INVALID)
+      return 0;
+
+   /* The consistency check is performed on the chromaticities; this factors out
+    * variations because of the normalization (or not) of the end point Y
+    * values.
+    */
+   if (preferred < 2 && (colorspace->flags & PNG_COLORSPACE_HAVE_ENDPOINTS))
+   {
+      /* The end points must be reasonably close to any we already have.  The
+       * following allows an error of up to +/-.001
+       */
+      if (!png_colorspace_endpoints_match(xy, &colorspace->end_points_xy, 100))
+      {
+         colorspace->flags |= PNG_COLORSPACE_INVALID;
+         png_benign_error(png_ptr, "inconsistent chromaticities");
+         return 0; /* failed */
+      }
+
+      /* Only overwrite with preferred values */
+      if (!preferred)
+         return 1; /* ok, but no change */
+   }
+
+   colorspace->end_points_xy = *xy;
+   colorspace->end_points_XYZ = *XYZ;
+   colorspace->flags |= PNG_COLORSPACE_HAVE_ENDPOINTS;
+
+   /* The end points are normally quoted to two decimal digits, so allow +/-0.01
+    * on this test.
+    */
+   if (png_colorspace_endpoints_match(xy, &sRGB_xy, 1000))
+      colorspace->flags |= PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB;
+
+   else
+      colorspace->flags &= PNG_COLORSPACE_CANCEL(
+         PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB);
+
+   return 2; /* ok and changed */
+}
+
+int /* PRIVATE */
+png_colorspace_set_chromaticities(png_const_structrp png_ptr,
+   png_colorspacerp colorspace, const png_xy *xy, int preferred)
+{
+   /* We must check the end points to ensure they are reasonable - in the past
+    * color management systems have crashed as a result of getting bogus
+    * colorant values, while this isn't the fault of libpng it is the
+    * responsibility of libpng because PNG carries the bomb and libpng is in a
+    * position to protect against it.
+    */
+   png_XYZ XYZ;
+
+   switch (png_colorspace_check_xy(&XYZ, xy))
    {
       case 0: /* success */
-         return 1;
+         return png_colorspace_set_xy_and_XYZ(png_ptr, colorspace, xy, &XYZ,
+            preferred);
 
       case 1:
-         /* The chunk may be technically valid, but we got png_fixed_point
-          * overflow while trying to get XYZ values out of it.  This is
-          * entirely benign - the cHRM chunk is pretty extreme.
+         /* We can't invert the chromaticities so we can't produce value XYZ
+          * values.  Likely as not a color management system will fail too.
           */
-         png_warning(png_ptr,
-            "extreme cHRM chunk cannot be converted to tristimulus values");
+         colorspace->flags |= PNG_COLORSPACE_INVALID;
+         png_benign_error(png_ptr, "invalid chromaticities");
          break;
 
       default:
          /* libpng is broken; this should be a warning but if it happens we
           * want error reports so for the moment it is an error.
           */
-         png_error(png_ptr, "internal error in png_XYZ_from_xy");
+         colorspace->flags |= PNG_COLORSPACE_INVALID;
+         png_error(png_ptr, "internal error checking chromaticities");
+         break;
+   }
+
+   return 0; /* failed */
+}
+
+int /* PRIVATE */
+png_colorspace_set_endpoints(png_const_structrp png_ptr,
+   png_colorspacerp colorspace, const png_XYZ *XYZ_in, int preferred)
+{
+   png_XYZ XYZ = *XYZ_in;
+   png_xy xy;
+
+   switch (png_colorspace_check_XYZ(&xy, &XYZ))
+   {
+      case 0:
+         return png_colorspace_set_xy_and_XYZ(png_ptr, colorspace, &xy, &XYZ,
+            preferred);
+
+      case 1:
+         /* End points are invalid. */
+         colorspace->flags |= PNG_COLORSPACE_INVALID;
+         png_benign_error(png_ptr, "invalid end points");
+         break;
+
+      default:
+         colorspace->flags |= PNG_COLORSPACE_INVALID;
+         png_error(png_ptr, "internal error checking chromaticities");
          break;
    }
 
-   /* ERROR RETURN */
+   return 0; /* failed */
+}
+
+#if defined(PNG_sRGB_SUPPORTED) || defined(PNG_iCCP_SUPPORTED)
+/* Error message generation */
+static char
+png_icc_tag_char(png_uint_32 byte)
+{
+   byte &= 0xff;
+   if (byte >= 32 && byte <= 126)
+      return (char)byte;
+   else
+      return '?';
+}
+
+static void
+png_icc_tag_name(char *name, png_uint_32 tag)
+{
+   name[0] = '\'';
+   name[1] = png_icc_tag_char(tag >> 24);
+   name[2] = png_icc_tag_char(tag >> 16);
+   name[3] = png_icc_tag_char(tag >>  8);
+   name[4] = png_icc_tag_char(tag      );
+   name[5] = '\'';
+}
+
+static int
+is_ICC_signature_char(png_alloc_size_t it)
+{
+   return it == 32 || (it >= 48 && it <= 57) || (it >= 65 && it <= 90) ||
+      (it >= 97 && it <= 122);
+}
+
+static int is_ICC_signature(png_alloc_size_t it)
+{
+   return is_ICC_signature_char(it >> 24) /* checks all the top bits */ &&
+      is_ICC_signature_char((it >> 16) & 0xff) &&
+      is_ICC_signature_char((it >> 8) & 0xff) &&
+      is_ICC_signature_char(it & 0xff);
+}
+
+static int
+png_icc_profile_error(png_const_structrp png_ptr, png_colorspacerp colorspace,
+   png_const_charp name, png_alloc_size_t value, png_const_charp reason)
+{
+   size_t pos;
+   char message[196]; /* see below for calculation */
+
+   if (colorspace != NULL)
+      colorspace->flags |= PNG_COLORSPACE_INVALID;
+
+   pos = png_safecat(message, (sizeof message), 0, "profile '"); /* 9 chars */
+   pos = png_safecat(message, pos+79, pos, name); /* Truncate to 79 chars */
+   pos = png_safecat(message, (sizeof message), pos, "': "); /* +2 = 90 */
+   if (is_ICC_signature(value))
+   {
+      /* So 'value' is at most 4 bytes and the following cast is safe */
+      png_icc_tag_name(message+pos, (png_uint_32)value);
+      pos += 6; /* total +8; less than the else clause */
+      message[pos++] = ':';
+      message[pos++] = ' ';
+   }
+#  ifdef PNG_WARNINGS_SUPPORTED
+   else
+      {
+         char number[PNG_NUMBER_BUFFER_SIZE]; /* +24 = 114*/
+
+         pos = png_safecat(message, (sizeof message), pos,
+            png_format_number(number, number+(sizeof number),
+               PNG_NUMBER_FORMAT_x, value));
+         pos = png_safecat(message, (sizeof message), pos, "h: "); /*+2 = 116*/
+      }
+#  endif
+   /* The 'reason' is an arbitrary message, allow +79 maximum 195 */
+   pos = png_safecat(message, (sizeof message), pos, reason);
+
+   /* This is recoverable, but make it unconditionally an app_error on write to
+    * avoid writing invalid ICC profiles into PNG files.  (I.e.  we handle them
+    * on read, with a warning, but on write unless the app turns off
+    * application errors the PNG won't be written.)
+    */
+   png_chunk_report(png_ptr, message,
+      (colorspace != NULL) ? PNG_CHUNK_ERROR : PNG_CHUNK_WRITE_ERROR);
+
    return 0;
 }
+#endif /* sRGB || iCCP */
+
+#ifdef PNG_sRGB_SUPPORTED
+int /* PRIVATE */
+png_colorspace_set_sRGB(png_const_structrp png_ptr, png_colorspacerp colorspace,
+   int intent)
+{
+   /* sRGB sets known gamma, end points and (from the chunk) intent. */
+   /* IMPORTANT: these are not necessarily the values found in an ICC profile
+    * because ICC profiles store values adapted to a D50 environment; it is
+    * expected that the ICC profile mediaWhitePointTag will be D50, see the
+    * checks and code elsewhere to understand this better.
+    *
+    * These XYZ values, which are accurate to 5dp, produce rgb to gray
+    * coefficients of (6968,23435,2366), which are reduced (because they add up
+    * to 32769 not 32768) to (6968,23434,2366).  These are the values that
+    * libpng has traditionally used (and are the best values given the 15bit
+    * algorithm used by the rgb to gray code.)
+    */
+   static const png_XYZ sRGB_XYZ = /* D65 XYZ (*not* the D50 adapted values!) */
+   {
+      /* color      X      Y      Z */
+      /* red   */ 41239, 21264,  1933,
+      /* green */ 35758, 71517, 11919,
+      /* blue  */ 18048,  7219, 95053
+   };
+
+   /* Do nothing if the colorspace is already invalidated. */
+   if (colorspace->flags & PNG_COLORSPACE_INVALID)
+      return 0;
+
+   /* Check the intent, then check for existing settings.  It is valid for the
+    * PNG file to have cHRM or gAMA chunks along with sRGB, but the values must
+    * be consistent with the correct values.  If, however, this function is
+    * called below because an iCCP chunk matches sRGB then it is quite
+    * conceivable that an older app recorded incorrect gAMA and cHRM because of
+    * an incorrect calculation based on the values in the profile - this does
+    * *not* invalidate the profile (though it still produces an error, which can
+    * be ignored.)
+    */
+   if (intent < 0 || intent >= PNG_sRGB_INTENT_LAST)
+      return png_icc_profile_error(png_ptr, colorspace, "sRGB",
+         (unsigned)intent, "invalid sRGB rendering intent");
+
+   if ((colorspace->flags & PNG_COLORSPACE_HAVE_INTENT) != 0 &&
+      colorspace->rendering_intent != intent)
+      return png_icc_profile_error(png_ptr, colorspace, "sRGB",
+         (unsigned)intent, "inconsistent rendering intents");
+
+   if ((colorspace->flags & PNG_COLORSPACE_FROM_sRGB) != 0)
+   {
+      png_benign_error(png_ptr, "duplicate sRGB information ignored");
+      return 0;
+   }
+
+   /* If the standard sRGB cHRM chunk does not match the one from the PNG file
+    * warn but overwrite the value with the correct one.
+    */
+   if ((colorspace->flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0 &&
+      !png_colorspace_endpoints_match(&sRGB_xy, &colorspace->end_points_xy,
+         100))
+      png_chunk_report(png_ptr, "cHRM chunk does not match sRGB",
+         PNG_CHUNK_ERROR);
+
+   /* This check is just done for the error reporting - the routine always
+    * returns true when the 'from' argument corresponds to sRGB (2).
+    */
+   (void)png_colorspace_check_gamma(png_ptr, colorspace, PNG_GAMMA_sRGB_INVERSE,
+      2/*from sRGB*/);
+
+   /* intent: bugs in GCC force 'int' to be used as the parameter type. */
+   colorspace->rendering_intent = (png_uint_16)intent;
+   colorspace->flags |= PNG_COLORSPACE_HAVE_INTENT;
+
+   /* endpoints */
+   colorspace->end_points_xy = sRGB_xy;
+   colorspace->end_points_XYZ = sRGB_XYZ;
+   colorspace->flags |=
+      (PNG_COLORSPACE_HAVE_ENDPOINTS|PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB);
+
+   /* gamma */
+   colorspace->gamma = PNG_GAMMA_sRGB_INVERSE;
+   colorspace->flags |= PNG_COLORSPACE_HAVE_GAMMA;
+
+   /* Finally record that we have an sRGB profile */
+   colorspace->flags |=
+      (PNG_COLORSPACE_MATCHES_sRGB|PNG_COLORSPACE_FROM_sRGB);
+
+   return 1; /* set */
+}
+#endif /* sRGB */
+
+#ifdef PNG_iCCP_SUPPORTED
+/* Encoded value of D50 as an ICC XYZNumber.  From the ICC 2010 spec the value
+ * is XYZ(0.9642,1.0,0.8249), which scales to:
+ *
+ *    (63189.8112, 65536, 54060.6464)
+ */
+static const png_byte D50_nCIEXYZ[12] =
+   { 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d };
+
+int /* PRIVATE */
+png_icc_check_length(png_const_structrp png_ptr, png_colorspacerp colorspace,
+   png_const_charp name, png_uint_32 profile_length)
+{
+   if (profile_length < 132)
+      return png_icc_profile_error(png_ptr, colorspace, name, profile_length,
+         "too short");
+
+   if (profile_length & 3)
+      return png_icc_profile_error(png_ptr, colorspace, name, profile_length,
+         "invalid length");
+
+   return 1;
+}
+
+int /* PRIVATE */
+png_icc_check_header(png_const_structrp png_ptr, png_colorspacerp colorspace,
+   png_const_charp name, png_uint_32 profile_length,
+   png_const_bytep profile/* first 132 bytes only */, int color_type)
+{
+   png_uint_32 temp;
+
+   /* Length check; this cannot be ignored in this code because profile_length
+    * is used later to check the tag table, so even if the profile seems over
+    * long profile_length from the caller must be correct.  The caller can fix
+    * this up on read or write by just passing in the profile header length.
+    */
+   temp = png_get_uint_32(profile);
+   if (temp != profile_length)
+      return png_icc_profile_error(png_ptr, colorspace, name, temp,
+         "length does not match profile");
+
+   temp = png_get_uint_32(profile+128); /* tag count: 12 bytes/tag */
+   if (temp > 357913930 || /* (2^32-4-132)/12: maximum possible tag count */
+      profile_length < 132+12*temp) /* truncated tag table */
+      return png_icc_profile_error(png_ptr, colorspace, name, temp,
+         "tag count too large");
+
+   /* The 'intent' must be valid or we can't store it, ICC limits the intent to
+    * 16 bits.
+    */
+   temp = png_get_uint_32(profile+64);
+   if (temp >= 0xffff) /* The ICC limit */
+      return png_icc_profile_error(png_ptr, colorspace, name, temp,
+         "invalid rendering intent");
+
+   /* This is just a warning because the profile may be valid in future
+    * versions.
+    */
+   if (temp >= PNG_sRGB_INTENT_LAST)
+      (void)png_icc_profile_error(png_ptr, NULL, name, temp,
+         "intent outside defined range");
+
+   /* At this point the tag table can't be checked because it hasn't necessarily
+    * been loaded; however, various header fields can be checked.  These checks
+    * are for values permitted by the PNG spec in an ICC profile; the PNG spec
+    * restricts the profiles that can be passed in an iCCP chunk (they must be
+    * appropriate to processing PNG data!)
+    */
+
+   /* Data checks (could be skipped).  These checks must be independent of the
+    * version number; however, the version number doesn't accomodate changes in
+    * the header fields (just the known tags and the interpretation of the
+    * data.)
+    */
+   temp = png_get_uint_32(profile+36); /* signature 'ascp' */
+   if (temp != 0x61637370)
+      return png_icc_profile_error(png_ptr, colorspace, name, temp,
+         "invalid signature");
+
+   /* Currently the PCS illuminant/adopted white point (the computational
+    * white point) are required to be D50,
+    * however the profile contains a record of the illuminant so perhaps ICC
+    * expects to be able to change this in the future (despite the rationale in
+    * the introduction for using a fixed PCS adopted white.)  Consequently the
+    * following is just a warning.
+    */
+   if (memcmp(profile+68, D50_nCIEXYZ, 12) != 0)
+      (void)png_icc_profile_error(png_ptr, NULL, name, 0/*no tag value*/,
+         "PCS illuminant is not D50");
+
+   /* The PNG spec requires this:
+    * "If the iCCP chunk is present, the image samples conform to the colour
+    * space represented by the embedded ICC profile as defined by the
+    * International Color Consortium [ICC]. The colour space of the ICC profile
+    * shall be an RGB colour space for colour images (PNG colour types 2, 3, and
+    * 6), or a greyscale colour space for greyscale images (PNG colour types 0
+    * and 4)."
+    *
+    * This checking code ensures the embedded profile (on either read or write)
+    * conforms to the specification requirements.  Notice that an ICC 'gray'
+    * color-space profile contains the information to transform the monochrome
+    * data to XYZ or L*a*b (according to which PCS the profile uses) and this
+    * should be used in preference to the standard libpng K channel replication
+    * into R, G and B channels.
+    *
+    * Previously it was suggested that an RGB profile on grayscale data could be
+    * handled.  However it it is clear that using an RGB profile in this context
+    * must be an error - there is no specification of what it means.  Thus it is
+    * almost certainly more correct to ignore the profile.
+    */
+   temp = png_get_uint_32(profile+16); /* data colour space field */
+   switch (temp)
+   {
+      case 0x52474220: /* 'RGB ' */
+         if (!(color_type & PNG_COLOR_MASK_COLOR))
+            return png_icc_profile_error(png_ptr, colorspace, name, temp,
+               "RGB color space not permitted on grayscale PNG");
+         break;
+
+      case 0x47524159: /* 'GRAY' */
+         if (color_type & PNG_COLOR_MASK_COLOR)
+            return png_icc_profile_error(png_ptr, colorspace, name, temp,
+               "Gray color space not permitted on RGB PNG");
+         break;
+
+      default:
+         return png_icc_profile_error(png_ptr, colorspace, name, temp,
+            "invalid ICC profile color space");
+   }
+
+   /* It is up to the application to check that the profile class matches the
+    * application requirements; the spec provides no guidance, but it's pretty
+    * weird if the profile is not scanner ('scnr'), monitor ('mntr'), printer
+    * ('prtr') or 'spac' (for generic color spaces).  Issue a warning in these
+    * cases.  Issue an error for device link or abstract profiles - these don't
+    * contain the records necessary to transform the color-space to anything
+    * other than the target device (and not even that for an abstract profile).
+    * Profiles of these classes may not be embedded in images.
+    */
+   temp = png_get_uint_32(profile+12); /* profile/device class */
+   switch (temp)
+   {
+      case 0x73636E72: /* 'scnr' */
+      case 0x6D6E7472: /* 'mntr' */
+      case 0x70727472: /* 'prtr' */
+      case 0x73706163: /* 'spac' */
+         /* All supported */
+         break;
+
+      case 0x61627374: /* 'abst' */
+         /* May not be embedded in an image */
+         return png_icc_profile_error(png_ptr, colorspace, name, temp,
+            "invalid embedded Abstract ICC profile");
+
+      case 0x6C696E6B: /* 'link' */
+         /* DeviceLink profiles cannnot be interpreted in a non-device specific
+          * fashion, if an app uses the AToB0Tag in the profile the results are
+          * undefined unless the result is sent to the intended device,
+          * therefore a DeviceLink profile should not be found embedded in a
+          * PNG.
+          */
+         return png_icc_profile_error(png_ptr, colorspace, name, temp,
+            "unexpected DeviceLink ICC profile class");
+
+      case 0x6E6D636C: /* 'nmcl' */
+         /* A NamedColor profile is also device specific, however it doesn't
+          * contain an AToB0 tag that is open to misintrepretation.  Almost
+          * certainly it will fail the tests below.
+          */
+         (void)png_icc_profile_error(png_ptr, NULL, name, temp,
+            "unexpected NamedColor ICC profile class");
+         break;
+
+      default:
+         /* To allow for future enhancements to the profile accept unrecognized
+          * profile classes with a warning, these then hit the test below on the
+          * tag content to ensure they are backward compatible with one of the
+          * understood profiles.
+          */
+         (void)png_icc_profile_error(png_ptr, NULL, name, temp,
+            "unrecognized ICC profile class");
+         break;
+   }
+
+   /* For any profile other than a device link one the PCS must be encoded
+    * either in XYZ or Lab.
+    */
+   temp = png_get_uint_32(profile+20);
+   switch (temp)
+   {
+      case 0x58595A20: /* 'XYZ ' */
+      case 0x4C616220: /* 'Lab ' */
+         break;
+
+      default:
+         return png_icc_profile_error(png_ptr, colorspace, name, temp,
+            "unexpected ICC PCS encoding");
+   }
+
+   return 1;
+}
+
+int /* PRIVATE */
+png_icc_check_tag_table(png_const_structrp png_ptr, png_colorspacerp colorspace,
+   png_const_charp name, png_uint_32 profile_length,
+   png_const_bytep profile /* header plus whole tag table */)
+{
+   png_uint_32 tag_count = png_get_uint_32(profile+128);
+   png_uint_32 itag;
+   png_const_bytep tag = profile+132; /* The first tag */
+
+   /* First scan all the tags in the table and add bits to the icc_info value
+    * (temporarily in 'tags').
+    */
+   for (itag=0; itag < tag_count; ++itag, tag += 12)
+   {
+      png_uint_32 tag_id = png_get_uint_32(tag+0);
+      png_uint_32 tag_start = png_get_uint_32(tag+4); /* must be aligned */
+      png_uint_32 tag_length = png_get_uint_32(tag+8);/* not padded */
+
+      /* The ICC specification does not exclude zero length tags, therefore the
+       * start might actually be anywhere if there is no data, but this would be
+       * a clear abuse of the intent of the standard so the start is checked for
+       * being in range.  All defined tag types have an 8 byte header - a 4 byte
+       * type signature then 0.
+       */
+      if ((tag_start & 3) != 0)
+      {
+         /* CNHP730S.icc shipped with Microsoft Windows 64 violates this, it is
+          * only a warning here because libpng does not care about the
+          * alignment.
+          */
+         (void)png_icc_profile_error(png_ptr, NULL, name, tag_id,
+            "ICC profile tag start not a multiple of 4");
+      }
+
+      /* This is a hard error; potentially it can cause read outside the
+       * profile.
+       */
+      if (tag_start > profile_length || tag_length > profile_length - tag_start)
+         return png_icc_profile_error(png_ptr, colorspace, name, tag_id,
+            "ICC profile tag outside profile");
+   }
+
+   return 1; /* success, maybe with warnings */
+}
+
+#ifdef PNG_sRGB_SUPPORTED
+/* Information about the known ICC sRGB profiles */
+static const struct
+{
+   png_uint_32 adler, crc, length;
+   png_uint_32 md5[4];
+   png_byte    have_md5;
+   png_byte    is_broken;
+   png_uint_16 intent;
+
+#  define PNG_MD5(a,b,c,d) { a, b, c, d }, (a!=0)||(b!=0)||(c!=0)||(d!=0)
+#  define PNG_ICC_CHECKSUM(adler, crc, md5, intent, broke, date, length, fname)\
+      { adler, crc, length, md5, broke, intent },
+
+} png_sRGB_checks[] =
+{
+   /* This data comes from contrib/tools/checksum-icc run on downloads of
+    * all four ICC sRGB profiles from www.color.org.
+    */
+   /* adler32, crc32, MD5[4], intent, date, length, file-name */
+   PNG_ICC_CHECKSUM(0x0a3fd9f6, 0x3b8772b9,
+      PNG_MD5(0x29f83dde, 0xaff255ae, 0x7842fae4, 0xca83390d), 0, 0,
+      "2009/03/27 21:36:31", 3048, "sRGB_IEC61966-2-1_black_scaled.icc")
+
+   /* ICC sRGB v2 perceptual no black-compensation: */
+   PNG_ICC_CHECKSUM(0x4909e5e1, 0x427ebb21,
+      PNG_MD5(0xc95bd637, 0xe95d8a3b, 0x0df38f99, 0xc1320389), 1, 0,
+      "2009/03/27 21:37:45", 3052, "sRGB_IEC61966-2-1_no_black_scaling.icc")
+
+   PNG_ICC_CHECKSUM(0xfd2144a1, 0x306fd8ae,
+      PNG_MD5(0xfc663378, 0x37e2886b, 0xfd72e983, 0x8228f1b8), 0, 0,
+      "2009/08/10 17:28:01", 60988, "sRGB_v4_ICC_preference_displayclass.icc")
+
+   /* ICC sRGB v4 perceptual */
+   PNG_ICC_CHECKSUM(0x209c35d2, 0xbbef7812,
+      PNG_MD5(0x34562abf, 0x994ccd06, 0x6d2c5721, 0xd0d68c5d), 0, 0,
+      "2007/07/25 00:05:37", 60960, "sRGB_v4_ICC_preference.icc")
+
+   /* The following profiles have no known MD5 checksum. If there is a match
+    * on the (empty) MD5 the other fields are used to attempt a match and
+    * a warning is produced.  The first two of these profiles have a 'cprt' tag
+    * which suggests that they were also made by Hewlett Packard.
+    */
+   PNG_ICC_CHECKSUM(0xa054d762, 0x5d5129ce,
+      PNG_MD5(0x00000000, 0x00000000, 0x00000000, 0x00000000), 1, 0,
+      "2004/07/21 18:57:42", 3024, "sRGB_IEC61966-2-1_noBPC.icc")
+
+   /* This is a 'mntr' (display) profile with a mediaWhitePointTag that does not
+    * match the D50 PCS illuminant in the header (it is in fact the D65 values,
+    * so the white point is recorded as the un-adapted value.)  The profiles
+    * below only differ in one byte - the intent - and are basically the same as
+    * the previous profile except for the mediaWhitePointTag error and a missing
+    * chromaticAdaptationTag.
+    */
+   PNG_ICC_CHECKSUM(0xf784f3fb, 0x182ea552,
+      PNG_MD5(0x00000000, 0x00000000, 0x00000000, 0x00000000), 0, 1/*broken*/,
+      "1998/02/09 06:49:00", 3144, "HP-Microsoft sRGB v2 perceptual")
+
+   PNG_ICC_CHECKSUM(0x0398f3fc, 0xf29e526d,
+      PNG_MD5(0x00000000, 0x00000000, 0x00000000, 0x00000000), 1, 1/*broken*/,
+      "1998/02/09 06:49:00", 3144, "HP-Microsoft sRGB v2 media-relative")
+};
+
+static int
+png_compare_ICC_profile_with_sRGB(png_const_structrp png_ptr,
+   png_const_bytep profile, uLong adler)
+{
+   /* The quick check is to verify just the MD5 signature and trust the
+    * rest of the data.  Because the profile has already been verified for
+    * correctness this is safe.  png_colorspace_set_sRGB will check the 'intent'
+    * field too, so if the profile has been edited with an intent not defined
+    * by sRGB (but maybe defined by a later ICC specification) the read of
+    * the profile will fail at that point.
+    */
+   png_uint_32 length = 0;
+   png_uint_32 intent = 0x10000; /* invalid */
+#if PNG_sRGB_PROFILE_CHECKS > 1
+   uLong crc = 0; /* the value for 0 length data */
+#endif
+   unsigned int i;
+
+   for (i=0; i < (sizeof png_sRGB_checks) / (sizeof png_sRGB_checks[0]); ++i)
+   {
+      if (png_get_uint_32(profile+84) == png_sRGB_checks[i].md5[0] &&
+         png_get_uint_32(profile+88) == png_sRGB_checks[i].md5[1] &&
+         png_get_uint_32(profile+92) == png_sRGB_checks[i].md5[2] &&
+         png_get_uint_32(profile+96) == png_sRGB_checks[i].md5[3])
+      {
+         /* This may be one of the old HP profiles without an MD5, in that
+          * case we can only use the length and Adler32 (note that these
+          * are not used by default if there is an MD5!)
+          */
+#        if PNG_sRGB_PROFILE_CHECKS == 0
+            if (png_sRGB_checks[i].have_md5)
+               return 1+png_sRGB_checks[i].is_broken;
+#        endif
+
+         /* Profile is unsigned or more checks have been configured in. */
+         if (length == 0)
+         {
+            length = png_get_uint_32(profile);
+            intent = png_get_uint_32(profile+64);
+         }
+
+         /* Length *and* intent must match */
+         if (length == png_sRGB_checks[i].length &&
+            intent == png_sRGB_checks[i].intent)
+         {
+            /* Now calculate the adler32 if not done already. */
+            if (adler == 0)
+            {
+               adler = adler32(0, NULL, 0);
+               adler = adler32(adler, profile, length);
+            }
+
+            if (adler == png_sRGB_checks[i].adler)
+            {
+               /* These basic checks suggest that the data has not been
+                * modified, but if the check level is more than 1 perform
+                * our own crc32 checksum on the data.
+                */
+#              if PNG_sRGB_PROFILE_CHECKS > 1
+                  if (crc == 0)
+                  {
+                     crc = crc32(0, NULL, 0);
+                     crc = crc32(crc, profile, length);
+                  }
+
+                  /* So this check must pass for the 'return' below to happen.
+                   */
+                  if (crc == png_sRGB_checks[i].crc)
+#              endif
+               {
+                  if (png_sRGB_checks[i].is_broken)
+                  {
+                     /* These profiles are known to have bad data that may cause
+                      * problems if they are used, therefore attempt to
+                      * discourage their use, skip the 'have_md5' warning below,
+                      * which is made irrelevant by this error.
+                      */
+                     png_chunk_report(png_ptr, "known incorrect sRGB profile",
+                        PNG_CHUNK_ERROR);
+                  }
+
+                  /* Warn that this being done; this isn't even an error since
+                   * the profile is perfectly valid, but it would be nice if
+                   * people used the up-to-date ones.
+                   */
+                  else if (!png_sRGB_checks[i].have_md5)
+                  {
+                     png_chunk_report(png_ptr,
+                        "out-of-date sRGB profile with no signature",
+                        PNG_CHUNK_WARNING);
+                  }
+
+                  return 1+png_sRGB_checks[i].is_broken;
+               }
+            }
+         }
+
+#        if PNG_sRGB_PROFILE_CHECKS > 0
+            /* The signature matched, but the profile had been changed in some
+             * way.  This is an apparent violation of the ICC terms of use and,
+             * anyway, probably indicates a data error or uninformed hacking.
+             */
+            if (png_sRGB_checks[i].have_md5)
+               png_benign_error(png_ptr,
+                  "copyright violation: edited ICC profile ignored");
+#        endif
+      }
+   }
+
+   return 0; /* no match */
+}
 #endif
 
+#ifdef PNG_sRGB_SUPPORTED
 void /* PRIVATE */
-png_check_IHDR(png_structp png_ptr,
+png_icc_set_sRGB(png_const_structrp png_ptr,
+   png_colorspacerp colorspace, png_const_bytep profile, uLong adler)
+{
+   /* Is this profile one of the known ICC sRGB profiles?  If it is, just set
+    * the sRGB information.
+    */
+   if (png_compare_ICC_profile_with_sRGB(png_ptr, profile, adler))
+      (void)png_colorspace_set_sRGB(png_ptr, colorspace,
+         (int)/*already checked*/png_get_uint_32(profile+64));
+}
+#endif /* PNG_READ_sRGB_SUPPORTED */
+
+int /* PRIVATE */
+png_colorspace_set_ICC(png_const_structrp png_ptr, png_colorspacerp colorspace,
+   png_const_charp name, png_uint_32 profile_length, png_const_bytep profile,
+   int color_type)
+{
+   if (colorspace->flags & PNG_COLORSPACE_INVALID)
+      return 0;
+
+   if (png_icc_check_length(png_ptr, colorspace, name, profile_length) &&
+      png_icc_check_header(png_ptr, colorspace, name, profile_length, profile,
+         color_type) &&
+      png_icc_check_tag_table(png_ptr, colorspace, name, profile_length,
+         profile))
+   {
+#     ifdef PNG_sRGB_SUPPORTED
+         /* If no sRGB support, don't try storing sRGB information */
+         png_icc_set_sRGB(png_ptr, colorspace, profile, 0);
+#     endif
+      return 1;
+   }
+
+   /* Failure case */
+   return 0;
+}
+#endif /* iCCP */
+
+#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
+void /* PRIVATE */
+png_colorspace_set_rgb_coefficients(png_structrp png_ptr)
+{
+   /* Set the rgb_to_gray coefficients from the colorspace. */
+   if (!png_ptr->rgb_to_gray_coefficients_set &&
+      (png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0)
+   {
+      /* png_set_background has not been called, get the coefficients from the Y
+       * values of the colorspace colorants.
+       */
+      png_fixed_point r = png_ptr->colorspace.end_points_XYZ.red_Y;
+      png_fixed_point g = png_ptr->colorspace.end_points_XYZ.green_Y;
+      png_fixed_point b = png_ptr->colorspace.end_points_XYZ.blue_Y;
+      png_fixed_point total = r+g+b;
+
+      if (total > 0 &&
+         r >= 0 && png_muldiv(&r, r, 32768, total) && r >= 0 && r <= 32768 &&
+         g >= 0 && png_muldiv(&g, g, 32768, total) && g >= 0 && g <= 32768 &&
+         b >= 0 && png_muldiv(&b, b, 32768, total) && b >= 0 && b <= 32768 &&
+         r+g+b <= 32769)
+      {
+         /* We allow 0 coefficients here.  r+g+b may be 32769 if two or
+          * all of the coefficients were rounded up.  Handle this by
+          * reducing the *largest* coefficient by 1; this matches the
+          * approach used for the default coefficients in pngrtran.c
+          */
+         int add = 0;
+
+         if (r+g+b > 32768)
+            add = -1;
+         else if (r+g+b < 32768)
+            add = 1;
+
+         if (add != 0)
+         {
+            if (g >= r && g >= b)
+               g += add;
+            else if (r >= g && r >= b)
+               r += add;
+            else
+               b += add;
+         }
+
+         /* Check for an internal error. */
+         if (r+g+b != 32768)
+            png_error(png_ptr,
+               "internal error handling cHRM coefficients");
+
+         else
+         {
+            png_ptr->rgb_to_gray_red_coeff   = (png_uint_16)r;
+            png_ptr->rgb_to_gray_green_coeff = (png_uint_16)g;
+         }
+      }
+
+      /* This is a png_error at present even though it could be ignored -
+       * it should never happen, but it is important that if it does, the
+       * bug is fixed.
+       */
+      else
+         png_error(png_ptr, "internal error handling cHRM->XYZ");
+   }
+}
+#endif
+
+#endif /* COLORSPACE */
+
+void /* PRIVATE */
+png_check_IHDR(png_const_structrp png_ptr,
    png_uint_32 width, png_uint_32 height, int bit_depth,
    int color_type, int interlace_type, int compression_type,
    int filter_type)
 {
    int error = 0;
 
    /* Check for width and height valid values */
    if (width == 0)
@@ -1465,31 +2652,31 @@ png_check_fp_string(png_const_charp stri
 #  ifdef PNG_FLOATING_POINT_SUPPORTED
 /* Utility used below - a simple accurate power of ten from an integral
  * exponent.
  */
 static double
 png_pow10(int power)
 {
    int recip = 0;
-   double d = 1.0;
+   double d = 1;
 
    /* Handle negative exponent with a reciprocal at the end because
     * 10 is exact whereas .1 is inexact in base 2
     */
    if (power < 0)
    {
       if (power < DBL_MIN_10_EXP) return 0;
       recip = 1, power = -power;
    }
 
    if (power > 0)
    {
       /* Decompose power bitwise. */
-      double mult = 10.0;
+      double mult = 10;
       do
       {
          if (power & 1) d *= mult;
          mult *= mult;
          power >>= 1;
       }
       while (power > 0);
 
@@ -1499,17 +2686,17 @@ png_pow10(int power)
 
    return d;
 }
 
 /* Function to format a floating point value in ASCII with a given
  * precision.
  */
 void /* PRIVATE */
-png_ascii_from_fp(png_structp png_ptr, png_charp ascii, png_size_t size,
+png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, png_size_t size,
     double fp, unsigned int precision)
 {
    /* We use standard functions from math.h, but not printf because
     * that would require stdio.  The caller must supply a buffer of
     * sufficient size or we will png_error.  The tests on size and
     * the space in ascii[] consumed are indicated below.
     */
    if (precision < 1)
@@ -1598,42 +2785,40 @@ png_ascii_from_fp(png_structp png_ptr, p
              */
             clead = czero; /* Count of leading zeros */
             cdigits = 0;   /* Count of digits in list. */
 
             do
             {
                double d;
 
-               fp *= 10.0;
-
+               fp *= 10;
                /* Use modf here, not floor and subtract, so that
                 * the separation is done in one step.  At the end
                 * of the loop don't break the number into parts so
                 * that the final digit is rounded.
                 */
                if (cdigits+czero-clead+1 < (int)precision)
                   fp = modf(fp, &d);
 
                else
                {
                   d = floor(fp + .5);
 
-                  if (d > 9.0)
+                  if (d > 9)
                   {
                      /* Rounding up to 10, handle that here. */
                      if (czero > 0)
                      {
                         --czero, d = 1;
                         if (cdigits == 0) --clead;
                      }
-
                      else
                      {
-                        while (cdigits > 0 && d > 9.0)
+                        while (cdigits > 0 && d > 9)
                         {
                            int ch = *--ascii;
 
                            if (exp_b10 != (-1))
                               ++exp_b10;
 
                            else if (ch == 46)
                            {
@@ -1648,17 +2833,17 @@ png_ascii_from_fp(png_structp png_ptr, p
                            --cdigits;
                            d = ch - 47;  /* I.e. 1+(ch-48) */
                         }
 
                         /* Did we reach the beginning? If so adjust the
                          * exponent but take into account the leading
                          * decimal point.
                          */
-                        if (d > 9.0)  /* cdigits == 0 */
+                        if (d > 9)  /* cdigits == 0 */
                         {
                            if (exp_b10 == (-1))
                            {
                               /* Leading decimal point (plus zeros?), if
                                * we lose the decimal point here it must
                                * be reentered below.
                                */
                               int ch = *--ascii;
@@ -1669,29 +2854,28 @@ png_ascii_from_fp(png_structp png_ptr, p
                               /* Else lost a leading zero, so 'exp_b10' is
                                * still ok at (-1)
                                */
                            }
                            else
                               ++exp_b10;
 
                            /* In all cases we output a '1' */
-                           d = 1.0;
+                           d = 1;
                         }
                      }
                   }
                   fp = 0; /* Guarantees termination below. */
                }
 
-               if (d == 0.0)
+               if (d == 0)
                {
                   ++czero;
                   if (cdigits == 0) ++clead;
                }
-
                else
                {
                   /* Included embedded zeros in the digit count. */
                   cdigits += czero - clead;
                   clead = 0;
 
                   while (czero > 0)
                   {
@@ -1709,17 +2893,16 @@ png_ascii_from_fp(png_structp png_ptr, p
                   }
 
                   if (exp_b10 != (-1))
                   {
                      if (exp_b10 == 0) *ascii++ = 46, --size; /* counted
                                                                  above */
                      --exp_b10;
                   }
-
                   *ascii++ = (char)(48 + (int)d), ++cdigits;
                }
             }
             while (cdigits+czero-clead < (int)precision && fp > DBL_MIN);
 
             /* The total output count (max) is now 4+precision */
 
             /* Check for an exponent, if we don't need one we are
@@ -1817,18 +3000,18 @@ png_ascii_from_fp(png_structp png_ptr, p
 }
 
 #  endif /* FLOATING_POINT */
 
 #  ifdef PNG_FIXED_POINT_SUPPORTED
 /* Function to format a fixed point value in ASCII.
  */
 void /* PRIVATE */
-png_ascii_from_fixed(png_structp png_ptr, png_charp ascii, png_size_t size,
-    png_fixed_point fp)
+png_ascii_from_fixed(png_const_structrp png_ptr, png_charp ascii,
+    png_size_t size, png_fixed_point fp)
 {
    /* Require space for 10 decimal digits, a decimal point, a minus sign and a
     * trailing \0, 13 characters:
     */
    if (size > 12)
    {
       png_uint_32 num;
 
@@ -1888,19 +3071,24 @@ png_ascii_from_fixed(png_structp png_ptr
 
    /* Here on buffer too small. */
    png_error(png_ptr, "ASCII conversion buffer too small");
 }
 #   endif /* FIXED_POINT */
 #endif /* READ_SCAL */
 
 #if defined(PNG_FLOATING_POINT_SUPPORTED) && \
-   !defined(PNG_FIXED_POINT_MACRO_SUPPORTED)
+   !defined(PNG_FIXED_POINT_MACRO_SUPPORTED) && \
+   (defined(PNG_gAMA_SUPPORTED) || defined(PNG_cHRM_SUPPORTED) || \
+   defined(PNG_sCAL_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) || \
+   defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)) || \
+   (defined(PNG_sCAL_SUPPORTED) && \
+   defined(PNG_FLOATING_ARITHMETIC_SUPPORTED))
 png_fixed_point
-png_fixed(png_structp png_ptr, double fp, png_const_charp text)
+png_fixed(png_const_structrp png_ptr, double fp, png_const_charp text)
 {
    double r = floor(100000 * fp + .5);
 
    if (r > 2147483647. || r < -2147483648.)
       png_fixed_error(png_ptr, text);
 
    return (png_fixed_point)r;
 }
@@ -2029,31 +3217,30 @@ png_muldiv(png_fixed_point_p res, png_fi
 }
 #endif /* READ_GAMMA || INCH_CONVERSIONS */
 
 #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_INCH_CONVERSIONS_SUPPORTED)
 /* The following is for when the caller doesn't much care about the
  * result.
  */
 png_fixed_point
-png_muldiv_warn(png_structp png_ptr, png_fixed_point a, png_int_32 times,
+png_muldiv_warn(png_const_structrp png_ptr, png_fixed_point a, png_int_32 times,
     png_int_32 divisor)
 {
    png_fixed_point result;
 
    if (png_muldiv(&result, a, times, divisor))
       return result;
 
    png_warning(png_ptr, "fixed point overflow ignored");
    return 0;
 }
 #endif
 
-#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_cHRM_SUPPORTED)
-/* more fixed point functions for gamma and cHRM (xy/XYZ) suport. */
+#ifdef PNG_GAMMA_SUPPORTED /* more fixed point functions for gamma */
 /* Calculate a reciprocal, return 0 on div-by-zero or overflow. */
 png_fixed_point
 png_reciprocal(png_fixed_point a)
 {
 #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
    double r = floor(1E10/a+.5);
 
    if (r <= 2147483647. && r >= -2147483648.)
@@ -2063,16 +3250,27 @@ png_reciprocal(png_fixed_point a)
 
    if (png_muldiv(&res, 100000, 100000, a))
       return res;
 #endif
 
    return 0; /* error/overflow */
 }
 
+/* This is the shared test on whether a gamma value is 'significant' - whether
+ * it is worth doing gamma correction.
+ */
+int /* PRIVATE */
+png_gamma_significant(png_fixed_point gamma_val)
+{
+   return gamma_val < PNG_FP_1 - PNG_GAMMA_THRESHOLD_FIXED ||
+       gamma_val > PNG_FP_1 + PNG_GAMMA_THRESHOLD_FIXED;
+}
+#endif
+
 #ifdef PNG_READ_GAMMA_SUPPORTED
 /* A local convenience routine. */
 static png_fixed_point
 png_product2(png_fixed_point a, png_fixed_point b)
 {
    /* The required result is 1/a * 1/b; the following preserves accuracy. */
 #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
    double r = a * 1E-5;
@@ -2085,17 +3283,16 @@ png_product2(png_fixed_point a, png_fixe
    png_fixed_point res;
 
    if (png_muldiv(&res, a, b, 100000))
       return res;
 #endif
 
    return 0; /* overflow */
 }
-#endif /* READ_GAMMA */
 
 /* The inverse of the above. */
 png_fixed_point
 png_reciprocal2(png_fixed_point a, png_fixed_point b)
 {
    /* The required result is 1/a * 1/b; the following preserves accuracy. */
 #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
    double r = 1E15/a;
@@ -2113,85 +3310,40 @@ png_reciprocal2(png_fixed_point a, png_f
    png_fixed_point res = png_product2(a, b);
 
    if (res != 0)
       return png_reciprocal(res);
 #endif
 
    return 0; /* overflow */
 }
-#endif /* READ_GAMMA || cHRM */
-
-#ifdef PNG_CHECK_cHRM_SUPPORTED
-/* Added at libpng version 1.2.34 (Dec 8, 2008) and 1.4.0 (Jan 2,
- * 2010: moved from pngset.c) */
-/*
- *    Multiply two 32-bit numbers, V1 and V2, using 32-bit
- *    arithmetic, to produce a 64-bit result in the HI/LO words.
- *
- *                  A B
- *                x C D
- *               ------
- *              AD || BD
- *        AC || CB || 0
- *
- *    where A and B are the high and low 16-bit words of V1,
- *    C and D are the 16-bit words of V2, AD is the product of
- *    A and D, and X || Y is (X << 16) + Y.
-*/
-
-void /* PRIVATE */
-png_64bit_product (long v1, long v2, unsigned long *hi_product,
-    unsigned long *lo_product)
-{
-   int a, b, c, d;
-   long lo, hi, x, y;
-
-   a = (v1 >> 16) & 0xffff;
-   b = v1 & 0xffff;
-   c = (v2 >> 16) & 0xffff;
-   d = v2 & 0xffff;
-
-   lo = b * d;                   /* BD */
-   x = a * d + c * b;            /* AD + CB */
-   y = ((lo >> 16) & 0xffff) + x;
-
-   lo = (lo & 0xffff) | ((y & 0xffff) << 16);
-   hi = (y >> 16) & 0xffff;
-
-   hi += a * c;                  /* AC */
-
-   *hi_product = (unsigned long)hi;
-   *lo_product = (unsigned long)lo;
-}
-#endif /* CHECK_cHRM */
+#endif /* READ_GAMMA */
 
 #ifdef PNG_READ_GAMMA_SUPPORTED /* gamma table code */
 #ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED
 /* Fixed point gamma.
  *
+ * The code to calculate the tables used below can be found in the shell script
+ * contrib/tools/intgamma.sh
+ *
  * To calculate gamma this code implements fast log() and exp() calls using only
  * fixed point arithmetic.  This code has sufficient precision for either 8-bit
  * or 16-bit sample values.
  *
  * The tables used here were calculated using simple 'bc' programs, but C double
- * precision floating point arithmetic would work fine.  The programs are given
- * at the head of each table.
+ * precision floating point arithmetic would work fine.
  *
  * 8-bit log table
  *   This is a table of -log(value/255)/log(2) for 'value' in the range 128 to
  *   255, so it's the base 2 logarithm of a normalized 8-bit floating point
  *   mantissa.  The numbers are 32-bit fractions.
  */
-static png_uint_32
+static const png_uint_32
 png_8bit_l2[128] =
 {
-#  ifdef PNG_DO_BC
-      for (i=128;i<256;++i) { .5 - l(i/255)/l(2)*65536*65536; }
-#  else
    4270715492U, 4222494797U, 4174646467U, 4127164793U, 4080044201U, 4033279239U,
    3986864580U, 3940795015U, 3895065449U, 3849670902U, 3804606499U, 3759867474U,
    3715449162U, 3671346997U, 3627556511U, 3584073329U, 3540893168U, 3498011834U,
    3455425220U, 3413129301U, 3371120137U, 3329393864U, 3287946700U, 3246774933U,
    3205874930U, 3165243125U, 3124876025U, 3084770202U, 3044922296U, 3005329011U,
    2965987113U, 2926893432U, 2888044853U, 2849438323U, 2811070844U, 2772939474U,
    2735041326U, 2697373562U, 2659933400U, 2622718104U, 2585724991U, 2548951424U,
    2512394810U, 2476052606U, 2439922311U, 2404001468U, 2368287663U, 2332778523U,
@@ -2204,17 +3356,16 @@ png_8bit_l2[128] =
    1144320946U, 1115161701U, 1086139034U, 1057251672U, 1028498358U, 999877854U,
    971388940U, 943030410U, 914801076U, 886699767U, 858725327U, 830876614U,
    803152505U, 775551890U, 748073672U, 720716771U, 693480120U, 666362667U,
    639363374U, 612481215U, 585715177U, 559064263U, 532527486U, 506103872U,
    479792461U, 453592303U, 427502463U, 401522014U, 375650043U, 349885648U,
    324227938U, 298676034U, 273229066U, 247886176U, 222646516U, 197509248U,
    172473545U, 147538590U, 122703574U, 97967701U, 73330182U, 48790236U,
    24347096U, 0U
-#  endif
 
 #if 0
    /* The following are the values for 16-bit tables - these work fine for the
     * 8-bit conversions but produce very slightly larger errors in the 16-bit
     * log (about 1.2 as opposed to 0.7 absolute error in the final value).  To
     * use these all the shifts below must be adjusted appropriately.
     */
    65166, 64430, 63700, 62976, 62257, 61543, 60835, 60132, 59434, 58741, 58054,
@@ -2227,28 +3378,28 @@ png_8bit_l2[128] =
    20636, 20175, 19718, 19262, 18808, 18357, 17908, 17461, 17016, 16573, 16132,
    15694, 15257, 14822, 14390, 13959, 13530, 13103, 12678, 12255, 11834, 11415,
    10997, 10582, 10168, 9756, 9346, 8937, 8531, 8126, 7723, 7321, 6921, 6523,
    6127, 5732, 5339, 4947, 4557, 4169, 3782, 3397, 3014, 2632, 2251, 1872, 1495,
    1119, 744, 372
 #endif
 };
 
-PNG_STATIC png_int_32
+static png_int_32
 png_log8bit(unsigned int x)
 {
    unsigned int lg2 = 0;
    /* Each time 'x' is multiplied by 2, 1 must be subtracted off the final log,
     * because the log is actually negate that means adding 1.  The final
     * returned value thus has the range 0 (for 255 input) to 7.994 (for 1
-    * input), return 7.99998 for the overflow (log 0) case - so the result is
+    * input), return -1 for the overflow (log 0) case, - so the result is
     * always at most 19 bits.
     */
    if ((x &= 0xff) == 0)
-      return 0xffffffff;
+      return -1;
 
    if ((x & 0xf0) == 0)
       lg2  = 4, x <<= 4;
 
    if ((x & 0xc0) == 0)
       lg2 += 2, x <<= 2;
 
    if ((x & 0x80) == 0)
@@ -2283,24 +3434,24 @@ png_log8bit(unsigned int x)
  * interpolation between the two end values 256/257 (result -368.61) and 258/257
  * (result 367.179).  The values used below are scaled by a further 64 to give
  * 16-bit precision in the interpolation:
  *
  * Start (256): -23591
  * Zero  (257):      0
  * End   (258):  23499
  */
-PNG_STATIC png_int_32
+static png_int_32
 png_log16bit(png_uint_32 x)
 {
    unsigned int lg2 = 0;
 
    /* As above, but now the input has 16 bits. */
    if ((x &= 0xffff) == 0)
-      return 0xffffffff;
+      return -1;
 
    if ((x & 0xff00) == 0)
       lg2  = 8, x <<= 8;
 
    if ((x & 0xf000) == 0)
       lg2 += 4, x <<= 4;
 
    if ((x & 0xc000) == 0)
@@ -2340,55 +3491,51 @@ png_log16bit(png_uint_32 x)
 }
 
 /* The 'exp()' case must invert the above, taking a 20-bit fixed point
  * logarithmic value and returning a 16 or 8-bit number as appropriate.  In
  * each case only the low 16 bits are relevant - the fraction - since the
  * integer bits (the top 4) simply determine a shift.
  *
  * The worst case is the 16-bit distinction between 65535 and 65534, this
- * requires perhaps spurious accuracy in the decoding of the logarithm to
+ * requires perhaps spurious accuracty in the decoding of the logarithm to
  * distinguish log2(65535/65534.5) - 10^-5 or 17 bits.  There is little chance
  * of getting this accuracy in practice.
  *
  * To deal with this the following exp() function works out the exponent of the
  * frational part of the logarithm by using an accurate 32-bit value from the
  * top four fractional bits then multiplying in the remaining bits.
  */
-static png_uint_32
+static const png_uint_32
 png_32bit_exp[16] =
 {
-#  ifdef PNG_DO_BC
-      for (i=0;i<16;++i) { .5 + e(-i/16*l(2))*2^32; }
-#  else
    /* NOTE: the first entry is deliberately set to the maximum 32-bit value. */
    4294967295U, 4112874773U, 3938502376U, 3771522796U, 3611622603U, 3458501653U,
    3311872529U, 3171459999U, 3037000500U, 2908241642U, 2784941738U, 2666869345U,
    2553802834U, 2445529972U, 2341847524U, 2242560872U
-#  endif
 };
 
 /* Adjustment table; provided to explain the numbers in the code below. */
-#ifdef PNG_DO_BC
+#if 0
 for (i=11;i>=0;--i){ print i, " ", (1 - e(-(2^i)/65536*l(2))) * 2^(32-i), "\n"}
    11 44937.64284865548751208448
    10 45180.98734845585101160448
     9 45303.31936980687359311872
     8 45364.65110595323018870784
     7 45395.35850361789624614912
     6 45410.72259715102037508096
     5 45418.40724413220722311168
     4 45422.25021786898173001728
     3 45424.17186732298419044352
     2 45425.13273269940811464704
     1 45425.61317555035558641664
     0 45425.85339951654943850496
 #endif
 
-PNG_STATIC png_uint_32
+static png_uint_32
 png_exp(png_fixed_point x)
 {
    if (x > 0 && x <= 0xfffff) /* Else overflow or zero (underflow) */
    {
       /* Obtain a 4-bit approximation */
       png_uint_32 e = png_32bit_exp[(x >> 12) & 0xf];
 
       /* Incorporate the low 12 bits - these decrease the returned value by
@@ -2426,31 +3573,31 @@ png_exp(png_fixed_point x)
    /* Check for overflow */
    if (x <= 0)
       return png_32bit_exp[0];
 
    /* Else underflow */
    return 0;
 }
 
-PNG_STATIC png_byte
+static png_byte
 png_exp8bit(png_fixed_point lg2)
 {
    /* Get a 32-bit value: */
    png_uint_32 x = png_exp(lg2);
 
    /* Convert the 32-bit value to 0..255 by multiplying by 256-1, note that the
     * second, rounding, step can't overflow because of the first, subtraction,
     * step.
     */
    x -= x >> 8;
    return (png_byte)((x + 0x7fffffU) >> 24);
 }
 
-PNG_STATIC png_uint_16
+static png_uint_16
 png_exp16bit(png_fixed_point lg2)
 {
    /* Get a 32-bit value: */
    png_uint_32 x = png_exp(lg2);
 
    /* Convert the 32-bit value to 0..65535 by multiplying by 65536-1: */
    x -= x >> 16;
    return (png_uint_16)((x + 32767U) >> 16);
@@ -2504,61 +3651,51 @@ png_gamma_16bit_correct(unsigned int val
 }
 
 /* This does the right thing based on the bit_depth field of the
  * png_struct, interpreting values as 8-bit or 16-bit.  While the result
  * is nominally a 16-bit value if bit depth is 8 then the result is
  * 8-bit (as are the arguments.)
  */
 png_uint_16 /* PRIVATE */
-png_gamma_correct(png_structp png_ptr, unsigned int value,
+png_gamma_correct(png_structrp png_ptr, unsigned int value,
     png_fixed_point gamma_val)
 {
    if (png_ptr->bit_depth == 8)
       return png_gamma_8bit_correct(value, gamma_val);
 
    else
       return png_gamma_16bit_correct(value, gamma_val);
 }
 
-/* This is the shared test on whether a gamma value is 'significant' - whether
- * it is worth doing gamma correction.
- */
-int /* PRIVATE */
-png_gamma_significant(png_fixed_point gamma_val)
-{
-   return gamma_val < PNG_FP_1 - PNG_GAMMA_THRESHOLD_FIXED ||
-       gamma_val > PNG_FP_1 + PNG_GAMMA_THRESHOLD_FIXED;
-}
-
 /* Internal function to build a single 16-bit table - the table consists of
- * 'num' 256-entry subtables, where 'num' is determined by 'shift' - the amount
+ * 'num' 256 entry subtables, where 'num' is determined by 'shift' - the amount
  * to shift the input values right (or 16-number_of_signifiant_bits).
  *
  * The caller is responsible for ensuring that the table gets cleaned up on
  * png_error (i.e. if one of the mallocs below fails) - i.e. the *table argument
  * should be somewhere that will be cleaned.
  */
 static void
-png_build_16bit_table(png_structp png_ptr, png_uint_16pp *ptable,
+png_build_16bit_table(png_structrp png_ptr, png_uint_16pp *ptable,
    PNG_CONST unsigned int shift, PNG_CONST png_fixed_point gamma_val)
 {
    /* Various values derived from 'shift': */
    PNG_CONST unsigned int num = 1U << (8U - shift);
    PNG_CONST unsigned int max = (1U << (16U - shift))-1U;
    PNG_CONST unsigned int max_by_2 = 1U << (15U-shift);
    unsigned int i;
 
    png_uint_16pp table = *ptable =
-       (png_uint_16pp)png_calloc(png_ptr, num * png_sizeof(png_uint_16p));
+       (png_uint_16pp)png_calloc(png_ptr, num * (sizeof (png_uint_16p)));
 
    for (i = 0; i < num; i++)
    {
       png_uint_16p sub_table = table[i] =
-          (png_uint_16p)png_malloc(png_ptr, 256 * png_sizeof(png_uint_16));
+          (png_uint_16p)png_malloc(png_ptr, 256 * (sizeof (png_uint_16)));
 
       /* The 'threshold' test is repeated here because it can arise for one of
        * the 16-bit tables even if the others don't hit it.
        */
       if (png_gamma_significant(gamma_val))
       {
          /* The old code would overflow at the end and this would cause the
           * 'pow' function to return a result >1, resulting in an
@@ -2601,34 +3738,34 @@ png_build_16bit_table(png_structp png_pt
       }
    }
 }
 
 /* NOTE: this function expects the *inverse* of the overall gamma transformation
  * required.
  */
 static void
-png_build_16to8_table(png_structp png_ptr, png_uint_16pp *ptable,
+png_build_16to8_table(png_structrp png_ptr, png_uint_16pp *ptable,
    PNG_CONST unsigned int shift, PNG_CONST png_fixed_point gamma_val)
 {
    PNG_CONST unsigned int num = 1U << (8U - shift);
    PNG_CONST unsigned int max = (1U << (16U - shift))-1U;
    unsigned int i;
    png_uint_32 last;
 
    png_uint_16pp table = *ptable =
-       (png_uint_16pp)png_calloc(png_ptr, num * png_sizeof(png_uint_16p));
-
-   /* 'num' is the number of tables and also the number of low bits of the
-    * input 16-bit value used to select a table.  Each table is itself indexed
-    * by the high 8 bits of the value.
+       (png_uint_16pp)png_calloc(png_ptr, num * (sizeof (png_uint_16p)));
+
+   /* 'num' is the number of tables and also the number of low bits of low
+    * bits of the input 16-bit value used to select a table.  Each table is
+    * itself index by the high 8 bits of the value.
     */
    for (i = 0; i < num; i++)
       table[i] = (png_uint_16p)png_malloc(png_ptr,
-          256 * png_sizeof(png_uint_16));
+          256 * (sizeof (png_uint_16)));
 
    /* 'gamma_val' is set to the reciprocal of the value calculated above, so
     * pow(out,g) is an *input* value.  'last' is the last input value set.
     *
     * In the loop 'i' is used to find output values.  Since the output is
     * 8-bit there are only 256 possible values.  The tables are set up to
     * select the closest possible output value for each input by finding
     * the input value at the boundary between each pair of output values
@@ -2665,37 +3802,37 @@ png_build_16to8_table(png_structp png_pt
    {
       table[last & (0xff >> shift)][last >> (8U - shift)] = 65535U;
       last++;
    }
 }
 
 /* Build a single 8-bit table: same as the 16-bit case but much simpler (and
  * typically much faster).  Note that libpng currently does no sBIT processing
- * (apparently contrary to the spec) so a 256-entry table is always generated.
+ * (apparently contrary to the spec) so a 256 entry table is always generated.
  */
 static void
-png_build_8bit_table(png_structp png_ptr, png_bytepp ptable,
+png_build_8bit_table(png_structrp png_ptr, png_bytepp ptable,
    PNG_CONST png_fixed_point gamma_val)
 {
    unsigned int i;
    png_bytep table = *ptable = (png_bytep)png_malloc(png_ptr, 256);
 
    if (png_gamma_significant(gamma_val)) for (i=0; i<256; i++)
       table[i] = png_gamma_8bit_correct(i, gamma_val);
 
    else for (i=0; i<256; ++i)
       table[i] = (png_byte)i;
 }
 
 /* Used from png_read_destroy and below to release the memory used by the gamma
  * tables.
  */
 void /* PRIVATE */
-png_destroy_gamma_table(png_structp png_ptr)
+png_destroy_gamma_table(png_structrp png_ptr)
 {
    png_free(png_ptr, png_ptr->gamma_table);
    png_ptr->gamma_table = NULL;
 
    if (png_ptr->gamma_16_table != NULL)
    {
       int i;
       int istop = (1 << (8 - png_ptr->gamma_shift));
@@ -2741,17 +3878,17 @@ png_destroy_gamma_table(png_structp png_
 }
 
 /* We build the 8- or 16-bit gamma tables here.  Note that for 16-bit
  * tables, we don't make a full table if we are reducing to 8-bit in
  * the future.  Note also how the gamma_16 tables are segmented so that
  * we don't need to allocate > 64K chunks for a full 16-bit table.
  */
 void /* PRIVATE */
-png_build_gamma_table(png_structp png_ptr, int bit_depth)
+png_build_gamma_table(png_structrp png_ptr, int bit_depth)
 {
   png_debug(1, "in png_build_gamma_table");
 
   /* Remove any existing table; this copes with multiple calls to
    * png_read_update_info.  The warning is because building the gamma tables
    * multiple times is a performance hit - it's harmless but the ability to call
    * png_read_update_info() multiple times is new in 1.5.6 so it seems sensible
    * to warn if the app introduces such a hit.
@@ -2760,30 +3897,30 @@ png_build_gamma_table(png_structp png_pt
   {
     png_warning(png_ptr, "gamma table being rebuilt");
     png_destroy_gamma_table(png_ptr);
   }
 
   if (bit_depth <= 8)
   {
      png_build_8bit_table(png_ptr, &png_ptr->gamma_table,
-         png_ptr->screen_gamma > 0 ?  png_reciprocal2(png_ptr->gamma,
+         png_ptr->screen_gamma > 0 ?  png_reciprocal2(png_ptr->colorspace.gamma,
          png_ptr->screen_gamma) : PNG_FP_1);
 
 #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
    defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \
    defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
      if (png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY))
      {
         png_build_8bit_table(png_ptr, &png_ptr->gamma_to_1,
-            png_reciprocal(png_ptr->gamma));
+            png_reciprocal(png_ptr->colorspace.gamma));
 
         png_build_8bit_table(png_ptr, &png_ptr->gamma_from_1,
             png_ptr->screen_gamma > 0 ?  png_reciprocal(png_ptr->screen_gamma) :
-            png_ptr->gamma/* Probably doing rgb_to_gray */);
+            png_ptr->colorspace.gamma/* Probably doing rgb_to_gray */);
      }
 #endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */
   }
   else
   {
      png_byte shift, sig_bit;
 
      if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
@@ -2801,17 +3938,17 @@ png_build_gamma_table(png_structp png_pt
 
      /* 16-bit gamma code uses this equation:
       *
       *   ov = table[(iv & 0xff) >> gamma_shift][iv >> 8]
       *
       * Where 'iv' is the input color value and 'ov' is the output value -
       * pow(iv, gamma).
       *
-      * Thus the gamma table consists of up to 256 256-entry tables.  The table
+      * Thus the gamma table consists of up to 256 256 entry tables.  The table
       * is selected by the (8-gamma_shift) most significant of the low 8 bits of
       * the color value then indexed by the upper 8 bits:
       *
       *   table[low bits][high 8 bits]
       *
       * So the table 'n' corresponds to all those 'iv' of:
       *
       *   <all high 8-bit values><n << gamma_shift>..<(n+1 << gamma_shift)-1>
@@ -2842,60 +3979,320 @@ png_build_gamma_table(png_structp png_pt
      /* NOTE: prior to 1.5.4 this test used to include PNG_BACKGROUND (now
       * PNG_COMPOSE).  This effectively smashed the background calculation for
       * 16-bit output because the 8-bit table assumes the result will be reduced
       * to 8 bits.
       */
      if (png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8))
 #endif
          png_build_16to8_table(png_ptr, &png_ptr->gamma_16_table, shift,
-         png_ptr->screen_gamma > 0 ? png_product2(png_ptr->gamma,
+         png_ptr->screen_gamma > 0 ? png_product2(png_ptr->colorspace.gamma,
          png_ptr->screen_gamma) : PNG_FP_1);
 
 #ifdef PNG_16BIT_SUPPORTED
      else
          png_build_16bit_table(png_ptr, &png_ptr->gamma_16_table, shift,
-         png_ptr->screen_gamma > 0 ? png_reciprocal2(png_ptr->gamma,
+         png_ptr->screen_gamma > 0 ? png_reciprocal2(png_ptr->colorspace.gamma,
          png_ptr->screen_gamma) : PNG_FP_1);
 #endif
 
 #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
    defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \
    defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
      if (png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY))
      {
         png_build_16bit_table(png_ptr, &png_ptr->gamma_16_to_1, shift,
-            png_reciprocal(png_ptr->gamma));
+            png_reciprocal(png_ptr->colorspace.gamma));
 
         /* Notice that the '16 from 1' table should be full precision, however
          * the lookup on this table still uses gamma_shift, so it can't be.
          * TODO: fix this.
          */
         png_build_16bit_table(png_ptr, &png_ptr->gamma_16_from_1, shift,
             png_ptr->screen_gamma > 0 ? png_reciprocal(png_ptr->screen_gamma) :
-            png_ptr->gamma/* Probably doing rgb_to_gray */);
+            png_ptr->colorspace.gamma/* Probably doing rgb_to_gray */);
      }
 #endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */
   }
 }
 #endif /* READ_GAMMA */
-#endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
 
 /* HARDWARE OPTION SUPPORT */
 #ifdef PNG_SET_OPTION_SUPPORTED
 int PNGAPI
-png_set_option(png_structp png_ptr, int option, int onoff)
+png_set_option(png_structrp png_ptr, int option, int onoff)
 {
    if (png_ptr != NULL && option >= 0 && option < PNG_OPTION_NEXT &&
       (option & 1) == 0)
    {
       int mask = 3 << option;
       int setting = (2 + (onoff != 0)) << option;
       int current = png_ptr->options;
 
       png_ptr->options = (png_byte)((current & ~mask) | setting);
 
       return (current & mask) >> option;
    }
 
    return PNG_OPTION_INVALID;
 }
 #endif
+
+/* sRGB support */
+#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\
+   defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
+/* sRGB conversion tables; these are machine generated with the code in
+ * contrib/tools/makesRGB.c.  The actual sRGB transfer curve defined in the
+ * specification (see the article at http://en.wikipedia.org/wiki/SRGB)
+ * is used, not the gamma=1/2.2 approximation use elsewhere in libpng.
+ * The sRGB to linear table is exact (to the nearest 16 bit linear fraction).
+ * The inverse (linear to sRGB) table has accuracies as follows:
+ *
+ * For all possible (255*65535+1) input values:
+ *
+ *    error: -0.515566 - 0.625971, 79441 (0.475369%) of readings inexact
+ *
+ * For the input values corresponding to the 65536 16-bit values:
+ *
+ *    error: -0.513727 - 0.607759, 308 (0.469978%) of readings inexact
+ *
+ * In all cases the inexact readings are off by one.
+ */
+
+#ifdef PNG_SIMPLIFIED_READ_SUPPORTED
+/* The convert-to-sRGB table is only currently required for read. */
+const png_uint_16 png_sRGB_table[256] =
+{
+   0,20,40,60,80,99,119,139,
+   159,179,199,219,241,264,288,313,
+   340,367,396,427,458,491,526,562,
+   599,637,677,718,761,805,851,898,
+   947,997,1048,1101,1156,1212,1270,1330,
+   1391,1453,1517,1583,1651,1720,1790,1863,
+   1937,2013,2090,2170,2250,2333,2418,2504,
+   2592,2681,2773,2866,2961,3058,3157,3258,
+   3360,3464,3570,3678,3788,3900,4014,4129,
+   4247,4366,4488,4611,4736,4864,4993,5124,
+   5257,5392,5530,5669,5810,5953,6099,6246,
+   6395,6547,6700,6856,7014,7174,7335,7500,
+   7666,7834,8004,8177,8352,8528,8708,8889,
+   9072,9258,9445,9635,9828,10022,10219,10417,
+   10619,10822,11028,11235,11446,11658,11873,12090,
+   12309,12530,12754,12980,13209,13440,13673,13909,
+   14146,14387,14629,14874,15122,15371,15623,15878,
+   16135,16394,16656,16920,17187,17456,17727,18001,
+   18277,18556,18837,19121,19407,19696,19987,20281,
+   20577,20876,21177,21481,21787,22096,22407,22721,
+   23038,23357,23678,24002,24329,24658,24990,25325,
+   25662,26001,26344,26688,27036,27386,27739,28094,
+   28452,28813,29176,29542,29911,30282,30656,31033,
+   31412,31794,32179,32567,32957,33350,33745,34143,
+   34544,34948,35355,35764,36176,36591,37008,37429,
+   37852,38278,38706,39138,39572,40009,40449,40891,
+   41337,41785,42236,42690,43147,43606,44069,44534,
+   45002,45473,45947,46423,46903,47385,47871,48359,
+   48850,49344,49841,50341,50844,51349,51858,52369,
+   52884,53401,53921,54445,54971,55500,56032,56567,
+   57105,57646,58190,58737,59287,59840,60396,60955,
+   61517,62082,62650,63221,63795,64372,64952,65535
+};
+
+#endif /* simplified read only */
+
+/* The base/delta tables are required for both read and write (but currently
+ * only the simplified versions.)
+ */
+const png_uint_16 png_sRGB_base[512] =
+{
+   128,1782,3383,4644,5675,6564,7357,8074,
+   8732,9346,9921,10463,10977,11466,11935,12384,
+   12816,13233,13634,14024,14402,14769,15125,15473,
+   15812,16142,16466,16781,17090,17393,17690,17981,
+   18266,18546,18822,19093,19359,19621,19879,20133,
+   20383,20630,20873,21113,21349,21583,21813,22041,
+   22265,22487,22707,22923,23138,23350,23559,23767,
+   23972,24175,24376,24575,24772,24967,25160,25352,
+   25542,25730,25916,26101,26284,26465,26645,26823,
+   27000,27176,27350,27523,27695,27865,28034,28201,
+   28368,28533,28697,28860,29021,29182,29341,29500,
+   29657,29813,29969,30123,30276,30429,30580,30730,
+   30880,31028,31176,31323,31469,31614,31758,31902,
+   32045,32186,32327,32468,32607,32746,32884,33021,
+   33158,33294,33429,33564,33697,33831,33963,34095,
+   34226,34357,34486,34616,34744,34873,35000,35127,
+   35253,35379,35504,35629,35753,35876,35999,36122,
+   36244,36365,36486,36606,36726,36845,36964,37083,
+   37201,37318,37435,37551,37668,37783,37898,38013,
+   38127,38241,38354,38467,38580,38692,38803,38915,
+   39026,39136,39246,39356,39465,39574,39682,39790,
+   39898,40005,40112,40219,40325,40431,40537,40642,
+   40747,40851,40955,41059,41163,41266,41369,41471,
+   41573,41675,41777,41878,41979,42079,42179,42279,
+   42379,42478,42577,42676,42775,42873,42971,43068,
+   43165,43262,43359,43456,43552,43648,43743,43839,
+   43934,44028,44123,44217,44311,44405,44499,44592,
+   44685,44778,44870,44962,45054,45146,45238,45329,
+   45420,45511,45601,45692,45782,45872,45961,46051,
+   46140,46229,46318,46406,46494,46583,46670,46758,
+   46846,46933,47020,47107,47193,47280,47366,47452,
+   47538,47623,47709,47794,47879,47964,48048,48133,
+   48217,48301,48385,48468,48552,48635,48718,48801,
+   48884,48966,49048,49131,49213,49294,49376,49458,
+   49539,49620,49701,49782,49862,49943,50023,50103,
+   50183,50263,50342,50422,50501,50580,50659,50738,
+   50816,50895,50973,51051,51129,51207,51285,51362,
+   51439,51517,51594,51671,51747,51824,51900,51977,
+   52053,52129,52205,52280,52356,52432,52507,52582,
+   52657,52732,52807,52881,52956,53030,53104,53178,
+   53252,53326,53400,53473,53546,53620,53693,53766,
+   53839,53911,53984,54056,54129,54201,54273,54345,
+   54417,54489,54560,54632,54703,54774,54845,54916,
+   54987,55058,55129,55199,55269,55340,55410,55480,
+   55550,55620,55689,55759,55828,55898,55967,56036,
+   56105,56174,56243,56311,56380,56448,56517,56585,
+   56653,56721,56789,56857,56924,56992,57059,57127,
+   57194,57261,57328,57395,57462,57529,57595,57662,
+   57728,57795,57861,57927,57993,58059,58125,58191,
+   58256,58322,58387,58453,58518,58583,58648,58713,
+   58778,58843,58908,58972,59037,59101,59165,59230,
+   59294,59358,59422,59486,59549,59613,59677,59740,
+   59804,59867,59930,59993,60056,60119,60182,60245,
+   60308,60370,60433,60495,60558,60620,60682,60744,
+   60806,60868,60930,60992,61054,61115,61177,61238,
+   61300,61361,61422,61483,61544,61605,61666,61727,
+   61788,61848,61909,61969,62030,62090,62150,62211,
+   62271,62331,62391,62450,62510,62570,62630,62689,
+   62749,62808,62867,62927,62986,63045,63104,63163,
+   63222,63281,63340,63398,63457,63515,63574,63632,
+   63691,63749,63807,63865,63923,63981,64039,64097,
+   64155,64212,64270,64328,64385,64443,64500,64557,
+   64614,64672,64729,64786,64843,64900,64956,65013,
+   65070,65126,65183,65239,65296,65352,65409,65465
+};
+
+const png_byte png_sRGB_delta[512] =
+{
+   207,201,158,129,113,100,90,82,77,72,68,64,61,59,56,54,
+   52,50,49,47,46,45,43,42,41,40,39,39,38,37,36,36,
+   35,34,34,33,33,32,32,31,31,30,30,30,29,29,28,28,
+   28,27,27,27,27,26,26,26,25,25,25,25,24,24,24,24,
+   23,23,23,23,23,22,22,22,22,22,22,21,21,21,21,21,
+   21,20,20,20,20,20,20,20,20,19,19,19,19,19,19,19,
+   19,18,18,18,18,18,18,18,18,18,18,17,17,17,17,17,
+   17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
+   16,16,16,16,15,15,15,15,15,15,15,15,15,15,15,15,
+   15,15,15,15,14,14,14,14,14,14,14,14,14,14,14,14,
+   14,14,14,14,14,14,14,13,13,13,13,13,13,13,13,13,
+   13,13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,
+   12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
+   12,12,12,12,12,12,12,12,12,12,12,12,11,11,11,11,
+   11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+   11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
+   11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+   10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+   10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
+   10,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+   9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+   9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+   9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+   9,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+   8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+   8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+   8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+   8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+   8,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,
+   7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+   7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+   7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
+};
+#endif /* SIMPLIFIED READ/WRITE sRGB support */
+
+/* SIMPLIFIED READ/WRITE SUPPORT */
+#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\
+   defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
+static int
+png_image_free_function(png_voidp argument)
+{
+   png_imagep image = png_voidcast(png_imagep, argument);
+   png_controlp cp = image->opaque;
+   png_control c;
+
+   /* Double check that we have a png_ptr - it should be impossible to get here
+    * without one.
+    */
+   if (cp->png_ptr == NULL)
+      return 0;
+
+   /* First free any data held in the control structure. */
+#  ifdef PNG_STDIO_SUPPORTED
+      if (cp->owned_file)
+      {
+         FILE *fp = png_voidcast(FILE*, cp->png_ptr->io_ptr);
+         cp->owned_file = 0;
+
+         /* Ignore errors here. */
+         if (fp != NULL)
+         {
+            cp->png_ptr->io_ptr = NULL;
+            (void)fclose(fp);
+         }
+      }
+#  endif
+
+   /* Copy the control structure so that the original, allocated, version can be
+    * safely freed.  Notice that a png_error here stops the remainder of the
+    * cleanup, but this is probably fine because that would indicate bad memory
+    * problems anyway.
+    */
+   c = *cp;
+   image->opaque = &c;
+   png_free(c.png_ptr, cp);
+
+   /* Then the structures, calling the correct API. */
+   if (c.for_write)
+   {
+#     ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
+         png_destroy_write_struct(&c.png_ptr, &c.info_ptr);
+#     else
+         png_error(c.png_ptr, "simplified write not supported");
+#     endif
+   }
+   else
+   {
+#     ifdef PNG_SIMPLIFIED_READ_SUPPORTED
+         png_destroy_read_struct(&c.png_ptr, &c.info_ptr, NULL);
+#     else
+         png_error(c.png_ptr, "simplified read not supported");
+#     endif
+   }
+
+   /* Success. */
+   return 1;
+}
+
+void PNGAPI
+png_image_free(png_imagep image)
+{
+   /* Safely call the real function, but only if doing so is safe at this point
+    * (if not inside an error handling context).  Otherwise assume
+    * png_safe_execute will call this API after the return.
+    */
+   if (image != NULL && image->opaque != NULL &&
+      image->opaque->error_buf == NULL)
+   {
+      /* Ignore errors here: */
+      (void)png_safe_execute(image, png_image_free_function, image);
+      image->opaque = NULL;
+   }
+}
+
+int /* PRIVATE */
+png_image_error(png_imagep image, png_const_charp error_message)
+{
+   /* Utility to log an error. */
+   png_safecat(image->message, (sizeof image->message), 0, error_message);
+   image->warning_or_error |= PNG_IMAGE_ERROR;
+   png_image_free(image);
+   return 0;
+}
+
+#endif /* SIMPLIFIED READ/WRITE */
+#endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
--- a/media/libpng/png.h
+++ b/media/libpng/png.h
@@ -1,22 +1,22 @@
 
 /* png.h - header file for PNG reference library
  *
- * libpng version 1.5.17 - June 27, 2013
+ * libpng version 1.6.6 - September 16, 2013
  * Copyright (c) 1998-2013 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
  * This code is released under the libpng license (See LICENSE, below)
  *
  * Authors and maintainers:
  *   libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  *   libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
- *   libpng versions 0.97, January 1998, through 1.5.17 - June 27, 2013: Glenn
+ *   libpng versions 0.97, January 1998, through 1.6.6 - September 16, 2013: Glenn
  *   See also "Contributing Authors", below.
  *
  * Note about libpng version numbers:
  *
  *   Due to various miscommunications, unforeseen code incompatibilities
  *   and occasional factors outside the authors' control, version numbering
  *   on the library has not always been consistent and straightforward.
  *   The following table summarizes matters since version 0.89c, which was
@@ -161,43 +161,33 @@
  *    1.5.5rc01               15    10505  15.so.15.5[.0]
  *    1.5.5                   15    10505  15.so.15.5[.0]
  *    1.5.6beta01-07          15    10506  15.so.15.6[.0]
  *    1.5.6rc01-03            15    10506  15.so.15.6[.0]
  *    1.5.6                   15    10506  15.so.15.6[.0]
  *    1.5.7beta01-05          15    10507  15.so.15.7[.0]
  *    1.5.7rc01-03            15    10507  15.so.15.7[.0]
  *    1.5.7                   15    10507  15.so.15.7[.0]
- *    1.5.8beta01             15    10508  15.so.15.8[.0]
- *    1.5.8rc01               15    10508  15.so.15.8[.0]
- *    1.5.8                   15    10508  15.so.15.8[.0]
- *    1.5.9beta01-02          15    10509  15.so.15.9[.0]
- *    1.5.9rc01               15    10509  15.so.15.9[.0]
- *    1.5.9                   15    10509  15.so.15.9[.0]
- *    1.5.10beta01-05         15    10510  15.so.15.10[.0]
- *    1.5.10                  15    10510  15.so.15.10[.0]
- *    1.5.11beta01            15    10511  15.so.15.11[.0]
- *    1.5.11rc01-05           15    10511  15.so.15.11[.0]
- *    1.5.11                  15    10511  15.so.15.11[.0]
- *    1.5.12                  15    10512  15.so.15.12[.0]
- *    1.5.13beta01-02         15    10513  15.so.15.13[.0]
- *    1.5.13rc01              15    10513  15.so.15.13[.0]
- *    1.5.13                  15    10513  15.so.15.13[.0]
- *    1.5.14beta01-08         15    10514  15.so.15.14[.0]
- *    1.5.14rc01-03           15    10514  15.so.15.14[.0]
- *    1.5.14                  15    10514  15.so.15.14[.0]
- *    1.5.15beta01-09         15    10515  15.so.15.15[.0]
- *    1.5.15rc01              15    10515  15.so.15.15[.0]
- *    1.5.15                  15    10515  15.so.15.15[.0]
- *    1.5.16beta01-06         15    10516  15.so.15.16[.0]
- *    1.5.16rc01              15    10516  15.so.15.16[.0]
- *    1.5.16                  15    10516  15.so.15.16[.0]
- *    1.5.17beta01            15    10517  15.so.15.17[.0]
- *    1.5.17rc01-03           15    10517  15.so.15.17[.0]
- *    1.5.17                  15    10517  15.so.15.17[.0]
+ *    1.6.0beta01-40          16    10600  16.so.16.0[.0]
+ *    1.6.0rc01-08            16    10600  16.so.16.0[.0]
+ *    1.6.0                   16    10600  16.so.16.0[.0]
+ *    1.6.1beta01-09          16    10601  16.so.16.1[.0]
+ *    1.6.1rc01               16    10601  16.so.16.1[.0]
+ *    1.6.1                   16    10601  16.so.16.1[.0]
+ *    1.6.2beta01             16    10602  16.so.16.2[.0]
+ *    1.6.2rc01-06            16    10602  16.so.16.2[.0]
+ *    1.6.2                   16    10602  16.so.16.2[.0]
+ *    1.6.3beta01-11          16    10603  16.so.16.3[.0]
+ *    1.6.3rc01               16    10603  16.so.16.3[.0]
+ *    1.6.3                   16    10603  16.so.16.3[.0]
+ *    1.6.4beta01-02          16    10604  16.so.16.4[.0]
+ *    1.6.4rc01               16    10604  16.so.16.4[.0]
+ *    1.6.4                   16    10604  16.so.16.4[.0]
+ *    1.6.5                   16    10605  16.so.16.5[.0]
+ *    1.6.6                   16    10606  16.so.16.6[.0]
  *
  *   Henceforth the source version will match the shared-library major
  *   and minor numbers; the shared-library major version number will be
  *   used for changes in backward compatibility, as it is intended.  The
  *   PNG_LIBPNG_VER macro, which is not used within libpng but is available
  *   for applications, is an unsigned integer of the form xyyzz corresponding
  *   to the source version x.y.z (leading zeros in y and z).  Beta versions
  *   were given the previous public release number plus a letter, until
@@ -219,17 +209,17 @@
 /*
  * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  *
  * If you modify libpng you may insert additional notices immediately following
  * this sentence.
  *
  * This code is released under the libpng license.
  *
- * libpng versions 1.2.6, August 15, 2004, through 1.5.17, June 27, 2013, are
+ * libpng versions 1.2.6, August 15, 2004, through 1.6.6, September 16, 2013, are
  * Copyright (c) 2004, 2006-2013 Glenn Randers-Pehrson, and are
  * distributed according to the same disclaimer and license as libpng-1.2.5
  * with the following individual added to the list of Contributing Authors:
  *
  *    Cosmin Truta
  *
  * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
@@ -331,51 +321,52 @@
  *
  * Thanks to Frank J. T. Wojcik for helping with the documentation.
  */
 
 /*
  * Y2K compliance in libpng:
  * =========================
  *
- *    June 27, 2013
+ *    September 16, 2013
  *
  *    Since the PNG Development group is an ad-hoc body, we can't make
  *    an official declaration.
  *
  *    This is your unofficial assurance that libpng from version 0.71 and
- *    upward through 1.5.17 are Y2K compliant.  It is my belief that
+ *    upward through 1.6.6 are Y2K compliant.  It is my belief that
  *    earlier versions were also Y2K compliant.
  *
  *    Libpng only has two year fields.  One is a 2-byte unsigned integer
- *    that will hold years up to 65535.  The other holds the date in text
- *    format, and will hold years up to 9999.
+ *    that will hold years up to 65535.  The other, which is deprecated,
+ *    holds the date in text format, and will hold years up to 9999.
  *
  *    The integer is
  *        "png_uint_16 year" in png_time_struct.
  *
  *    The string is
- *        "char time_buffer[29]" in png_struct.  This will be no
- *    longer used in libpng-1.6.0 and will be removed from libpng-1.7.0.
+ *        "char time_buffer[29]" in png_struct.  This is no longer used
+ *    in libpng-1.6.x and will be removed from libpng-1.7.0.
  *
  *    There are seven time-related functions:
- *        png.c: png_convert_to_rfc_1123() in png.c
- *          (formerly png_convert_to_rfc_1152() in error)
+ *        png.c: png_convert_to_rfc_1123_buffer() in png.c
+ *          (formerly png_convert_to_rfc_1123() prior to libpng-1.5.x and
+ *          png_convert_to_rfc_1152() in error prior to libpng-0.98)
  *        png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  *        png_convert_from_time_t() in pngwrite.c
  *        png_get_tIME() in pngget.c
  *        png_handle_tIME() in pngrutil.c, called in pngread.c
  *        png_set_tIME() in pngset.c
  *        png_write_tIME() in pngwutil.c, called in pngwrite.c
  *
  *    All handle dates properly in a Y2K environment.  The
  *    png_convert_from_time_t() function calls gmtime() to convert from system
  *    clock time, which returns (year - 1900), which we properly convert to
- *    the full 4-digit year.  There is a possibility that applications using
- *    libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
+ *    the full 4-digit year.  There is a possibility that libpng applications
+ *    are not passing 4-digit years into the png_convert_to_rfc_1123_buffer()
  *    function, or that they are incorrectly passing only a 2-digit year
  *    instead of "year - 1900" into the png_convert_from_struct_tm() function,
  *    but this is not under our control.  The libpng documentation has always
  *    stated that it works with 4-digit years, and the APIs have been
  *    documented as such.
  *
  *    The tIME chunk itself is also Y2K compliant.  It uses a 2-byte unsigned
  *    integer to hold the year, and can hold years as large as 65535.
@@ -396,27 +387,27 @@
  * with some code on which to build.  This file is useful for looking
  * at the actual function definitions and structure components.
  *
  * If you just need to read a PNG file and don't want to read the documentation
  * skip to the end of this file and read the section entitled 'simplified API'.
  */
 
 /* Version information for png.h - this should match the version in png.c */
-#define PNG_LIBPNG_VER_STRING "1.5.17"
+#define PNG_LIBPNG_VER_STRING "1.6.6"
 #define PNG_HEADER_VERSION_STRING \
-     " libpng version 1.5.17 - June 27, 2013\n"
-
-#define PNG_LIBPNG_VER_SONUM   15
-#define PNG_LIBPNG_VER_DLLNUM  15
+     " libpng version 1.6.6 - September 16, 2013\n"
+
+#define PNG_LIBPNG_VER_SONUM   16
+#define PNG_LIBPNG_VER_DLLNUM  16
 
 /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
 #define PNG_LIBPNG_VER_MAJOR   1
-#define PNG_LIBPNG_VER_MINOR   5
-#define PNG_LIBPNG_VER_RELEASE 17
+#define PNG_LIBPNG_VER_MINOR   6
+#define PNG_LIBPNG_VER_RELEASE 6
 
 /* This should match the numeric part of the final component of
  * PNG_LIBPNG_VER_STRING, omitting any leading zero:
  */
 
 #define PNG_LIBPNG_VER_BUILD  0
 
 /* Release Status */
@@ -437,44 +428,27 @@
 #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
 
 /* Careful here.  At one time, Guy wanted to use 082, but that would be octal.
  * We must not include leading zeros.
  * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  * version 1.0.0 was mis-numbered 100 instead of 10000).  From
  * version 1.0.1 it's    xxyyzz, where x=major, y=minor, z=release
  */
-#define PNG_LIBPNG_VER 10517 /* 1.5.17 */
-
-#ifndef MOZPNGCONF_H
-#   include "mozpngconf.h"
-#endif
+#define PNG_LIBPNG_VER 10606 /* 1.6.6 */
+
+/* Library configuration: these options cannot be changed after
+ * the library has been built.
+ */
 
 #ifndef PNG_VERSION_INFO_ONLY
-#  ifndef PNG_BUILDING_SYMBOL_TABLE
-  /*
-   *   Standard header files (not needed for the version info or while
-   *   building symbol table -- see scripts/pnglibconf.dfa)
-   */
-#    ifdef PNG_SETJMP_SUPPORTED
-#      include <setjmp.h>
-#    endif
-
-    /* Need the time information for converting tIME chunks, it
-     * defines struct tm:
-     */
-#    ifdef PNG_CONVERT_tIME_SUPPORTED
-       /* "time.h" functions are not supported on all operating systems */
-#      include <time.h>
-#    endif
-#  endif
-
-/* Machine specific configuration. */
+   /* Machine specific configuration. */
+#  include "mozpngconf.h"
 #  include "pngconf.h"
-#endif /* PNG_VERSION_INFO_ONLY */
+#endif
 
 /*
  * Added at libpng-1.2.8
  *
  * Ref MSDN: Private as priority over Special
  * VS_FF_PRIVATEBUILD File *was not* built using standard release
  * procedures. If this value is given, the StringFileInfo block must
  * contain a PrivateBuild string.
@@ -511,16 +485,17 @@ extern "C" {
 
 /* This file is arranged in several sections:
  *
  * 1. Any configuration options that can be specified by for the application
  *    code when it is built.  (Build time configuration is in pnglibconf.h)
  * 2. Type definitions (base types are defined in pngconf.h), structure
  *    definitions.
  * 3. Exported library functions.
+ * 4. Simplified API.
  *
  * The library source code has additional files (principally pngpriv.h) that
  * allow configuration of the library.
  */
 /* Section 1: run time configuration
  * See pnglibconf.h for build time configuration
  *
  * Run time configuration allows the application to choose between
@@ -564,87 +539,128 @@ extern "C" {
 /* blend_op flags from inside fcTL */
 #define PNG_BLEND_OP_SOURCE        0x00
 #define PNG_BLEND_OP_OVER          0x01
 #endif /* PNG_APNG_SUPPORTED */
 
 /* This triggers a compiler error in png.c, if png.c and png.h
  * do not agree upon the version number.
  */
-typedef char* png_libpng_version_1_5_17;
+typedef char* png_libpng_version_1_6_6;
+
+/* Basic control structions.  Read libpng-manual.txt or libpng.3 for more info.
+ *
+ * png_struct is the cache of information used while reading or writing a single
+ * PNG file.  One of these is always required, although the simplified API
+ * (below) hides the creation and destruction of it.
+ */
+typedef struct png_struct_def png_struct;
+typedef const png_struct * png_const_structp;
+typedef png_struct * png_structp;
+typedef png_struct * * png_structpp;
+
+/* png_info contains information read from or to be written to a PNG file.  One
+ * or more of these must exist while reading or creating a PNG file.  The
+ * information is not used by libpng during read but is used to control what
+ * gets written when a PNG file is created.  "png_get_" function calls read
+ * information during read and "png_set_" functions calls write information
+ * when creating a PNG.
+ * been moved into a separate header file that is not accessible to
+ * applications.  Read libpng-manual.txt or libpng.3 for more info.
+ */
+typedef struct png_info_def png_info;
+typedef png_info * png_infop;
+typedef const png_info * png_const_infop;
+typedef png_info * * png_infopp;
+
+/* Types with names ending 'p' are pointer types.  The corresponding types with
+ * names ending 'rp' are identical pointer types except that the pointer is
+ * marked 'restrict', which means that it is the only pointer to the object
+ * passed to the function.  Applications should not use the 'restrict' types;
+ * it is always valid to pass 'p' to a pointer with a function argument of the
+ * corresponding 'rp' type.  Different compilers have different rules with
+ * regard to type matching in the presence of 'restrict'.  For backward
+ * compatibility libpng callbacks never have 'restrict' in their parameters and,
+ * consequentially, writing portable application code is extremely difficult if
+ * an attempt is made to use 'restrict'.
+ */
+typedef png_struct * PNG_RESTRICT png_structrp;
+typedef const png_struct * PNG_RESTRICT png_const_structrp;
+typedef png_info * PNG_RESTRICT png_inforp;
+typedef const png_info * PNG_RESTRICT png_const_inforp;
 
 /* Three color definitions.  The order of the red, green, and blue, (and the
  * exact size) is not important, although the size of the fields need to
  * be png_byte or png_uint_16 (as defined below).
  */
 typedef struct png_color_struct
 {
    png_byte red;
    png_byte green;
    png_byte blue;
 } png_color;
-typedef png_color FAR * png_colorp;
-typedef PNG_CONST png_color FAR * png_const_colorp;
-typedef png_color FAR * FAR * png_colorpp;
+typedef png_color * png_colorp;
+typedef const png_color * png_const_colorp;
+typedef png_color * * png_colorpp;
 
 typedef struct png_color_16_struct
 {
    png_byte index;    /* used for palette files */
    png_uint_16 red;   /* for use in red green blue files */
    png_uint_16 green;
    png_uint_16 blue;
    png_uint_16 gray;  /* for use in grayscale files */
 } png_color_16;
-typedef png_color_16 FAR * png_color_16p;
-typedef PNG_CONST png_color_16 FAR * png_const_color_16p;
-typedef png_color_16 FAR * FAR * png_color_16pp;
+typedef png_color_16 * png_color_16p;
+typedef const png_color_16 * png_const_color_16p;
+typedef png_color_16 * * png_color_16pp;
 
 typedef struct png_color_8_struct
 {
    png_byte red;   /* for use in red green blue files */
    png_byte green;
    png_byte blue;
    png_byte gray;  /* for use in grayscale files */
    png_byte alpha; /* for alpha channel files */
 } png_color_8;
-typedef png_color_8 FAR * png_color_8p;
-typedef PNG_CONST png_color_8 FAR * png_const_color_8p;
-typedef png_color_8 FAR * FAR * png_color_8pp;
+typedef png_color_8 * png_color_8p;
+typedef const png_color_8 * png_const_color_8p;
+typedef png_color_8 * * png_color_8pp;
 
 /*
  * The following two structures are used for the in-core representation
  * of sPLT chunks.
  */
 typedef struct png_sPLT_entry_struct
 {
    png_uint_16 red;
    png_uint_16 green;
    png_uint_16 blue;
    png_uint_16 alpha;
    png_uint_16 frequency;
 } png_sPLT_entry;
-typedef png_sPLT_entry FAR * png_sPLT_entryp;
-typedef PNG_CONST png_sPLT_entry FAR * png_const_sPLT_entryp;
-typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
+typedef png_sPLT_entry * png_sPLT_entryp;
+typedef const png_sPLT_entry * png_const_sPLT_entryp;
+typedef png_sPLT_entry * * png_sPLT_entrypp;
 
 /*  When the depth of the sPLT palette is 8 bits, the color and alpha samples
  *  occupy the LSB of their respective members, and the MSB of each member
  *  is zero-filled.  The frequency member always occupies the full 16 bits.
  */
 
 typedef struct png_sPLT_struct
 {
    png_charp name;           /* palette name */
    png_byte depth;           /* depth of palette samples */
    png_sPLT_entryp entries;  /* palette entries */
    png_int_32 nentries;      /* number of palette entries */
 } png_sPLT_t;
-typedef png_sPLT_t FAR * png_sPLT_tp;
-typedef PNG_CONST png_sPLT_t FAR * png_const_sPLT_tp;
-typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
+typedef png_sPLT_t * png_sPLT_tp;
+typedef const png_sPLT_t * png_const_sPLT_tp;
+typedef png_sPLT_t * * png_sPLT_tpp;
 
 #ifdef PNG_TEXT_SUPPORTED
 /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  * and whether that contents is compressed or not.  The "key" field
  * points to a regular zero-terminated C string.  The "text" fields can be a
  * regular C string, an empty string, or a NULL pointer.
  * However, the structure returned by png_get_text() will always contain
  * the "text" field as a regular zero-terminated C string (possibly
@@ -671,19 +687,19 @@ typedef struct png_text_struct
                               or a NULL pointer */
    png_size_t text_length; /* length of the text string */
    png_size_t itxt_length; /* length of the itxt string */
    png_charp lang;         /* language code, 0-79 characters
                               or a NULL pointer */
    png_charp lang_key;     /* keyword translated UTF-8 string, 0 or more
                               chars or a NULL pointer */
 } png_text;
-typedef png_text FAR * png_textp;
-typedef PNG_CONST png_text FAR * png_const_textp;
-typedef png_text FAR * FAR * png_textpp;
+typedef png_text * png_textp;
+typedef const png_text * png_const_textp;
+typedef png_text * * png_textpp;
 #endif
 
 /* Supported compression types for text in PNG files (tEXt, and zTXt).
  * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
 #define PNG_TEXT_COMPRESSION_NONE_WR -3
 #define PNG_TEXT_COMPRESSION_zTXt_WR -2
 #define PNG_TEXT_COMPRESSION_NONE    -1
 #define PNG_TEXT_COMPRESSION_zTXt     0
@@ -701,59 +717,54 @@ typedef struct png_time_struct
 {
    png_uint_16 year; /* full year, as in, 1995 */
    png_byte month;   /* month of year, 1 - 12 */
    png_byte day;     /* day of month, 1 - 31 */
    png_byte hour;    /* hour of day, 0 - 23 */
    png_byte minute;  /* minute of hour, 0 - 59 */
    png_byte second;  /* second of minute, 0 - 60 (for leap seconds) */
 } png_time;
-typedef png_time FAR * png_timep;
-typedef PNG_CONST png_time FAR * png_const_timep;
-typedef png_time FAR * FAR * png_timepp;
-
-#if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) || \
-    defined(PNG_HANDLE_AS_UNKNOWN_SUPPORTED)
+typedef png_time * png_timep;
+typedef const png_time * png_const_timep;
+typedef png_time * * png_timepp;
+
+#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
 /* png_unknown_chunk is a structure to hold queued chunks for which there is
  * no specific support.  The idea is that we can use this to queue
  * up private chunks for output even though the library doesn't actually
  * know about their semantics.
+ *
+ * The data in the structure is set by libpng on read and used on write.
  */
 typedef struct png_unknown_chunk_t
 {
-    png_byte name[5];
-    png_byte *data;
+    png_byte name[5]; /* Textual chunk name with '\0' terminator */
+    png_byte *data;   /* Data, should not be modified on read! */
     png_size_t size;
 
-    /* libpng-using applications should NOT directly modify this byte. */
+    /* On write 'location' must be set using the flag values listed below.
+     * Notice that on read it is set by libpng however the values stored have
+     * more bits set than are listed below.  Always treat the value as a
+     * bitmask.  On write set only one bit - setting multiple bits may cause the
+     * chunk to be written in multiple places.
+     */
     png_byte location; /* mode of operation at read time */
 }
-
-
 png_unknown_chunk;
-typedef png_unknown_chunk FAR * png_unknown_chunkp;
-typedef PNG_CONST png_unknown_chunk FAR * png_const_unknown_chunkp;
-typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
+
+typedef png_unknown_chunk * png_unknown_chunkp;
+typedef const png_unknown_chunk * png_const_unknown_chunkp;
+typedef png_unknown_chunk * * png_unknown_chunkpp;
 #endif
 
-/* Values for the unknown chunk location byte */
-
+/* Flag values for the unknown chunk location byte. */
 #define PNG_HAVE_IHDR  0x01
 #define PNG_HAVE_PLTE  0x02
 #define PNG_AFTER_IDAT 0x08
 
-/* The complete definition of png_info has, as of libpng-1.5.0,
- * been moved into a separate header file that is not accessible to
- * applications.  Read libpng-manual.txt or libpng.3 for more info.
- */
-typedef struct png_info_def png_info;
-typedef png_info FAR * png_infop;
-typedef PNG_CONST png_info FAR * png_const_infop;
-typedef png_info FAR * FAR * png_infopp;
-
 /* Maximum positive integer used in PNG is (2^31)-1 */
 #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
 #define PNG_UINT_32_MAX ((png_uint_32)(-1))
 #define PNG_SIZE_MAX ((png_size_t)(-1))
 
 /* These are constants for fixed point values encoded in the
  * PNG specification manner (x100000)
  */
@@ -863,26 +874,18 @@ typedef struct png_row_info_struct
    png_uint_32 width;    /* width of row */
    png_size_t rowbytes;  /* number of bytes in row */
    png_byte color_type;  /* color type of row */
    png_byte bit_depth;   /* bit depth of row */
    png_byte channels;    /* number of channels (1, 2, 3, or 4) */
    png_byte pixel_depth; /* bits per pixel (depth * channels) */
 } png_row_info;
 
-typedef png_row_info FAR * png_row_infop;
-typedef png_row_info FAR * FAR * png_row_infopp;
-
-/* The complete definition of png_struct has, as of libpng-1.5.0,
- * been moved into a separate header file that is not accessible to
- * applications.  Read libpng-manual.txt or libpng.3 for more info.
- */
-typedef struct png_struct_def png_struct;
-typedef PNG_CONST png_struct FAR * png_const_structp;
-typedef png_struct FAR * png_structp;
+typedef png_row_info * png_row_infop;
+typedef png_row_info * * png_row_infopp;
 
 /* These are the function types for the I/O functions and for the functions
  * that allow the user to override the default I/O functions with his or her
  * own.  The png_error_ptr type should match that of user-supplied warning
  * and error functions, while the png_rw_ptr type should match that of the
  * user read/write data functions.  Note that the 'write' function must not
  * modify the buffer it is passed. The 'read' function, on the other hand, is
  * expected to return the read data in the buffer.
@@ -923,17 +926,18 @@ typedef PNG_CALLBACK(void, *png_user_tra
     png_bytep));
 #endif
 
 #ifdef PNG_USER_CHUNKS_SUPPORTED
 typedef PNG_CALLBACK(int, *png_user_chunk_ptr, (png_structp,
     png_unknown_chunkp));
 #endif
 #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
-typedef PNG_CALLBACK(void, *png_unknown_chunk_ptr, (png_structp));
+/* not used anywhere */
+/* typedef PNG_CALLBACK(void, *png_unknown_chunk_ptr, (png_structp)); */
 #endif
 
 #ifdef PNG_SETJMP_SUPPORTED
 /* This must match the function definition in <setjmp.h>, and the application
  * must include this before png.h to obtain the definition of jmp_buf.  The
  * function is required to be PNG_NORETURN, but this is not checked.  If the
  * function does return the application will crash via an abort() or similar
  * system level call.
@@ -979,18 +983,16 @@ PNG_FUNCTION(void, (PNGCAPI *png_longjmp
  * platforms.  In 1.5 the zlib default malloc (which just calls malloc and
  * ignores the first argument) should be completely compatible with the
  * following.
  */
 typedef PNG_CALLBACK(png_voidp, *png_malloc_ptr, (png_structp,
     png_alloc_size_t));
 typedef PNG_CALLBACK(void, *png_free_ptr, (png_structp, png_voidp));
 
-typedef png_struct FAR * FAR * png_structpp;
-
 /* Section 3: exported functions
  * Here are the function definitions most commonly used.  This is not
  * the place to find out how to use libpng.  See libpng-manual.txt for the
  * full explanation, see example.c for the summary.  This just provides
  * a simple one line description of the use of each function.
  *
  * The PNG_EXPORT() and PNG_EXPORTA() macros used below are defined in
  * pngconf.h and in the *.dfn files in the scripts directory.
@@ -1016,17 +1018,17 @@ typedef png_struct FAR * FAR * png_struc
  */
 
 /* Returns the version number of the library */
 PNG_EXPORT(1, png_uint_32, png_access_version_number, (void));
 
 /* Tell lib we have already handled the first <num_bytes> magic bytes.
  * Handling more than 8 bytes from the beginning of the file is an error.
  */
-PNG_EXPORT(2, void, png_set_sig_bytes, (png_structp png_ptr, int num_bytes));
+PNG_EXPORT(2, void, png_set_sig_bytes, (png_structrp png_ptr, int num_bytes));
 
 /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  * PNG file.  Returns zero if the supplied bytes match the 8-byte PNG
  * signature, and non-zero otherwise.  Having num_to_check == 0 or
  * start > 7 will always fail (ie return non-zero).
  */
 PNG_EXPORT(3, int, png_sig_cmp, (png_const_bytep sig, png_size_t start,
     png_size_t num_to_check));
@@ -1044,51 +1046,51 @@ PNG_EXPORTA(4, png_structp, png_create_r
 
 /* Allocate and initialize png_ptr struct for writing, and any other memory */
 PNG_EXPORTA(5, png_structp, png_create_write_struct,
     (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn,
     png_error_ptr warn_fn),
     PNG_ALLOCATED);
 
 PNG_EXPORT(6, png_size_t, png_get_compression_buffer_size,
-    (png_const_structp png_ptr));
-
-PNG_EXPORT(7, void, png_set_compression_buffer_size, (png_structp png_ptr,
+    (png_const_structrp png_ptr));
+
+PNG_EXPORT(7, void, png_set_compression_buffer_size, (png_structrp png_ptr,
     png_size_t size));
 
 /* Moved from pngconf.h in 1.4.0 and modified to ensure setjmp/longjmp
  * match up.
  */
 #ifdef PNG_SETJMP_SUPPORTED
 /* This function returns the jmp_buf built in to *png_ptr.  It must be
  * supplied with an appropriate 'longjmp' function to use on that jmp_buf
  * unless the default error function is overridden in which case NULL is
  * acceptable.  The size of the jmp_buf is checked against the actual size
  * allocated by the library - the call will return NULL on a mismatch
  * indicating an ABI mismatch.
  */
-PNG_EXPORT(8, jmp_buf*, png_set_longjmp_fn, (png_structp png_ptr,
+PNG_EXPORT(8, jmp_buf*, png_set_longjmp_fn, (png_structrp png_ptr,
     png_longjmp_ptr longjmp_fn, size_t jmp_buf_size));
 #  define png_jmpbuf(png_ptr) \
-      (*png_set_longjmp_fn((png_ptr), longjmp, sizeof (jmp_buf)))
+      (*png_set_longjmp_fn((png_ptr), longjmp, (sizeof (jmp_buf))))
 #else
 #  define png_jmpbuf(png_ptr) \
       (LIBPNG_WAS_COMPILED_WITH__PNG_NO_SETJMP)
 #endif
 /* This function should be used by libpng applications in place of
  * longjmp(png_ptr->jmpbuf, val).  If longjmp_fn() has been set, it
  * will use it; otherwise it will call PNG_ABORT().  This function was
  * added in libpng-1.5.0.
  */
-PNG_EXPORTA(9, void, png_longjmp, (png_structp png_ptr, int val),
+PNG_EXPORTA(9, void, png_longjmp, (png_const_structrp png_ptr, int val),
     PNG_NORETURN);
 
 #ifdef PNG_READ_SUPPORTED
 /* Reset the compression stream */
-PNG_EXPORT(10, int, png_reset_zstream, (png_structp png_ptr));
+PNG_EXPORTA(10, int, png_reset_zstream, (png_structrp png_ptr), PNG_DEPRECATED);
 #endif
 
 /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
 #ifdef PNG_USER_MEM_SUPPORTED
 PNG_EXPORTA(11, png_structp, png_create_read_struct_2,
     (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn,
     png_error_ptr warn_fn,
     png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn),
@@ -1096,106 +1098,117 @@ PNG_EXPORTA(11, png_structp, png_create_
 PNG_EXPORTA(12, png_structp, png_create_write_struct_2,
     (png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn,
     png_error_ptr warn_fn,
     png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn),
     PNG_ALLOCATED);
 #endif
 
 /* Write the PNG file signature. */
-PNG_EXPORT(13, void, png_write_sig, (png_structp png_ptr));
+PNG_EXPORT(13, void, png_write_sig, (png_structrp png_ptr));
 
 /* Write a PNG chunk - size, type, (optional) data, CRC. */
-PNG_EXPORT(14, void, png_write_chunk, (png_structp png_ptr, png_const_bytep
+PNG_EXPORT(14, void, png_write_chunk, (png_structrp png_ptr, png_const_bytep
     chunk_name, png_const_bytep data, png_size_t length));
 
 /* Write the start of a PNG chunk - length and chunk name. */
-PNG_EXPORT(15, void, png_write_chunk_start, (png_structp png_ptr,
+PNG_EXPORT(15, void, png_write_chunk_start, (png_structrp png_ptr,
     png_const_bytep chunk_name, png_uint_32 length));
 
 /* Write the data of a PNG chunk started with png_write_chunk_start(). */
-PNG_EXPORT(16, void, png_write_chunk_data, (png_structp png_ptr,
+PNG_EXPORT(16, void, png_write_chunk_data, (png_structrp png_ptr,
     png_const_bytep data, png_size_t length));
 
 /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
-PNG_EXPORT(17, void, png_write_chunk_end, (png_structp png_ptr));
+PNG_EXPORT(17, void, png_write_chunk_end, (png_structrp png_ptr));
 
 /* Allocate and initialize the info structure */
-PNG_EXPORTA(18, png_infop, png_create_info_struct, (png_structp png_ptr),
+PNG_EXPORTA(18, png_infop, png_create_info_struct, (png_const_structrp png_ptr),
     PNG_ALLOCATED);
 
-PNG_EXPORT(19, void, png_info_init_3, (png_infopp info_ptr,
-    png_size_t png_info_struct_size));
+/* DEPRECATED: this function allowed init structures to be created using the
+ * default allocation method (typically malloc).  Use is deprecated in 1.6.0 and
+ * the API will be removed in the future.
+ */
+PNG_EXPORTA(19, void, png_info_init_3, (png_infopp info_ptr,
+    png_size_t png_info_struct_size), PNG_DEPRECATED);
 
 /* Writes all the PNG information before the image. */
 PNG_EXPORT(20, void, png_write_info_before_PLTE,
-    (png_structp png_ptr, png_infop info_ptr));
+    (png_structrp png_ptr, png_const_inforp info_ptr));
 PNG_EXPORT(21, void, png_write_info,
-    (png_structp png_ptr, png_infop info_ptr));
+    (png_structrp png_ptr, png_const_inforp info_ptr));
 
 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
 /* Read the information before the actual image data. */
 PNG_EXPORT(22, void, png_read_info,
-    (png_structp png_ptr, png_infop info_ptr));
+    (png_structrp png_ptr, png_inforp info_ptr));
 #endif
 
 #ifdef PNG_TIME_RFC1123_SUPPORTED
-PNG_EXPORT(23, png_const_charp, png_convert_to_rfc1123,
-    (png_structp png_ptr,
+   /* Convert to a US string format: there is no localization support in this
+    * routine.  The original implementation used a 29 character buffer in
+    * png_struct, this will be removed in future versions.
+    */
+#if PNG_LIBPNG_VER < 10700
+/* To do: remove this from libpng17 (and from libpng17/png.c and pngstruct.h) */
+PNG_EXPORTA(23, png_const_charp, png_convert_to_rfc1123, (png_structrp png_ptr,
+    png_const_timep ptime),PNG_DEPRECATED);
+#endif
+PNG_EXPORT(241, int, png_convert_to_rfc1123_buffer, (char out[29],
     png_const_timep ptime));
 #endif
 
 #ifdef PNG_CONVERT_tIME_SUPPORTED
 /* Convert from a struct tm to png_time */
 PNG_EXPORT(24, void, png_convert_from_struct_tm, (png_timep ptime,
-    PNG_CONST struct tm FAR * ttime));
+    const struct tm * ttime));
 
 /* Convert from time_t to png_time.  Uses gmtime() */
-PNG_EXPORT(25, void, png_convert_from_time_t,
-    (png_timep ptime, time_t ttime));
+PNG_EXPORT(25, void, png_convert_from_time_t, (png_timep ptime, time_t ttime));
 #endif /* PNG_CONVERT_tIME_SUPPORTED */
 
 #ifdef PNG_READ_EXPAND_SUPPORTED
 /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
-PNG_EXPORT(26, void, png_set_expand, (png_structp png_ptr));
-PNG_EXPORT(27, void, png_set_expand_gray_1_2_4_to_8, (png_structp png_ptr));
-PNG_EXPORT(28, void, png_set_palette_to_rgb, (png_structp png_ptr));
-PNG_EXPORT(29, void, png_set_tRNS_to_alpha, (png_structp png_ptr));
+PNG_EXPORT(26, void, png_set_expand, (png_structrp png_ptr));
+PNG_EXPORT(27, void, png_set_expand_gray_1_2_4_to_8, (png_structrp png_ptr));
+PNG_EXPORT(28, void, png_set_palette_to_rgb, (png_structrp png_ptr));
+PNG_EXPORT(29, void, png_set_tRNS_to_alpha, (png_structrp png_ptr));
 #endif
 
 #ifdef PNG_READ_EXPAND_16_SUPPORTED
 /* Expand to 16-bit channels, forces conversion of palette to RGB and expansion
  * of a tRNS chunk if present.
  */
-PNG_EXPORT(221, void, png_set_expand_16, (png_structp png_ptr));
+PNG_EXPORT(221, void, png_set_expand_16, (png_structrp png_ptr));
 #endif
 
 #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
 /* Use blue, green, red order for pixels. */
-PNG_EXPORT(30, void, png_set_bgr, (png_structp png_ptr));
+PNG_EXPORT(30, void, png_set_bgr, (png_structrp png_ptr));
 #endif
 
 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
 /* Expand the grayscale to 24-bit RGB if necessary. */
-PNG_EXPORT(31, void, png_set_gray_to_rgb, (png_structp png_ptr));
+PNG_EXPORT(31, void, png_set_gray_to_rgb, (png_structrp png_ptr));
 #endif
 
 #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
 /* Reduce RGB to grayscale. */
 #define PNG_ERROR_ACTION_NONE  1
 #define PNG_ERROR_ACTION_WARN  2
 #define PNG_ERROR_ACTION_ERROR 3
 #define PNG_RGB_TO_GRAY_DEFAULT (-1)/*for red/green coefficients*/
 
-PNG_FP_EXPORT(32, void, png_set_rgb_to_gray, (png_structp png_ptr,
+PNG_FP_EXPORT(32, void, png_set_rgb_to_gray, (png_structrp png_ptr,
     int error_action, double red, double green))
-PNG_FIXED_EXPORT(33, void, png_set_rgb_to_gray_fixed, (png_structp png_ptr,
+PNG_FIXED_EXPORT(33, void, png_set_rgb_to_gray_fixed, (png_structrp png_ptr,
     int error_action, png_fixed_point red, png_fixed_point green))
 
-PNG_EXPORT(34, png_byte, png_get_rgb_to_gray_status, (png_const_structp
+PNG_EXPORT(34, png_byte, png_get_rgb_to_gray_status, (png_const_structrp
     png_ptr));
 #endif
 
 #ifdef PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED
 PNG_EXPORT(35, void, png_build_grayscale_palette, (int bit_depth,
     png_colorp palette));
 #endif
 
@@ -1250,23 +1263,23 @@ PNG_EXPORT(35, void, png_build_grayscale
  */
 #define PNG_ALPHA_PNG           0 /* according to the PNG standard */
 #define PNG_ALPHA_STANDARD      1 /* according to Porter/Duff */
 #define PNG_ALPHA_ASSOCIATED    1 /* as above; this is the normal practice */
 #define PNG_ALPHA_PREMULTIPLIED 1 /* as above */
 #define PNG_ALPHA_OPTIMIZED     2 /* 'PNG' for opaque pixels, else 'STANDARD' */
 #define PNG_ALPHA_BROKEN        3 /* the alpha channel is gamma encoded */
 
-PNG_FP_EXPORT(227, void, png_set_alpha_mode, (png_structp png_ptr, int mode,
+PNG_FP_EXPORT(227, void, png_set_alpha_mode, (png_structrp png_ptr, int mode,
     double output_gamma))
-PNG_FIXED_EXPORT(228, void, png_set_alpha_mode_fixed, (png_structp png_ptr,
+PNG_FIXED_EXPORT(228, void, png_set_alpha_mode_fixed, (png_structrp png_ptr,
     int mode, png_fixed_point output_gamma))
 #endif
 
-#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_ALPHA_MODE_SUPPORTED)
+#if defined(PNG_GAMMA_SUPPORTED) || defined(PNG_READ_ALPHA_MODE_SUPPORTED)
 /* The output_gamma value is a screen gamma in libpng terminology: it expresses
  * how to decode the output values, not how they are encoded.  The values used
  * correspond to the normal numbers used to describe the overall gamma of a
  * computer display system; for example 2.2 for an sRGB conformant system.  The
  * values are scaled by 100000 in the _fixed version of the API (so 220000 for
  * sRGB.)
  *
  * The inverse of the value is always used to provide a default for the PNG file
@@ -1404,119 +1417,117 @@ PNG_FIXED_EXPORT(228, void, png_set_alph
  *    is easier than achieving the same effect with png_set_gamma.  You must use
  *    PNG_ALPHA_PNG for the first call - internal checking in png_set_alpha will
  *    fire if more than one call to png_set_alpha_mode and png_set_background is
  *    made in the same read operation, however multiple calls with PNG_ALPHA_PNG
  *    are ignored.
  */
 
 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
-PNG_EXPORT(36, void, png_set_strip_alpha, (png_structp png_ptr));
+PNG_EXPORT(36, void, png_set_strip_alpha, (png_structrp png_ptr));
 #endif
 
 #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
     defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
-PNG_EXPORT(37, void, png_set_swap_alpha, (png_structp png_ptr));
+PNG_EXPORT(37, void, png_set_swap_alpha, (png_structrp png_ptr));
 #endif
 
 #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
     defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
-PNG_EXPORT(38, void, png_set_invert_alpha, (png_structp png_ptr));
+PNG_EXPORT(38, void, png_set_invert_alpha, (png_structrp png_ptr));
 #endif
 
 #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
 /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
-PNG_EXPORT(39, void, png_set_filler, (png_structp png_ptr, png_uint_32 filler,
+PNG_EXPORT(39, void, png_set_filler, (png_structrp png_ptr, png_uint_32 filler,
     int flags));
 /* The values of the PNG_FILLER_ defines should NOT be changed */
 #  define PNG_FILLER_BEFORE 0
 #  define PNG_FILLER_AFTER 1
 /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
-PNG_EXPORT(40, void, png_set_add_alpha,
-    (png_structp png_ptr, png_uint_32 filler,
-    int flags));
+PNG_EXPORT(40, void, png_set_add_alpha, (png_structrp png_ptr,
+    png_uint_32 filler, int flags));
 #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
 
 #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
 /* Swap bytes in 16-bit depth files. */
-PNG_EXPORT(41, void, png_set_swap, (png_structp png_ptr));
+PNG_EXPORT(41, void, png_set_swap, (png_structrp png_ptr));
 #endif
 
 #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
 /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
-PNG_EXPORT(42, void, png_set_packing, (png_structp png_ptr));
+PNG_EXPORT(42, void, png_set_packing, (png_structrp png_ptr));
 #endif
 
 #if defined(PNG_READ_PACKSWAP_SUPPORTED) || \
     defined(PNG_WRITE_PACKSWAP_SUPPORTED)
 /* Swap packing order of pixels in bytes. */
-PNG_EXPORT(43, void, png_set_packswap, (png_structp png_ptr));
+PNG_EXPORT(43, void, png_set_packswap, (png_structrp png_ptr));
 #endif
 
 #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
 /* Converts files to legal bit depths. */
-PNG_EXPORT(44, void, png_set_shift, (png_structp png_ptr, png_const_color_8p
+PNG_EXPORT(44, void, png_set_shift, (png_structrp png_ptr, png_const_color_8p
     true_bits));
 #endif
 
 #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
     defined(PNG_WRITE_INTERLACING_SUPPORTED)
 /* Have the code handle the interlacing.  Returns the number of passes.
  * MUST be called before png_read_update_info or png_start_read_image,
  * otherwise it will not have the desired effect.  Note that it is still
  * necessary to call png_read_row or png_read_rows png_get_image_height
  * times for each pass.
 */
-PNG_EXPORT(45, int, png_set_interlace_handling, (png_structp png_ptr));
+PNG_EXPORT(45, int, png_set_interlace_handling, (png_structrp png_ptr));
 #endif
 
 #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
 /* Invert monochrome files */
-PNG_EXPORT(46, void, png_set_invert_mono, (png_structp png_ptr));
+PNG_EXPORT(46, void, png_set_invert_mono, (png_structrp png_ptr));
 #endif
 
 #ifdef PNG_READ_BACKGROUND_SUPPORTED
 /* Handle alpha and tRNS by replacing with a background color.  Prior to
  * libpng-1.5.4 this API must not be called before the PNG file header has been
  * read.  Doing so will result in unexpected behavior and possible warnings or
  * errors if the PNG file contains a bKGD chunk.
  */
-PNG_FP_EXPORT(47, void, png_set_background, (png_structp png_ptr,
+PNG_FP_EXPORT(47, void, png_set_background, (png_structrp png_ptr,
     png_const_color_16p background_color, int background_gamma_code,
     int need_expand, double background_gamma))
-PNG_FIXED_EXPORT(215, void, png_set_background_fixed, (png_structp png_ptr,
+PNG_FIXED_EXPORT(215, void, png_set_background_fixed, (png_structrp png_ptr,
     png_const_color_16p background_color, int background_gamma_code,
     int need_expand, png_fixed_point background_gamma))
 #endif
 #ifdef PNG_READ_BACKGROUND_SUPPORTED
 #  define PNG_BACKGROUND_GAMMA_UNKNOWN 0
 #  define PNG_BACKGROUND_GAMMA_SCREEN  1
 #  define PNG_BACKGROUND_GAMMA_FILE    2
 #  define PNG_BACKGROUND_GAMMA_UNIQUE  3
 #endif
 
 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
 /* Scale a 16-bit depth file down to 8-bit, accurately. */
-PNG_EXPORT(229, void, png_set_scale_16, (png_structp png_ptr));
+PNG_EXPORT(229, void, png_set_scale_16, (png_structrp png_ptr));
 #endif
 
 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
 #define PNG_READ_16_TO_8 SUPPORTED /* Name prior to 1.5.4 */
 /* Strip the second byte of information from a 16-bit depth file. */
-PNG_EXPORT(48, void, png_set_strip_16, (png_structp png_ptr));
+PNG_EXPORT(48, void, png_set_strip_16, (png_structrp png_ptr));
 #endif
 
 #ifdef PNG_READ_QUANTIZE_SUPPORTED
 /* Turn on quantizing, and reduce the palette to the number of colors
  * available.
  */
-PNG_EXPORT(49, void, png_set_quantize,
-    (png_structp png_ptr, png_colorp palette,
-    int num_palette, int maximum_colors, png_const_uint_16p histogram,
-    int full_quantize));
+PNG_EXPORT(49, void, png_set_quantize, (png_structrp png_ptr,
+    png_colorp palette, int num_palette, int maximum_colors,
+    png_const_uint_16p histogram, int full_quantize));
 #endif
 
 #ifdef PNG_READ_GAMMA_SUPPORTED
 /* The threshold on gamma processing is configurable but hard-wired into the
  * library.  The following is the floating point variant.
  */
 #define PNG_GAMMA_THRESHOLD (PNG_GAMMA_THRESHOLD_FIXED*.00001)
 
@@ -1526,94 +1537,92 @@ PNG_EXPORT(49, void, png_set_quantize,
  * the file header has been read - use with care  - call before reading the PNG
  * file for best results!
  *
  * These routines accept the same gamma values as png_set_alpha_mode (described
  * above).  The PNG_GAMMA_ defines and PNG_DEFAULT_sRGB can be passed to either
  * API (floating point or fixed.)  Notice, however, that the 'file_gamma' value
  * is the inverse of a 'screen gamma' value.
  */
-PNG_FP_EXPORT(50, void, png_set_gamma,
-    (png_structp png_ptr, double screen_gamma,
-    double override_file_gamma))
-PNG_FIXED_EXPORT(208, void, png_set_gamma_fixed, (png_structp png_ptr,
+PNG_FP_EXPORT(50, void, png_set_gamma, (png_structrp png_ptr,
+    double screen_gamma, double override_file_gamma))
+PNG_FIXED_EXPORT(208, void, png_set_gamma_fixed, (png_structrp png_ptr,
     png_fixed_point screen_gamma, png_fixed_point override_file_gamma))
 #endif
 
 #ifdef PNG_WRITE_FLUSH_SUPPORTED
 /* Set how many lines between output flushes - 0 for no flushing */
-PNG_EXPORT(51, void, png_set_flush, (png_structp png_ptr, int nrows));
+PNG_EXPORT(51, void, png_set_flush, (png_structrp png_ptr, int nrows));
 /* Flush the current PNG output buffer */
-PNG_EXPORT(52, void, png_write_flush, (png_structp png_ptr));
+PNG_EXPORT(52, void, png_write_flush, (png_structrp png_ptr));
 #endif
 
 /* Optional update palette with requested transformations */
-PNG_EXPORT(53, void, png_start_read_image, (png_structp png_ptr));
+PNG_EXPORT(53, void, png_start_read_image, (png_structrp png_ptr));
 
 /* Optional call to update the users info structure */
-PNG_EXPORT(54, void, png_read_update_info,
-    (png_structp png_ptr, png_infop info_ptr));
+PNG_EXPORT(54, void, png_read_update_info, (png_structrp png_ptr,
+    png_inforp info_ptr));
 
 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
 /* Read one or more rows of image data. */
-PNG_EXPORT(55, void, png_read_rows, (png_structp png_ptr, png_bytepp row,
+PNG_EXPORT(55, void, png_read_rows, (png_structrp png_ptr, png_bytepp row,
     png_bytepp display_row, png_uint_32 num_rows));
 #endif
 
 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
 /* Read a row of data. */
-PNG_EXPORT(56, void, png_read_row, (png_structp png_ptr, png_bytep row,
+PNG_EXPORT(56, void, png_read_row, (png_structrp png_ptr, png_bytep row,
     png_bytep display_row));
 #endif
 
 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
 /* Read the whole image into memory at once. */
-PNG_EXPORT(57, void, png_read_image, (png_structp png_ptr, png_bytepp image));
+PNG_EXPORT(57, void, png_read_image, (png_structrp png_ptr, png_bytepp image));
 #endif
 
 /* Write a row of image data */
-PNG_EXPORT(58, void, png_write_row,
-    (png_structp png_ptr, png_const_bytep row));
+PNG_EXPORT(58, void, png_write_row, (png_structrp png_ptr,
+    png_const_bytep row));
 
 /* Write a few rows of image data: (*row) is not written; however, the type
  * is declared as writeable to maintain compatibility with previous versions
  * of libpng and to allow the 'display_row' array from read_rows to be passed
  * unchanged to write_rows.
  */
-PNG_EXPORT(59, void, png_write_rows, (png_structp png_ptr, png_bytepp row,
+PNG_EXPORT(59, void, png_write_rows, (png_structrp png_ptr, png_bytepp row,
     png_uint_32 num_rows));
 
 /* Write the image data */
-PNG_EXPORT(60, void, png_write_image,
-    (png_structp png_ptr, png_bytepp image));
+PNG_EXPORT(60, void, png_write_image, (png_structrp png_ptr, png_bytepp image));
 
 /* Write the end of the PNG file. */
-PNG_EXPORT(61, void, png_write_end,
-    (png_structp png_ptr, png_infop info_ptr));
+PNG_EXPORT(61, void, png_write_end, (png_structrp png_ptr,
+    png_inforp info_ptr));
 
 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
 /* Read the end of the PNG file. */
-PNG_EXPORT(62, void, png_read_end, (png_structp png_ptr, png_infop info_ptr));
+PNG_EXPORT(62, void, png_read_end, (png_structrp png_ptr, png_inforp info_ptr));
 #endif
 
 /* Free any memory associated with the png_info_struct */
-PNG_EXPORT(63, void, png_destroy_info_struct, (png_structp png_ptr,
+PNG_EXPORT(63, void, png_destroy_info_struct, (png_const_structrp png_ptr,
     png_infopp info_ptr_ptr));
 
 /* Free any memory associated with the png_struct and the png_info_structs */
 PNG_EXPORT(64, void, png_destroy_read_struct, (png_structpp png_ptr_ptr,
     png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
 
 /* Free any memory associated with the png_struct and the png_info_structs */
 PNG_EXPORT(65, void, png_destroy_write_struct, (png_structpp png_ptr_ptr,
     png_infopp info_ptr_ptr));
 
 /* Set the libpng method of handling chunk CRC errors */
-PNG_EXPORT(66, void, png_set_crc_action,
-    (png_structp png_ptr, int crit_action, int ancil_action));
+PNG_EXPORT(66, void, png_set_crc_action, (png_structrp png_ptr, int crit_action,
+    int ancil_action));
 
 /* Values for png_set_crc_action() say how to handle CRC errors in
  * ancillary and critical chunks, and whether to use the data contained
  * therein.  Note that it is impossible to "discard" data in a critical
  * chunk.  For versions prior to 0.90, the action was always error/quit,
  * whereas in version 0.90 and later, the action for CRC errors in ancillary
  * chunks is warn/discard.  These values should NOT be changed.
  *
@@ -1632,18 +1641,18 @@ PNG_EXPORT(66, void, png_set_crc_action,
  * Those users who are tight on memory or want faster performance at the
  * expense of compression can modify them.  See the compression library
  * header file (zlib.h) for an explination of the compression functions.
  */
 
 /* Set the filtering method(s) used by libpng.  Currently, the only valid
  * value for "method" is 0.
  */
-PNG_EXPORT(67, void, png_set_filter,
-    (png_structp png_ptr, int method, int filters));
+PNG_EXPORT(67, void, png_set_filter, (png_structrp png_ptr, int method,
+    int filters));
 
 /* Flags for png_set_filter() to say which filters to use.  The flags
  * are chosen so that they don't conflict with real filter types
  * below, in case they are supplied instead of the #defined constants.
  * These values should NOT be changed.
  */
 #define PNG_NO_FILTERS     0x00
 #define PNG_FILTER_NONE    0x08
@@ -1688,23 +1697,23 @@ PNG_EXPORT(67, void, png_set_filter,
  *
  * A negative weight or cost indicates the default value is to be used, and
  * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  * The default values for both weights and costs are currently 1.0, but may
  * change if good general weighting/cost heuristics can be found.  If both
  * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  * to the UNWEIGHTED method, but with added encoding time/computation.
  */
-PNG_FP_EXPORT(68, void, png_set_filter_heuristics, (png_structp png_ptr,
+PNG_FP_EXPORT(68, void, png_set_filter_heuristics, (png_structrp png_ptr,
     int heuristic_method, int num_weights, png_const_doublep filter_weights,
     png_const_doublep filter_costs))
 PNG_FIXED_EXPORT(209, void, png_set_filter_heuristics_fixed,
-    (png_structp png_ptr,
-    int heuristic_method, int num_weights, png_const_fixed_point_p
-    filter_weights, png_const_fixed_point_p filter_costs))
+    (png_structrp png_ptr, int heuristic_method, int num_weights,
+    png_const_fixed_point_p filter_weights,
+    png_const_fixed_point_p filter_costs))
 #endif /*  PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
 
 /* Heuristic used for row filter selection.  These defines should NOT be
  * changed.
  */
 #define PNG_FILTER_HEURISTIC_DEFAULT    0  /* Currently "UNWEIGHTED" */
 #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1  /* Used by libpng < 0.95 */
 #define PNG_FILTER_HEURISTIC_WEIGHTED   2  /* Experimental feature */
@@ -1713,292 +1722,318 @@ PNG_FIXED_EXPORT(209, void, png_set_filt
 #ifdef PNG_WRITE_SUPPORTED
 /* Set the library compression level.  Currently, valid values range from
  * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  * (0 - no compression, 9 - "maximal" compression).  Note that tests have
  * shown that zlib compression levels 3-6 usually perform as well as level 9
  * for PNG images, and do considerably fewer caclulations.  In the future,
  * these values may not correspond directly to the zlib compression levels.
  */
-PNG_EXPORT(69, void, png_set_compression_level,
-    (png_structp png_ptr, int level));
-
-PNG_EXPORT(70, void, png_set_compression_mem_level, (png_structp png_ptr,
+PNG_EXPORT(69, void, png_set_compression_level, (png_structrp png_ptr,
+    int level));
+
+PNG_EXPORT(70, void, png_set_compression_mem_level, (png_structrp png_ptr,
     int mem_level));
 
-PNG_EXPORT(71, void, png_set_compression_strategy, (png_structp png_ptr,
+PNG_EXPORT(71, void, png_set_compression_strategy, (png_structrp png_ptr,
     int strategy));
 
 /* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
  * smaller value of window_bits if it can do so safely.
  */
-PNG_EXPORT(72, void, png_set_compression_window_bits, (png_structp png_ptr,
+PNG_EXPORT(72, void, png_set_compression_window_bits, (png_structrp png_ptr,
     int window_bits));
 
-PNG_EXPORT(73, void, png_set_compression_method, (png_structp png_ptr,
+PNG_EXPORT(73, void, png_set_compression_method, (png_structrp png_ptr,
     int method));
 #endif
 
 #ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
 /* Also set zlib parameters for compressing non-IDAT chunks */
-PNG_EXPORT(222, void, png_set_text_compression_level,
-    (png_structp png_ptr, int level));
-
-PNG_EXPORT(223, void, png_set_text_compression_mem_level, (png_structp png_ptr,
+PNG_EXPORT(222, void, png_set_text_compression_level, (png_structrp png_ptr,
+    int level));
+
+PNG_EXPORT(223, void, png_set_text_compression_mem_level, (png_structrp png_ptr,
     int mem_level));
 
-PNG_EXPORT(224, void, png_set_text_compression_strategy, (png_structp png_ptr,
+PNG_EXPORT(224, void, png_set_text_compression_strategy, (png_structrp png_ptr,
     int strategy));
 
 /* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
  * smaller value of window_bits if it can do so safely.
  */
-PNG_EXPORT(225, void, png_set_text_compression_window_bits, (png_structp
-    png_ptr, int window_bits));
-
-PNG_EXPORT(226, void, png_set_text_compression_method, (png_structp png_ptr,
+PNG_EXPORT(225, void, png_set_text_compression_window_bits,
+    (png_structrp png_ptr, int window_bits));
+
+PNG_EXPORT(226, void, png_set_text_compression_method, (png_structrp png_ptr,
     int method));
 #endif /* PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED */
 
 /* These next functions are called for input/output, memory, and error
  * handling.  They are in the file pngrio.c, pngwio.c, and pngerror.c,
  * and call standard C I/O routines such as fread(), fwrite(), and
  * fprintf().  These functions can be made to use other I/O routines
  * at run time for those applications that need to handle I/O in a
  * different manner by calling png_set_???_fn().  See libpng-manual.txt for
  * more information.
  */
 
 #ifdef PNG_STDIO_SUPPORTED
 /* Initialize the input/output for the PNG file to the default functions. */
-PNG_EXPORT(74, void, png_init_io, (png_structp png_ptr, png_FILE_p fp));
+PNG_EXPORT(74, void, png_init_io, (png_structrp png_ptr, png_FILE_p fp));
 #endif
 
 /* Replace the (error and abort), and warning functions with user
  * supplied functions.  If no messages are to be printed you must still
  * write and use replacement functions. The replacement error_fn should
  * still do a longjmp to the last setjmp location if you are using this
  * method of error handling.  If error_fn or warning_fn is NULL, the
  * default function will be used.
  */
 
-PNG_EXPORT(75, void, png_set_error_fn,
-    (png_structp png_ptr, png_voidp error_ptr,
-    png_error_ptr error_fn, png_error_ptr warning_fn));
+PNG_EXPORT(75, void, png_set_error_fn, (png_structrp png_ptr,
+    png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
 
 /* Return the user pointer associated with the error functions */
-PNG_EXPORT(76, png_voidp, png_get_error_ptr, (png_const_structp png_ptr));
+PNG_EXPORT(76, png_voidp, png_get_error_ptr, (png_const_structrp png_ptr));
 
 /* Replace the default data output functions with a user supplied one(s).
  * If buffered output is not used, then output_flush_fn can be set to NULL.
  * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  * output_flush_fn will be ignored (and thus can be NULL).
  * It is probably a mistake to use NULL for output_flush_fn if
  * write_data_fn is not also NULL unless you have built libpng with
  * PNG_WRITE_FLUSH_SUPPORTED undefined, because in this case libpng's
  * default flush function, which uses the standard *FILE structure, will
  * be used.
  */
-PNG_EXPORT(77, void, png_set_write_fn, (png_structp png_ptr, png_voidp io_ptr,
+PNG_EXPORT(77, void, png_set_write_fn, (png_structrp png_ptr, png_voidp io_ptr,
     png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
 
 /* Replace the default data input function with a user supplied one. */
-PNG_EXPORT(78, void, png_set_read_fn, (png_structp png_ptr, png_voidp io_ptr,
+PNG_EXPORT(78, void, png_set_read_fn, (png_structrp png_ptr, png_voidp io_ptr,
     png_rw_ptr read_data_fn));
 
 /* Return the user pointer associated with the I/O functions */
-PNG_EXPORT(79, png_voidp, png_get_io_ptr, (png_structp png_ptr));
-
-PNG_EXPORT(80, void, png_set_read_status_fn, (png_structp png_ptr,
+PNG_EXPORT(79, png_voidp, png_get_io_ptr, (png_const_structrp png_ptr));
+
+PNG_EXPORT(80, void, png_set_read_status_fn, (png_structrp png_ptr,
     png_read_status_ptr read_row_fn));
 
-PNG_EXPORT(81, void, png_set_write_status_fn, (png_structp png_ptr,
+PNG_EXPORT(81, void, png_set_write_status_fn, (png_structrp png_ptr,
     png_write_status_ptr write_row_fn));
 
 #ifdef PNG_USER_MEM_SUPPORTED
 /* Replace the default memory allocation functions with user supplied one(s). */
-PNG_EXPORT(82, void, png_set_mem_fn, (png_structp png_ptr, png_voidp mem_ptr,
+PNG_EXPORT(82, void, png_set_mem_fn, (png_structrp png_ptr, png_voidp mem_ptr,
     png_malloc_ptr malloc_fn, png_free_ptr free_fn));
 /* Return the user pointer associated with the memory functions */
-PNG_EXPORT(83, png_voidp, png_get_mem_ptr, (png_const_structp png_ptr));
+PNG_EXPORT(83, png_voidp, png_get_mem_ptr, (png_const_structrp png_ptr));
 #endif
 
 #ifdef PNG_READ_USER_TRANSFORM_SUPPORTED
-PNG_EXPORT(84, void, png_set_read_user_transform_fn, (png_structp png_ptr,
+PNG_EXPORT(84, void, png_set_read_user_transform_fn, (png_structrp png_ptr,
     png_user_transform_ptr read_user_transform_fn));
 #endif
 
 #ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
-PNG_EXPORT(85, void, png_set_write_user_transform_fn, (png_structp png_ptr,
+PNG_EXPORT(85, void, png_set_write_user_transform_fn, (png_structrp png_ptr,
     png_user_transform_ptr write_user_transform_fn));
 #endif
 
 #ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED
-PNG_EXPORT(86, void, png_set_user_transform_info, (png_structp png_ptr,
+PNG_EXPORT(86, void, png_set_user_transform_info, (png_structrp png_ptr,
     png_voidp user_transform_ptr, int user_transform_depth,
     int user_transform_channels));
 /* Return the user pointer associated with the user transform functions */
 PNG_EXPORT(87, png_voidp, png_get_user_transform_ptr,
-    (png_const_structp png_ptr));
+    (png_const_structrp png_ptr));
 #endif
 
 #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED
 /* Return information about the row currently being processed.  Note that these
  * APIs do not fail but will return unexpected results if called outside a user
  * transform callback.  Also note that when transforming an interlaced image the
  * row number is the row number within the sub-image of the interlace pass, so
  * the value will increase to the height of the sub-image (not the full image)
  * then reset to 0 for the next pass.
  *
  * Use PNG_ROW_FROM_PASS_ROW(row, pass) and PNG_COL_FROM_PASS_COL(col, pass) to
  * find the output pixel (x,y) given an interlaced sub-image pixel
  * (row,col,pass).  (See below for these macros.)
  */
-PNG_EXPORT(217, png_uint_32, png_get_current_row_number, (png_const_structp));
-PNG_EXPORT(218, png_byte, png_get_current_pass_number, (png_const_structp));
+PNG_EXPORT(217, png_uint_32, png_get_current_row_number, (png_const_structrp));
+PNG_EXPORT(218, png_byte, png_get_current_pass_number, (png_const_structrp));
+#endif
+
+#ifdef PNG_READ_USER_CHUNKS_SUPPORTED
+/* This callback is called only for *unknown* chunks.  If
+ * PNG_HANDLE_AS_UNKNOWN_SUPPORTED is set then it is possible to set known
+ * chunks to be treated as unknown, however in this case the callback must do
+ * any processing required by the chunk (e.g. by calling the appropriate
+ * png_set_ APIs.)
+ *
+ * There is no write support - on write, by default, all the chunks in the
+ * 'unknown' list are written in the specified position.
+ *
+ * The integer return from the callback function is interpreted thus:
+ *
+ * negative: An error occured, png_chunk_error will be called.
+ *     zero: The chunk was not handled, the chunk will be saved. A critical
+ *           chunk will cause an error at this point unless it is to be saved.
+ * positive: The chunk was handled, libpng will ignore/discard it.
+ *
+ * See "INTERACTION WTIH USER CHUNK CALLBACKS" below for important notes about
+ * how this behavior will change in libpng 1.7
+ */
+PNG_EXPORT(88, void, png_set_read_user_chunk_fn, (png_structrp png_ptr,
+    png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
 #endif
 
 #ifdef PNG_USER_CHUNKS_SUPPORTED
-PNG_EXPORT(88, void, png_set_read_user_chunk_fn, (png_structp png_ptr,
-    png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
-PNG_EXPORT(89, png_voidp, png_get_user_chunk_ptr, (png_const_structp png_ptr));
+PNG_EXPORT(89, png_voidp, png_get_user_chunk_ptr, (png_const_structrp png_ptr));
 #endif
 
 #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
 /* Sets the function callbacks for the push reader, and a pointer to a
  * user-defined structure available to the callback functions.
  */
-PNG_EXPORT(90, void, png_set_progressive_read_fn, (png_structp png_ptr,
+PNG_EXPORT(90, void, png_set_progressive_read_fn, (png_structrp png_ptr,
     png_voidp progressive_ptr, png_progressive_info_ptr info_fn,
     png_progressive_row_ptr row_fn, png_progressive_end_ptr end_fn));
 
 /* Returns the user pointer associated with the push read functions */
-PNG_EXPORT(91, png_voidp, png_get_progressive_ptr, (png_const_structp png_ptr));
+PNG_EXPORT(91, png_voidp, png_get_progressive_ptr,
+    (png_const_structrp png_ptr));
 
 /* Function to be called when data becomes available */
-PNG_EXPORT(92, void, png_process_data,
-    (png_structp png_ptr, png_infop info_ptr,
-    png_bytep buffer, png_size_t buffer_size));
+PNG_EXPORT(92, void, png_process_data, (png_structrp png_ptr,
+    png_inforp info_ptr, png_bytep buffer, png_size_t buffer_size));
 
 /* A function which may be called *only* within png_process_data to stop the
  * processing of any more data.  The function returns the number of bytes
  * remaining, excluding any that libpng has cached internally.  A subsequent
  * call to png_process_data must supply these bytes again.  If the argument
  * 'save' is set to true the routine will first save all the pending data and
  * will always return 0.
  */
-PNG_EXPORT(219, png_size_t, png_process_data_pause, (png_structp, int save));
+PNG_EXPORT(219, png_size_t, png_process_data_pause, (png_structrp, int save));
 
 /* A function which may be called *only* outside (after) a call to
  * png_process_data.  It returns the number of bytes of data to skip in the
  * input.  Normally it will return 0, but if it returns a non-zero value the
  * application must skip than number of bytes of input data and pass the
  * following data to the next call to png_process_data.
  */
-PNG_EXPORT(220, png_uint_32, png_process_data_skip, (png_structp));
+PNG_EXPORT(220, png_uint_32, png_process_data_skip, (png_structrp));
 
 #ifdef PNG_READ_INTERLACING_SUPPORTED
 /* Function that combines rows.  'new_row' is a flag that should come from
  * the callback and be non-NULL if anything needs to be done; the library
  * stores its own version of the new data internally and ignores the passed
  * in value.
  */
-PNG_EXPORT(93, void, png_progressive_combine_row, (png_structp png_ptr,
+PNG_EXPORT(93, void, png_progressive_combine_row, (png_const_structrp png_ptr,
     png_bytep old_row, png_const_bytep new_row));
 #endif /* PNG_READ_INTERLACING_SUPPORTED */
 #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
 
-PNG_EXPORTA(94, png_voidp, png_malloc,
-    (png_structp png_ptr, png_alloc_size_t size),
-    PNG_ALLOCATED);
+PNG_EXPORTA(94, png_voidp, png_malloc, (png_const_structrp png_ptr,
+    png_alloc_size_t size), PNG_ALLOCATED);
 /* Added at libpng version 1.4.0 */
-PNG_EXPORTA(95, png_voidp, png_calloc,
-    (png_structp png_ptr, png_alloc_size_t size),
-    PNG_ALLOCATED);
+PNG_EXPORTA(95, png_voidp, png_calloc, (png_const_structrp png_ptr,
+    png_alloc_size_t size), PNG_ALLOCATED);
 
 /* Added at libpng version 1.2.4 */
-PNG_EXPORTA(96, png_voidp, png_malloc_warn, (png_structp png_ptr,
+PNG_EXPORTA(96, png_voidp, png_malloc_warn, (png_const_structrp png_ptr,
     png_alloc_size_t size), PNG_ALLOCATED);
 
 /* Frees a pointer allocated by png_malloc() */
-PNG_EXPORT(97, void, png_free, (png_structp png_ptr, png_voidp ptr));
+PNG_EXPORT(97, void, png_free, (png_const_structrp png_ptr, png_voidp ptr));
 
 /* Free data that was allocated internally */
-PNG_EXPORT(98, void, png_free_data,
-    (png_structp png_ptr, png_infop info_ptr, png_uint_32 free_me, int num));
+PNG_EXPORT(98, void, png_free_data, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_uint_32 free_me, int num));
 
 /* Reassign responsibility for freeing existing data, whether allocated
- * by libpng or by the application */
-PNG_EXPORT(99, void, png_data_freer,
-    (png_structp png_ptr, png_infop info_ptr, int freer, png_uint_32 mask));
+ * by libpng or by the application; this works on the png_info structure passed
+ * in, it does not change the state for other png_info structures.
+ *
+ * It is unlikely that this function works correctly as of 1.6.0 and using it
+ * may result either in memory leaks or double free of allocated data.
+ */
+PNG_EXPORTA(99, void, png_data_freer, (png_const_structrp png_ptr,
+    png_inforp info_ptr, int freer, png_uint_32 mask), PNG_DEPRECATED);
 
 /* Assignments for png_data_freer */
 #define PNG_DESTROY_WILL_FREE_DATA 1
 #define PNG_SET_WILL_FREE_DATA 1
 #define PNG_USER_WILL_FREE_DATA 2
 /* Flags for png_ptr->free_me and info_ptr->free_me */
 #define PNG_FREE_HIST 0x0008
 #define PNG_FREE_ICCP 0x0010
 #define PNG_FREE_SPLT 0x0020
 #define PNG_FREE_ROWS 0x0040
 #define PNG_FREE_PCAL 0x0080
 #define PNG_FREE_SCAL 0x0100
-#define PNG_FREE_UNKN 0x0200
-#define PNG_FREE_LIST 0x0400
+#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
+#  define PNG_FREE_UNKN 0x0200
+#endif
+/*      PNG_FREE_LIST 0x0400    removed in 1.6.0 because it is ignored */
 #define PNG_FREE_PLTE 0x1000
 #define PNG_FREE_TRNS 0x2000
 #define PNG_FREE_TEXT 0x4000
 #define PNG_FREE_ALL  0x7fff
 #define PNG_FREE_MUL  0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
 
 #ifdef PNG_USER_MEM_SUPPORTED
-PNG_EXPORTA(100, png_voidp, png_malloc_default, (png_structp png_ptr,
-    png_alloc_size_t size), PNG_ALLOCATED);
-PNG_EXPORT(101, void, png_free_default, (png_structp png_ptr, png_voidp ptr));
+PNG_EXPORTA(100, png_voidp, png_malloc_default, (png_const_structrp png_ptr,
+    png_alloc_size_t size), PNG_ALLOCATED PNG_DEPRECATED);
+PNG_EXPORTA(101, void, png_free_default, (png_const_structrp png_ptr,
+    png_voidp ptr), PNG_DEPRECATED);
 #endif
 
 #ifdef PNG_ERROR_TEXT_SUPPORTED
 /* Fatal error in PNG image of libpng - can't continue */
-PNG_EXPORTA(102, void, png_error,
-    (png_structp png_ptr, png_const_charp error_message),
-    PNG_NORETURN);
+PNG_EXPORTA(102, void, png_error, (png_const_structrp png_ptr,
+    png_const_charp error_message), PNG_NORETURN);
 
 /* The same, but the chunk name is prepended to the error string. */
-PNG_EXPORTA(103, void, png_chunk_error, (png_structp png_ptr,
+PNG_EXPORTA(103, void, png_chunk_error, (png_const_structrp png_ptr,
     png_const_charp error_message), PNG_NORETURN);
 
 #else
 /* Fatal error in PNG image of libpng - can't continue */
-PNG_EXPORTA(104, void, png_err, (png_structp png_ptr), PNG_NORETURN);
+PNG_EXPORTA(104, void, png_err, (png_const_structrp png_ptr), PNG_NORETURN);
 #endif
 
 #ifdef PNG_WARNINGS_SUPPORTED
 /* Non-fatal error in libpng.  Can continue, but may have a problem. */
-PNG_EXPORT(105, void, png_warning, (png_structp png_ptr,
+PNG_EXPORT(105, void, png_warning, (png_const_structrp png_ptr,
     png_const_charp warning_message));
 
 /* Non-fatal error in libpng, chunk name is prepended to message. */
-PNG_EXPORT(106, void, png_chunk_warning, (png_structp png_ptr,
+PNG_EXPORT(106, void, png_chunk_warning, (png_const_structrp png_ptr,
     png_const_charp warning_message));
 #endif
 
 #ifdef PNG_BENIGN_ERRORS_SUPPORTED
 /* Benign error in libpng.  Can continue, but may have a problem.
  * User can choose whether to handle as a fatal error or as a warning. */
-#  undef png_benign_error
-PNG_EXPORT(107, void, png_benign_error, (png_structp png_ptr,
+PNG_EXPORT(107, void, png_benign_error, (png_const_structrp png_ptr,
     png_const_charp warning_message));
 
-/* Same, chunk name is prepended to message. */
-#  undef png_chunk_benign_error
-PNG_EXPORT(108, void, png_chunk_benign_error, (png_structp png_ptr,
+#ifdef PNG_READ_SUPPORTED
+/* Same, chunk name is prepended to message (only during read) */
+PNG_EXPORT(108, void, png_chunk_benign_error, (png_const_structrp png_ptr,
     png_const_charp warning_message));
+#endif
 
 PNG_EXPORT(109, void, png_set_benign_errors,
-    (png_structp png_ptr, int allowed));
+    (png_structrp png_ptr, int allowed));
 #else
 #  ifdef PNG_ALLOW_BENIGN_ERRORS
 #    define png_benign_error png_warning
 #    define png_chunk_benign_error png_chunk_warning
 #  else
 #    define png_benign_error png_error
 #    define png_chunk_benign_error png_chunk_error
 #  endif
@@ -2012,502 +2047,583 @@ PNG_EXPORT(109, void, png_set_benign_err
  * in info_ptr, or return zero and do not change any of the parameters if the
  * data was not available.
  *
  * These functions should be used instead of directly accessing png_info
  * to avoid problems with future changes in the size and internal layout of
  * png_info_struct.
  */
 /* Returns "flag" if chunk data is valid in info_ptr. */
-PNG_EXPORT(110, png_uint_32, png_get_valid,
-    (png_const_structp png_ptr, png_const_infop info_ptr,
-    png_uint_32 flag));
+PNG_EXPORT(110, png_uint_32, png_get_valid, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr, png_uint_32 flag));
 
 /* Returns number of bytes needed to hold a transformed row. */
-PNG_EXPORT(111, png_size_t, png_get_rowbytes, (png_const_structp png_ptr,
-    png_const_infop info_ptr));
+PNG_EXPORT(111, png_size_t, png_get_rowbytes, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr));
 
 #ifdef PNG_INFO_IMAGE_SUPPORTED
 /* Returns row_pointers, which is an array of pointers to scanlines that was
  * returned from png_read_png().
  */
-PNG_EXPORT(112, png_bytepp, png_get_rows,
-    (png_const_structp png_ptr, png_const_infop info_ptr));
+PNG_EXPORT(112, png_bytepp, png_get_rows, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr));
+
 /* Set row_pointers, which is an array of pointers to scanlines for use
  * by png_write_png().
  */
-PNG_EXPORT(113, void, png_set_rows, (png_structp png_ptr,
-    png_infop info_ptr, png_bytepp row_pointers));
+PNG_EXPORT(113, void, png_set_rows, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_bytepp row_pointers));
 #endif
 
 /* Returns number of color channels in image. */
-PNG_EXPORT(114, png_byte, png_get_channels,
-    (png_const_structp png_ptr, png_const_infop info_ptr));
+PNG_EXPORT(114, png_byte, png_get_channels, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr));
 
 #ifdef PNG_EASY_ACCESS_SUPPORTED
 /* Returns image width in pixels. */
-PNG_EXPORT(115, png_uint_32, png_get_image_width, (png_const_structp png_ptr,
-    png_const_infop info_ptr));
+PNG_EXPORT(115, png_uint_32, png_get_image_width, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr));
 
 /* Returns image height in pixels. */
-PNG_EXPORT(116, png_uint_32, png_get_image_height, (png_const_structp png_ptr,
-    png_const_infop info_ptr));
+PNG_EXPORT(116, png_uint_32, png_get_image_height, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr));
 
 /* Returns image bit_depth. */
-PNG_EXPORT(117, png_byte, png_get_bit_depth,
-    (png_const_structp png_ptr, png_const_infop info_ptr));
+PNG_EXPORT(117, png_byte, png_get_bit_depth, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr));
 
 /* Returns image color_type. */
-PNG_EXPORT(118, png_byte, png_get_color_type, (png_const_structp png_ptr,
-    png_const_infop info_ptr));
+PNG_EXPORT(118, png_byte, png_get_color_type, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr));
 
 /* Returns image filter_type. */
-PNG_EXPORT(119, png_byte, png_get_filter_type, (png_const_structp png_ptr,
-    png_const_infop info_ptr));
+PNG_EXPORT(119, png_byte, png_get_filter_type, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr));
 
 /* Returns image interlace_type. */
-PNG_EXPORT(120, png_byte, png_get_interlace_type, (png_const_structp png_ptr,
-    png_const_infop info_ptr));
+PNG_EXPORT(120, png_byte, png_get_interlace_type, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr));
 
 /* Returns image compression_type. */
-PNG_EXPORT(121, png_byte, png_get_compression_type, (png_const_structp png_ptr,
-    png_const_infop info_ptr));
+PNG_EXPORT(121, png_byte, png_get_compression_type, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr));
 
 /* Returns image resolution in pixels per meter, from pHYs chunk data. */
 PNG_EXPORT(122, png_uint_32, png_get_pixels_per_meter,
-    (png_const_structp png_ptr, png_const_infop info_ptr));
+    (png_const_structrp png_ptr, png_const_inforp info_ptr));
 PNG_EXPORT(123, png_uint_32, png_get_x_pixels_per_meter,
-    (png_const_structp png_ptr, png_const_infop info_ptr));
+    (png_const_structrp png_ptr, png_const_inforp info_ptr));
 PNG_EXPORT(124, png_uint_32, png_get_y_pixels_per_meter,
-    (png_const_structp png_ptr, png_const_infop info_ptr));
+    (png_const_structrp png_ptr, png_const_inforp info_ptr));
 
 /* Returns pixel aspect ratio, computed from pHYs chunk data.  */
 PNG_FP_EXPORT(125, float, png_get_pixel_aspect_ratio,
-    (png_const_structp png_ptr, png_const_infop info_ptr))
+    (png_const_structrp png_ptr, png_const_inforp info_ptr))
 PNG_FIXED_EXPORT(210, png_fixed_point, png_get_pixel_aspect_ratio_fixed,
-    (png_const_structp png_ptr, png_const_infop info_ptr))
+    (png_const_structrp png_ptr, png_const_inforp info_ptr))
 
 /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
 PNG_EXPORT(126, png_int_32, png_get_x_offset_pixels,
-    (png_const_structp png_ptr, png_const_infop info_ptr));
+    (png_const_structrp png_ptr, png_const_inforp info_ptr));
 PNG_EXPORT(127, png_int_32, png_get_y_offset_pixels,
-    (png_const_structp png_ptr, png_const_infop info_ptr));
+    (png_const_structrp png_ptr, png_const_inforp info_ptr));
 PNG_EXPORT(128, png_int_32, png_get_x_offset_microns,
-    (png_const_structp png_ptr, png_const_infop info_ptr));
+    (png_const_structrp png_ptr, png_const_inforp info_ptr));
 PNG_EXPORT(129, png_int_32, png_get_y_offset_microns,
-    (png_const_structp png_ptr, png_const_infop info_ptr));
+    (png_const_structrp png_ptr, png_const_inforp info_ptr));
 
 #endif /* PNG_EASY_ACCESS_SUPPORTED */
 
+#ifdef PNG_READ_SUPPORTED
 /* Returns pointer to signature string read from PNG header */
-PNG_EXPORT(130, png_const_bytep, png_get_signature,
-    (png_const_structp png_ptr, png_infop info_ptr));
+PNG_EXPORT(130, png_const_bytep, png_get_signature, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr));
+#endif
 
 #ifdef PNG_bKGD_SUPPORTED
-PNG_EXPORT(131, png_uint_32, png_get_bKGD,
-    (png_const_structp png_ptr, png_infop info_ptr,
-    png_color_16p *background));
+PNG_EXPORT(131, png_uint_32, png_get_bKGD, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_color_16p *background));
 #endif
 
 #ifdef PNG_bKGD_SUPPORTED
-PNG_EXPORT(132, void, png_set_bKGD, (png_structp png_ptr, png_infop info_ptr,
-    png_const_color_16p background));
+PNG_EXPORT(132, void, png_set_bKGD, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_const_color_16p background));
 #endif
 
 #ifdef PNG_cHRM_SUPPORTED
-PNG_FP_EXPORT(133, png_uint_32, png_get_cHRM, (png_const_structp png_ptr,
-   png_const_infop info_ptr, double *white_x, double *white_y, double *red_x,
+PNG_FP_EXPORT(133, png_uint_32, png_get_cHRM, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr, double *white_x, double *white_y, double *red_x,
     double *red_y, double *green_x, double *green_y, double *blue_x,
     double *blue_y))
-PNG_FP_EXPORT(230, png_uint_32, png_get_cHRM_XYZ, (png_structp png_ptr,
-    png_const_infop info_ptr, double *red_X, double *red_Y, double *red_Z,
+PNG_FP_EXPORT(230, png_uint_32, png_get_cHRM_XYZ, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr, double *red_X, double *red_Y, double *red_Z,
     double *green_X, double *green_Y, double *green_Z, double *blue_X,
     double *blue_Y, double *blue_Z))
-#ifdef PNG_FIXED_POINT_SUPPORTED /* Otherwise not implemented */
 PNG_FIXED_EXPORT(134, png_uint_32, png_get_cHRM_fixed,
-    (png_const_structp png_ptr,
-    png_const_infop info_ptr, png_fixed_point *int_white_x,
-    png_fixed_point *int_white_y, png_fixed_point *int_red_x,
-    png_fixed_point *int_red_y, png_fixed_point *int_green_x,
-    png_fixed_point *int_green_y, png_fixed_point *int_blue_x,
-    png_fixed_point *int_blue_y))
-#endif
+    (png_const_structrp png_ptr, png_const_inforp info_ptr,
+    png_fixed_point *int_white_x, png_fixed_point *int_white_y,
+    png_fixed_point *int_red_x, png_fixed_point *int_red_y,
+    png_fixed_point *int_green_x, png_fixed_point *int_green_y,
+    png_fixed_point *int_blue_x, png_fixed_point *int_blue_y))
 PNG_FIXED_EXPORT(231, png_uint_32, png_get_cHRM_XYZ_fixed,
-    (png_structp png_ptr, png_const_infop info_ptr,
+    (png_const_structrp png_ptr, png_const_inforp info_ptr,
     png_fixed_point *int_red_X, png_fixed_point *int_red_Y,
     png_fixed_point *int_red_Z, png_fixed_point *int_green_X,
     png_fixed_point *int_green_Y, png_fixed_point *int_green_Z,
     png_fixed_point *int_blue_X, png_fixed_point *int_blue_Y,
     png_fixed_point *int_blue_Z))
 #endif
 
 #ifdef PNG_cHRM_SUPPORTED
-PNG_FP_EXPORT(135, void, png_set_cHRM,
-    (png_structp png_ptr, png_infop info_ptr,
+PNG_FP_EXPORT(135, void, png_set_cHRM, (png_const_structrp png_ptr,
+    png_inforp info_ptr,
     double white_x, double white_y, double red_x, double red_y, double green_x,
     double green_y, double blue_x, double blue_y))
-PNG_FP_EXPORT(232, void, png_set_cHRM_XYZ, (png_structp png_ptr,
-    png_infop info_ptr, double red_X, double red_Y, double red_Z,
+PNG_FP_EXPORT(232, void, png_set_cHRM_XYZ, (png_const_structrp png_ptr,
+    png_inforp info_ptr, double red_X, double red_Y, double red_Z,
     double green_X, double green_Y, double green_Z, double blue_X,
     double blue_Y, double blue_Z))
-PNG_FIXED_EXPORT(136, void, png_set_cHRM_fixed, (png_structp png_ptr,
-    png_infop info_ptr, png_fixed_point int_white_x,
+PNG_FIXED_EXPORT(136, void, png_set_cHRM_fixed, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_fixed_point int_white_x,
     png_fixed_point int_white_y, png_fixed_point int_red_x,
     png_fixed_point int_red_y, png_fixed_point int_green_x,
     png_fixed_point int_green_y, png_fixed_point int_blue_x,
     png_fixed_point int_blue_y))
-PNG_FIXED_EXPORT(233, void, png_set_cHRM_XYZ_fixed, (png_structp png_ptr,
-    png_infop info_ptr, png_fixed_point int_red_X, png_fixed_point int_red_Y,
+PNG_FIXED_EXPORT(233, void, png_set_cHRM_XYZ_fixed, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_fixed_point int_red_X, png_fixed_point int_red_Y,
     png_fixed_point int_red_Z, png_fixed_point int_green_X,
     png_fixed_point int_green_Y, png_fixed_point int_green_Z,
     png_fixed_point int_blue_X, png_fixed_point int_blue_Y,
     png_fixed_point int_blue_Z))
 #endif
 
 #ifdef PNG_gAMA_SUPPORTED
-PNG_FP_EXPORT(137, png_uint_32, png_get_gAMA,
-    (png_const_structp png_ptr, png_const_infop info_ptr,
-    double *file_gamma))
+PNG_FP_EXPORT(137, png_uint_32, png_get_gAMA, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr, double *file_gamma))
 PNG_FIXED_EXPORT(138, png_uint_32, png_get_gAMA_fixed,
-    (png_const_structp png_ptr, png_const_infop info_ptr,
+    (png_const_structrp png_ptr, png_const_inforp info_ptr,
     png_fixed_point *int_file_gamma))
 #endif
 
 #ifdef PNG_gAMA_SUPPORTED
-PNG_FP_EXPORT(139, void, png_set_gAMA, (png_structp png_ptr,
-    png_infop info_ptr, double file_gamma))
-PNG_FIXED_EXPORT(140, void, png_set_gAMA_fixed, (png_structp png_ptr,
-    png_infop info_ptr, png_fixed_point int_file_gamma))
+PNG_FP_EXPORT(139, void, png_set_gAMA, (png_const_structrp png_ptr,
+    png_inforp info_ptr, double file_gamma))
+PNG_FIXED_EXPORT(140, void, png_set_gAMA_fixed, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_fixed_point int_file_gamma))
 #endif
 
 #ifdef PNG_hIST_SUPPORTED
-PNG_EXPORT(141, png_uint_32, png_get_hIST,
-    (png_const_structp png_ptr, png_const_infop info_ptr,
-    png_uint_16p *hist));
+PNG_EXPORT(141, png_uint_32, png_get_hIST, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_uint_16p *hist));
 #endif
 
 #ifdef PNG_hIST_SUPPORTED
-PNG_EXPORT(142, void, png_set_hIST, (png_structp png_ptr,
-    png_infop info_ptr, png_const_uint_16p hist));
+PNG_EXPORT(142, void, png_set_hIST, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_const_uint_16p hist));
 #endif
 
-PNG_EXPORT(143, png_uint_32, png_get_IHDR,
-    (png_structp png_ptr, png_infop info_ptr,
-    png_uint_32 *width, png_uint_32 *height, int *bit_depth, int *color_type,
-    int *interlace_method, int *compression_method, int *filter_method));
-
-PNG_EXPORT(144, void, png_set_IHDR,
-    (png_structp png_ptr, png_infop info_ptr,
-    png_uint_32 width, png_uint_32 height, int bit_depth, int color_type,
-    int interlace_method, int compression_method, int filter_method));
+PNG_EXPORT(143, png_uint_32, png_get_IHDR, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr, png_uint_32 *width, png_uint_32 *height,
+    int *bit_depth, int *color_type, int *interlace_method,
+    int *compression_method, int *filter_method));
+
+PNG_EXPORT(144, void, png_set_IHDR, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
+    int color_type, int interlace_method, int compression_method,
+    int filter_method));
 
 #ifdef PNG_oFFs_SUPPORTED
-PNG_EXPORT(145, png_uint_32, png_get_oFFs,
-    (png_const_structp png_ptr, png_const_infop info_ptr,
-    png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type));
+PNG_EXPORT(145, png_uint_32, png_get_oFFs, (png_const_structrp png_ptr,
+   png_const_inforp info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
+   int *unit_type));
 #endif
 
 #ifdef PNG_oFFs_SUPPORTED
-PNG_EXPORT(146, void, png_set_oFFs,
-    (png_structp png_ptr, png_infop info_ptr,
-    png_int_32 offset_x, png_int_32 offset_y, int unit_type));
+PNG_EXPORT(146, void, png_set_oFFs, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_int_32 offset_x, png_int_32 offset_y,
+    int unit_type));
 #endif
 
 #ifdef PNG_pCAL_SUPPORTED
-PNG_EXPORT(147, png_uint_32, png_get_pCAL,
-    (png_const_structp png_ptr, png_const_infop info_ptr,
-    png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type,
-    int *nparams,
-    png_charp *units, png_charpp *params));
+PNG_EXPORT(147, png_uint_32, png_get_pCAL, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_charp *purpose, png_int_32 *X0,
+    png_int_32 *X1, int *type, int *nparams, png_charp *units,
+    png_charpp *params));
 #endif
 
 #ifdef PNG_pCAL_SUPPORTED
-PNG_EXPORT(148, void, png_set_pCAL, (png_structp png_ptr,
-    png_infop info_ptr,
-    png_const_charp purpose, png_int_32 X0, png_int_32 X1, int type,
-    int nparams, png_const_charp units, png_charpp params));
-#endif
-
-#ifdef PNG_pHYs_SUPPORTED
-PNG_EXPORT(149, png_uint_32, png_get_pHYs,
-    (png_const_structp png_ptr, png_const_infop info_ptr,
-    png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
+PNG_EXPORT(148, void, png_set_pCAL, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_const_charp purpose, png_int_32 X0, png_int_32 X1,
+    int type, int nparams, png_const_charp units, png_charpp params));
 #endif
 
 #ifdef PNG_pHYs_SUPPORTED
-PNG_EXPORT(150, void, png_set_pHYs,
-    (png_structp png_ptr, png_infop info_ptr,
-    png_uint_32 res_x, png_uint_32 res_y, int unit_type));
+PNG_EXPORT(149, png_uint_32, png_get_pHYs, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr, png_uint_32 *res_x, png_uint_32 *res_y,
+    int *unit_type));
 #endif
 
-PNG_EXPORT(151, png_uint_32, png_get_PLTE,
-    (png_const_structp png_ptr, png_const_infop info_ptr,
-    png_colorp *palette, int *num_palette));
-
-PNG_EXPORT(152, void, png_set_PLTE,
-    (png_structp png_ptr, png_infop info_ptr,
-    png_const_colorp palette, int num_palette));
+#ifdef PNG_pHYs_SUPPORTED
+PNG_EXPORT(150, void, png_set_pHYs, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
+#endif
+
+PNG_EXPORT(151, png_uint_32, png_get_PLTE, (png_const_structrp png_ptr,
+   png_inforp info_ptr, png_colorp *palette, int *num_palette));
+
+PNG_EXPORT(152, void, png_set_PLTE, (png_structrp png_ptr,
+    png_inforp info_ptr, png_const_colorp palette, int num_palette));
 
 #ifdef PNG_sBIT_SUPPORTED
-PNG_EXPORT(153, png_uint_32, png_get_sBIT,
-    (png_const_structp png_ptr, png_infop info_ptr,
-    png_color_8p *sig_bit));
+PNG_EXPORT(153, png_uint_32, png_get_sBIT, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_color_8p *sig_bit));
 #endif
 
 #ifdef PNG_sBIT_SUPPORTED
-PNG_EXPORT(154, void, png_set_sBIT,
-    (png_structp png_ptr, png_infop info_ptr, png_const_color_8p sig_bit));
-#endif
-
-#ifdef PNG_sRGB_SUPPORTED
-PNG_EXPORT(155, png_uint_32, png_get_sRGB, (png_const_structp png_ptr,
-    png_const_infop info_ptr, int *file_srgb_intent));
+PNG_EXPORT(154, void, png_set_sBIT, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_const_color_8p sig_bit));
 #endif
 
 #ifdef PNG_sRGB_SUPPORTED
-PNG_EXPORT(156, void, png_set_sRGB,
-    (png_structp png_ptr, png_infop info_ptr, int srgb_intent));
-PNG_EXPORT(157, void, png_set_sRGB_gAMA_and_cHRM, (png_structp png_ptr,
-    png_infop info_ptr, int srgb_intent));
+PNG_EXPORT(155, png_uint_32, png_get_sRGB, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr, int *file_srgb_intent));
 #endif
 
-#ifdef PNG_iCCP_SUPPORTED
-PNG_EXPORT(158, png_uint_32, png_get_iCCP,
-    (png_const_structp png_ptr, png_const_infop info_ptr,
-    png_charpp name, int *compression_type, png_bytepp profile,
-    png_uint_32 *proflen));
+#ifdef PNG_sRGB_SUPPORTED
+PNG_EXPORT(156, void, png_set_sRGB, (png_const_structrp png_ptr,
+    png_inforp info_ptr, int srgb_intent));
+PNG_EXPORT(157, void, png_set_sRGB_gAMA_and_cHRM, (png_const_structrp png_ptr,
+    png_inforp info_ptr, int srgb_intent));
 #endif
 
 #ifdef PNG_iCCP_SUPPORTED
-PNG_EXPORT(159, void, png_set_iCCP,
-    (png_structp png_ptr, png_infop info_ptr,
-    png_const_charp name, int compression_type, png_const_bytep profile,
-    png_uint_32 proflen));
+PNG_EXPORT(158, png_uint_32, png_get_iCCP, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_charpp name, int *compression_type,
+    png_bytepp profile, png_uint_32 *proflen));
+#endif
+
+#ifdef PNG_iCCP_SUPPORTED
+PNG_EXPORT(159, void, png_set_iCCP, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_const_charp name, int compression_type,
+    png_const_bytep profile, png_uint_32 proflen));
 #endif
 
 #ifdef PNG_sPLT_SUPPORTED
-PNG_EXPORT(160, png_uint_32, png_get_sPLT,
-    (png_const_structp png_ptr, png_const_infop info_ptr,
-    png_sPLT_tpp entries));
+PNG_EXPORT(160, int, png_get_sPLT, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_sPLT_tpp entries));
 #endif
 
 #ifdef PNG_sPLT_SUPPORTED
-PNG_EXPORT(161, void, png_set_sPLT,
-    (png_structp png_ptr, png_infop info_ptr,
-    png_const_sPLT_tp entries, int nentries));
+PNG_EXPORT(161, void, png_set_sPLT, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_const_sPLT_tp entries, int nentries));
 #endif
 
 #ifdef PNG_TEXT_SUPPORTED
 /* png_get_text also returns the number of text chunks in *num_text */
-PNG_EXPORT(162, png_uint_32, png_get_text,
-    (png_const_structp png_ptr, png_const_infop info_ptr,
-    png_textp *text_ptr, int *num_text));
+PNG_EXPORT(162, int, png_get_text, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_textp *text_ptr, int *num_text));
 #endif
 
 /* Note while png_set_text() will accept a structure whose text,
  * language, and  translated keywords are NULL pointers, the structure
  * returned by png_get_text will always contain regular
  * zero-terminated C strings.  They might be empty strings but
  * they will never be NULL pointers.
  */
 
 #ifdef PNG_TEXT_SUPPORTED
-PNG_EXPORT(163, void, png_set_text,
-    (png_structp png_ptr, png_infop info_ptr,
-    png_const_textp text_ptr, int num_text));
+PNG_EXPORT(163, void, png_set_text, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_const_textp text_ptr, int num_text));
 #endif
 
 #ifdef PNG_tIME_SUPPORTED
-PNG_EXPORT(164, png_uint_32, png_get_tIME,
-    (png_const_structp png_ptr, png_infop info_ptr, png_timep *mod_time));
+PNG_EXPORT(164, png_uint_32, png_get_tIME, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_timep *mod_time));
 #endif
 
 #ifdef PNG_tIME_SUPPORTED
-PNG_EXPORT(165, void, png_set_tIME,
-    (png_structp png_ptr, png_infop info_ptr, png_const_timep mod_time));
+PNG_EXPORT(165, void, png_set_tIME, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_const_timep mod_time));
 #endif
 
 #ifdef PNG_tRNS_SUPPORTED
-PNG_EXPORT(166, png_uint_32, png_get_tRNS,
-    (png_const_structp png_ptr, png_infop info_ptr,
-    png_bytep *trans_alpha, int *num_trans, png_color_16p *trans_color));
+PNG_EXPORT(166, png_uint_32, png_get_tRNS, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_bytep *trans_alpha, int *num_trans,
+    png_color_16p *trans_color));
 #endif
 
 #ifdef PNG_tRNS_SUPPORTED
-PNG_EXPORT(167, void, png_set_tRNS,
-    (png_structp png_ptr, png_infop info_ptr,
-    png_const_bytep trans_alpha, int num_trans,
+PNG_EXPORT(167, void, png_set_tRNS, (png_structrp png_ptr,
+    png_inforp info_ptr, png_const_bytep trans_alpha, int num_trans,
     png_const_color_16p trans_color));
 #endif
 
 #ifdef PNG_sCAL_SUPPORTED
-PNG_FP_EXPORT(168, png_uint_32, png_get_sCAL,
-    (png_const_structp png_ptr, png_const_infop info_ptr,
-    int *unit, double *width, double *height))
-#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
+PNG_FP_EXPORT(168, png_uint_32, png_get_sCAL, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr, int *unit, double *width, double *height))
+#if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || \
+   defined(PNG_FLOATING_POINT_SUPPORTED)
 /* NOTE: this API is currently implemented using floating point arithmetic,
  * consequently it can only be used on systems with floating point support.
  * In any case the range of values supported by png_fixed_point is small and it
  * is highly recommended that png_get_sCAL_s be used instead.
  */
 PNG_FIXED_EXPORT(214, png_uint_32, png_get_sCAL_fixed,
-    (png_structp png_ptr, png_const_infop info_ptr, int *unit,
-    png_fixed_point *width,
-    png_fixed_point *height))
+    (png_const_structrp png_ptr, png_const_inforp info_ptr, int *unit,
+    png_fixed_point *width, png_fixed_point *height))
 #endif
 PNG_EXPORT(169, png_uint_32, png_get_sCAL_s,
-    (png_const_structp png_ptr, png_const_infop info_ptr,
-    int *unit, png_charpp swidth, png_charpp sheight));
-
-PNG_FP_EXPORT(170, void, png_set_sCAL,
-    (png_structp png_ptr, png_infop info_ptr,
-    int unit, double width, double height))
-PNG_FIXED_EXPORT(213, void, png_set_sCAL_fixed, (png_structp png_ptr,
-   png_infop info_ptr, int unit, png_fixed_point width,
+    (png_const_structrp png_ptr, png_const_inforp info_ptr, int *unit,
+    png_charpp swidth, png_charpp sheight));
+
+PNG_FP_EXPORT(170, void, png_set_sCAL, (png_const_structrp png_ptr,
+    png_inforp info_ptr, int unit, double width, double height))
+PNG_FIXED_EXPORT(213, void, png_set_sCAL_fixed, (png_const_structrp png_ptr,
+   png_inforp info_ptr, int unit, png_fixed_point width,
    png_fixed_point height))
-PNG_EXPORT(171, void, png_set_sCAL_s,
-    (png_structp png_ptr, png_infop info_ptr,
-    int unit, png_const_charp swidth, png_const_charp sheight));
+PNG_EXPORT(171, void, png_set_sCAL_s, (png_const_structrp png_ptr,
+    png_inforp info_ptr, int unit,
+    png_const_charp swidth, png_const_charp sheight));
 #endif /* PNG_sCAL_SUPPORTED */
 
-#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
-/* Provide a list of chunks and how they are to be handled, if the built-in
-   handling or default unknown chunk handling is not desired.  Any chunks not
-   listed will be handled in the default manner.  The IHDR and IEND chunks
-   must not be listed.  Because this turns off the default handling for chunks
-   that would otherwise be recognized the behavior of libpng transformations may
-   well become incorrect!
-      keep = 0: PNG_HANDLE_CHUNK_AS_DEFAULT: follow default behavior
-           = 1: PNG_HANDLE_CHUNK_NEVER:      do not keep
-           = 2: PNG_HANDLE_CHUNK_IF_SAFE:    keep only if safe-to-copy
-           = 3: PNG_HANDLE_CHUNK_ALWAYS:     keep even if unsafe-to-copy
-*/
-PNG_EXPORT(172, void, png_set_keep_unknown_chunks,
-    (png_structp png_ptr, int keep,
-    png_const_bytep chunk_list, int num_chunks));
-
-/* The handling code is returned; the result is therefore true (non-zero) if
- * special handling is required, false for the default handling.
+#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
+/* Provide the default handling for all unknown chunks or, optionally, for
+ * specific unknown chunks.
+ *
+ * NOTE: prior to 1.6.0 the handling specified for particular chunks on read was
+ * ignored and the default was used, the per-chunk setting only had an effect on
+ * write.  If you wish to have chunk-specific handling on read in code that must
+ * work on earlier versions you must use a user chunk callback to specify the
+ * desired handling (keep or discard.)
+ *
+ * The 'keep' parameter is a PNG_HANDLE_CHUNK_ value as listed below.  The
+ * parameter is interpreted as follows:
+ *
+ * READ:
+ *    PNG_HANDLE_CHUNK_AS_DEFAULT:
+ *       Known chunks: do normal libpng processing, do not keep the chunk (but
+ *          see the comments below about PNG_HANDLE_AS_UNKNOWN_SUPPORTED)
+ *       Unknown chunks: for a specific chunk use the global default, when used
+ *          as the default discard the chunk data.
+ *    PNG_HANDLE_CHUNK_NEVER:
+ *       Discard the chunk data.
+ *    PNG_HANDLE_CHUNK_IF_SAFE:
+ *       Keep the chunk data if the chunk is not critical else raise a chunk
+ *       error.
+ *    PNG_HANDLE_CHUNK_ALWAYS:
+ *       Keep the chunk data.
+ *
+ * If the chunk data is saved it can be retrieved using png_get_unknown_chunks,
+ * below.  Notice that specifying "AS_DEFAULT" as a global default is equivalent
+ * to specifying "NEVER", however when "AS_DEFAULT" is used for specific chunks
+ * it simply resets the behavior to the libpng default.
+ *
+ * INTERACTION WTIH USER CHUNK CALLBACKS:
+ * The per-chunk handling is always used when there is a png_user_chunk_ptr
+ * callback and the callback returns 0; the chunk is then always stored *unless*
+ * it is critical and the per-chunk setting is other than ALWAYS.  Notice that
+ * the global default is *not* used in this case.  (In effect the per-chunk
+ * value is incremented to at least IF_SAFE.)
+ *
+ * IMPORTANT NOTE: this behavior will change in libpng 1.7 - the global and
+ * per-chunk defaults will be honored.  If you want to preserve the current
+ * behavior when your callback returns 0 you must set PNG_HANDLE_CHUNK_IF_SAFE
+ * as the default - if you don't do this libpng 1.6 will issue a warning.
+ *
+ * If you want unhandled unknown chunks to be discarded in libpng 1.6 and
+ * earlier simply return '1' (handled).
+ *
+ * PNG_HANDLE_AS_UNKNOWN_SUPPORTED:
+ *    If this is *not* set known chunks will always be handled by libpng and
+ *    will never be stored in the unknown chunk list.  Known chunks listed to
+ *    png_set_keep_unknown_chunks will have no effect.  If it is set then known
+ *    chunks listed with a keep other than AS_DEFAULT will *never* be processed
+ *    by libpng, in addition critical chunks must either be processed by the
+ *    callback or saved.
+ *
+ *    The IHDR and IEND chunks must not be listed.  Because this turns off the
+ *    default handling for chunks that would otherwise be recognized the
+ *    behavior of libpng transformations may well become incorrect!
+ *
+ * WRITE:
+ *    When writing chunks the options only apply to the chunks specified by
+ *    png_set_unknown_chunks (below), libpng will *always* write known chunks
+ *    required by png_set_ calls and will always write the core critical chunks
+ *    (as required for PLTE).
+ *
+ *    Each chunk in the png_set_unknown_chunks list is looked up in the
+ *    png_set_keep_unknown_chunks list to find the keep setting, this is then
+ *    interpreted as follows:
+ *
+ *    PNG_HANDLE_CHUNK_AS_DEFAULT:
+ *       Write safe-to-copy chunks and write other chunks if the global
+ *       default is set to _ALWAYS, otherwise don't write this chunk.
+ *    PNG_HANDLE_CHUNK_NEVER:
+ *       Do not write the chunk.
+ *    PNG_HANDLE_CHUNK_IF_SAFE:
+ *       Write the chunk if it is safe-to-copy, otherwise do not write it.
+ *    PNG_HANDLE_CHUNK_ALWAYS:
+ *       Write the chunk.
+ *
+ * Note that the default behavior is effectively the opposite of the read case -
+ * in read unknown chunks are not stored by default, in write they are written
+ * by default.  Also the behavior of PNG_HANDLE_CHUNK_IF_SAFE is very different
+ * - on write the safe-to-copy bit is checked, on read the critical bit is
+ * checked and on read if the chunk is critical an error will be raised.
+ *
+ * num_chunks:
+ * ===========
+ *    If num_chunks is positive, then the "keep" parameter specifies the manner
+ *    for handling only those chunks appearing in the chunk_list array,
+ *    otherwise the chunk list array is ignored.
+ *
+ *    If num_chunks is 0 the "keep" parameter specifies the default behavior for
+ *    unknown chunks, as described above.
+ *
+ *    If num_chunks is negative, then the "keep" parameter specifies the manner
+ *    for handling all unknown chunks plus all chunks recognized by libpng
+ *    except for the IHDR, PLTE, tRNS, IDAT, and IEND chunks (which continue to
+ *    be processed by libpng.
  */
-PNG_EXPORT(173, int, png_handle_as_unknown, (png_structp png_ptr,
+PNG_EXPORT(172, void, png_set_keep_unknown_chunks, (png_structrp png_ptr,
+    int keep, png_const_bytep chunk_list, int num_chunks));
+
+/* The "keep" PNG_HANDLE_CHUNK_ parameter for the specified chunk is returned;
+ * the result is therefore true (non-zero) if special handling is required,
+ * false for the default handling.
+ */
+PNG_EXPORT(173, int, png_handle_as_unknown, (png_const_structrp png_ptr,
     png_const_bytep chunk_name));
 #endif
-#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
-PNG_EXPORT(174, void, png_set_unknown_chunks, (png_structp png_ptr,
-    png_infop info_ptr, png_const_unknown_chunkp unknowns,
+
+#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
+PNG_EXPORT(174, void, png_set_unknown_chunks, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_const_unknown_chunkp unknowns,
     int num_unknowns));
+   /* NOTE: prior to 1.6.0 this routine set the 'location' field of the added
+    * unknowns to the location currently stored in the png_struct.  This is
+    * invariably the wrong value on write.  To fix this call the following API
+    * for each chunk in the list with the correct location.  If you know your
+    * code won't be compiled on earlier versions you can rely on
+    * png_set_unknown_chunks(write-ptr, png_get_unknown_chunks(read-ptr)) doing
+    * the correct thing.
+    */
+
 PNG_EXPORT(175, void, png_set_unknown_chunk_location,
-    (png_structp png_ptr, png_infop info_ptr, int chunk, int location));
-PNG_EXPORT(176, int, png_get_unknown_chunks, (png_const_structp png_ptr,
-    png_const_infop info_ptr, png_unknown_chunkpp entries));
+    (png_const_structrp png_ptr, png_inforp info_ptr, int chunk, int location));
+
+PNG_EXPORT(176, int, png_get_unknown_chunks, (png_const_structrp png_ptr,
+    png_inforp info_ptr, png_unknown_chunkpp entries));
 #endif
 
 /* Png_free_data() will turn off the "valid" flag for anything it frees.
  * If you need to turn it off for a chunk that your application has freed,
  * you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK);
  */
-PNG_EXPORT(177, void, png_set_invalid,
-    (png_structp png_ptr, png_infop info_ptr, int mask));
+PNG_EXPORT(177, void, png_set_invalid, (png_const_structrp png_ptr,
+    png_inforp info_ptr, int mask));
 
 #ifdef PNG_INFO_IMAGE_SUPPORTED
 /* The "params" pointer is currently not used and is for future expansion. */
-PNG_EXPORT(178, void, png_read_png, (png_structp png_ptr, png_infop info_ptr,
+PNG_EXPORT(178, void, png_read_png, (png_structrp png_ptr, png_inforp info_ptr,
     int transforms, png_voidp params));
-PNG_EXPORT(179, void, png_write_png, (png_structp png_ptr, png_infop info_ptr,
+PNG_EXPORT(179, void, png_write_png, (png_structrp png_ptr, png_inforp info_ptr,
     int transforms, png_voidp params));
 #endif
 
 PNG_EXPORT(180, png_const_charp, png_get_copyright,
-    (png_const_structp png_ptr));
+    (png_const_structrp png_ptr));
 PNG_EXPORT(181, png_const_charp, png_get_header_ver,
-    (png_const_structp png_ptr));
+    (png_const_structrp png_ptr));
 PNG_EXPORT(182, png_const_charp, png_get_header_version,
-    (png_const_structp png_ptr));
+    (png_const_structrp png_ptr));
 PNG_EXPORT(183, png_const_charp, png_get_libpng_ver,
-    (png_const_structp png_ptr));
+    (png_const_structrp png_ptr));
 
 #ifdef PNG_MNG_FEATURES_SUPPORTED
-PNG_EXPORT(184, png_uint_32, png_permit_mng_features, (png_structp png_ptr,
+PNG_EXPORT(184, png_uint_32, png_permit_mng_features, (png_structrp png_ptr,
     png_uint_32 mng_features_permitted));
 #endif
 
 /* For use in png_set_keep_unknown, added to version 1.2.6 */
 #define PNG_HANDLE_CHUNK_AS_DEFAULT   0
 #define PNG_HANDLE_CHUNK_NEVER        1
 #define PNG_HANDLE_CHUNK_IF_SAFE      2
 #define PNG_HANDLE_CHUNK_ALWAYS       3
+#define PNG_HANDLE_CHUNK_LAST         4
 
 /* Strip the prepended error numbers ("#nnn ") from error and warning
  * messages before passing them to the error or warning handler.
  */
 #ifdef PNG_ERROR_NUMBERS_SUPPORTED
-PNG_EXPORT(185, void, png_set_strip_error_numbers,
-    (png_structp png_ptr,
+PNG_EXPORT(185, void, png_set_strip_error_numbers, (png_structrp png_ptr,
     png_uint_32 strip_mode));
 #endif
 
 /* Added in libpng-1.2.6 */
 #ifdef PNG_SET_USER_LIMITS_SUPPORTED
-PNG_EXPORT(186, void, png_set_user_limits, (png_structp png_ptr,
+PNG_EXPORT(186, void, png_set_user_limits, (png_structrp png_ptr,
     png_uint_32 user_width_max, png_uint_32 user_height_max));
 PNG_EXPORT(187, png_uint_32, png_get_user_width_max,
-    (png_const_structp png_ptr));
+    (png_const_structrp png_ptr));
 PNG_EXPORT(188, png_uint_32, png_get_user_height_max,
-    (png_const_structp png_ptr));
+    (png_const_structrp png_ptr));
 /* Added in libpng-1.4.0 */
-PNG_EXPORT(189, void, png_set_chunk_cache_max, (png_structp png_ptr,
+PNG_EXPORT(189, void, png_set_chunk_cache_max, (png_structrp png_ptr,
     png_uint_32 user_chunk_cache_max));
 PNG_EXPORT(190, png_uint_32, png_get_chunk_cache_max,
-    (png_const_structp png_ptr));
+    (png_const_structrp png_ptr));
 /* Added in libpng-1.4.1 */
-PNG_EXPORT(191, void, png_set_chunk_malloc_max, (png_structp png_ptr,
+PNG_EXPORT(191, void, png_set_chunk_malloc_max, (png_structrp png_ptr,
     png_alloc_size_t user_chunk_cache_max));
 PNG_EXPORT(192, png_alloc_size_t, png_get_chunk_malloc_max,
-    (png_const_structp png_ptr));
+    (png_const_structrp png_ptr));
 #endif
 
 #if defined(PNG_INCH_CONVERSIONS_SUPPORTED)
 PNG_EXPORT(193, png_uint_32, png_get_pixels_per_inch,
-    (png_const_structp png_ptr, png_const_infop info_ptr));
+    (png_const_structrp png_ptr, png_const_inforp info_ptr));
 
 PNG_EXPORT(194, png_uint_32, png_get_x_pixels_per_inch,
-    (png_const_structp png_ptr, png_const_infop info_ptr));
+    (png_const_structrp png_ptr, png_const_inforp info_ptr));
 
 PNG_EXPORT(195, png_uint_32, png_get_y_pixels_per_inch,
-    (png_const_structp png_ptr, png_const_infop info_ptr));
+    (png_const_structrp png_ptr, png_const_inforp info_ptr));
 
 PNG_FP_EXPORT(196, float, png_get_x_offset_inches,
-    (png_const_structp png_ptr, png_const_infop info_ptr))
+    (png_const_structrp png_ptr, png_const_inforp info_ptr))
 #ifdef PNG_FIXED_POINT_SUPPORTED /* otherwise not implemented. */
 PNG_FIXED_EXPORT(211, png_fixed_point, png_get_x_offset_inches_fixed,
-    (png_structp png_ptr, png_const_infop info_ptr))
+    (png_const_structrp png_ptr, png_const_inforp info_ptr))
 #endif
 
-PNG_FP_EXPORT(197, float, png_get_y_offset_inches, (png_const_structp png_ptr,
-    png_const_infop info_ptr))
+PNG_FP_EXPORT(197, float, png_get_y_offset_inches, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr))
 #ifdef PNG_FIXED_POINT_SUPPORTED /* otherwise not implemented. */
 PNG_FIXED_EXPORT(212, png_fixed_point, png_get_y_offset_inches_fixed,
-    (png_structp png_ptr, png_const_infop info_ptr))
+    (png_const_structrp png_ptr, png_const_inforp info_ptr))
 #endif
 
 #  ifdef PNG_pHYs_SUPPORTED
-PNG_EXPORT(198, png_uint_32, png_get_pHYs_dpi, (png_const_structp png_ptr,
-    png_const_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y,
+PNG_EXPORT(198, png_uint_32, png_get_pHYs_dpi, (png_const_structrp png_ptr,
+    png_const_inforp info_ptr, png_uint_32 *res_x, png_uint_32 *res_y,
     int *unit_type));
 #  endif /* PNG_pHYs_SUPPORTED */
 #endif  /* PNG_INCH_CONVERSIONS_SUPPORTED */
 
 /* Added in libpng-1.4.0 */
 #ifdef PNG_IO_STATE_SUPPORTED
-PNG_EXPORT(199, png_uint_32, png_get_io_state, (png_structp png_ptr));
-
-PNG_EXPORTA(200, png_const_bytep, png_get_io_chunk_name,
-    (png_structp png_ptr), PNG_DEPRECATED);
+PNG_EXPORT(199, png_uint_32, png_get_io_state, (png_const_structrp png_ptr));
+
+/* Removed from libpng 1.6; use png_get_io_chunk_type. */
+PNG_REMOVED(200, png_const_bytep, png_get_io_chunk_name, (png_structrp png_ptr),
+    PNG_DEPRECATED)
+
 PNG_EXPORT(216, png_uint_32, png_get_io_chunk_type,
-    (png_const_structp png_ptr));
+    (png_const_structrp png_ptr));
 
 /* The flags returned by png_get_io_state() are the following: */
 #  define PNG_IO_NONE        0x0000   /* no I/O at this moment */
 #  define PNG_IO_READING     0x0001   /* currently reading */
 #  define PNG_IO_WRITING     0x0002   /* currently writing */
 #  define PNG_IO_SIGNATURE   0x0010   /* currently at the file signature */
 #  define PNG_IO_CHUNK_HDR   0x0020   /* currently at the chunk header */
 #  define PNG_IO_CHUNK_DATA  0x0040   /* currently at the chunk data */
@@ -2553,20 +2669,20 @@ PNG_EXPORT(216, png_uint_32, png_get_io_
    -1)-PNG_PASS_START_ROW(pass)))>>PNG_PASS_ROW_SHIFT(pass))
 #define PNG_PASS_COLS(width, pass) (((width)+(((1<<PNG_PASS_COL_SHIFT(pass))\
    -1)-PNG_PASS_START_COL(pass)))>>PNG_PASS_COL_SHIFT(pass))
 
 /* For the reader row callbacks (both progressive and sequential) it is
  * necessary to find the row in the output image given a row in an interlaced
  * image, so two more macros:
  */
-#define PNG_ROW_FROM_PASS_ROW(yIn, pass) \
-   (((yIn)<<PNG_PASS_ROW_SHIFT(pass))+PNG_PASS_START_ROW(pass))
-#define PNG_COL_FROM_PASS_COL(xIn, pass) \
-   (((xIn)<<PNG_PASS_COL_SHIFT(pass))+PNG_PASS_START_COL(pass))
+#define PNG_ROW_FROM_PASS_ROW(y_in, pass) \
+   (((y_in)<<PNG_PASS_ROW_SHIFT(pass))+PNG_PASS_START_ROW(pass))
+#define PNG_COL_FROM_PASS_COL(x_in, pass) \
+   (((x_in)<<PNG_PASS_COL_SHIFT(pass))+PNG_PASS_START_COL(pass))
 
 /* Two macros which return a boolean (0 or 1) saying whether the given row
  * or column is in a particular pass.  These use a common utility macro that
  * returns a mask for a given pass - the offset 'off' selects the row or
  * column version.  The mask has the appropriate bit set for each column in
  * the tile.
  */
 #define PNG_PASS_MASK(pass,off) ( \
@@ -2621,17 +2737,17 @@ PNG_EXPORT(216, png_uint_32, png_get_io_
 #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
 
 #ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED
 PNG_EXPORT(201, png_uint_32, png_get_uint_32, (png_const_bytep buf));
 PNG_EXPORT(202, png_uint_16, png_get_uint_16, (png_const_bytep buf));
 PNG_EXPORT(203, png_int_32, png_get_int_32, (png_const_bytep buf));
 #endif
 
-PNG_EXPORT(204, png_uint_32, png_get_uint_31, (png_structp png_ptr,
+PNG_EXPORT(204, png_uint_32, png_get_uint_31, (png_const_structrp png_ptr,
     png_const_bytep buf));
 /* No png_get_int_16 -- may be added if there's a real need for it. */
 
 /* Place a 32-bit number into a buffer in PNG byte order (big-endian). */
 #ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED
 PNG_EXPORT(205, void, png_save_uint_32, (png_bytep buf, png_uint_32 i));
 #endif
 #ifdef PNG_SAVE_INT_32_SUPPORTED
@@ -2647,41 +2763,510 @@ PNG_EXPORT(207, void, png_save_uint_16, 
 /* No png_save_int_16 -- may be added if there's a real need for it. */
 #endif
 
 #ifdef PNG_USE_READ_MACROS
 /* Inline macros to do direct reads of bytes from the input buffer.
  * The png_get_int_32() routine assumes we are using two's complement
  * format for negative values, which is almost certainly true.
  */
-#  defi