Path: blob/master/src/java.desktop/share/native/libsplashscreen/libpng/png.c
41154 views
/*1* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.2*3* This code is free software; you can redistribute it and/or modify it4* under the terms of the GNU General Public License version 2 only, as5* published by the Free Software Foundation. Oracle designates this6* particular file as subject to the "Classpath" exception as provided7* by Oracle in the LICENSE file that accompanied this code.8*9* This code is distributed in the hope that it will be useful, but WITHOUT10* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or11* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License12* version 2 for more details (a copy is included in the LICENSE file that13* accompanied this code).14*15* You should have received a copy of the GNU General Public License version16* 2 along with this work; if not, write to the Free Software Foundation,17* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.18*19* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA20* or visit www.oracle.com if you need additional information or have any21* questions.22*/2324/* png.c - location for general purpose libpng functions25*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file and, per its terms, should not be removed:30*31* Copyright (c) 2018-2019 Cosmin Truta32* Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson33* Copyright (c) 1996-1997 Andreas Dilger34* Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.35*36* This code is released under the libpng license.37* For conditions of distribution and use, see the disclaimer38* and license in png.h39*/4041#include "pngpriv.h"4243/* Generate a compiler error if there is an old png.h in the search path. */44typedef png_libpng_version_1_6_37 Your_png_h_is_not_version_1_6_37;4546#ifdef __GNUC__47/* The version tests may need to be added to, but the problem warning has48* consistently been fixed in GCC versions which obtain wide-spread release.49* The problem is that many versions of GCC rearrange comparison expressions in50* the optimizer in such a way that the results of the comparison will change51* if signed integer overflow occurs. Such comparisons are not permitted in52* ANSI C90, however GCC isn't clever enough to work out that that do not occur53* below in png_ascii_from_fp and png_muldiv, so it produces a warning with54* -Wextra. Unfortunately this is highly dependent on the optimizer and the55* machine architecture so the warning comes and goes unpredictably and is56* impossible to "fix", even were that a good idea.57*/58#if __GNUC__ == 7 && __GNUC_MINOR__ == 159#define GCC_STRICT_OVERFLOW 160#endif /* GNU 7.1.x */61#endif /* GNU */62#ifndef GCC_STRICT_OVERFLOW63#define GCC_STRICT_OVERFLOW 064#endif6566/* Tells libpng that we have already handled the first "num_bytes" bytes67* of the PNG file signature. If the PNG data is embedded into another68* stream we can set num_bytes = 8 so that libpng will not attempt to read69* or write any of the magic bytes before it starts on the IHDR.70*/7172#ifdef PNG_READ_SUPPORTED73void PNGAPI74png_set_sig_bytes(png_structrp png_ptr, int num_bytes)75{76unsigned int nb = (unsigned int)num_bytes;7778png_debug(1, "in png_set_sig_bytes");7980if (png_ptr == NULL)81return;8283if (num_bytes < 0)84nb = 0;8586if (nb > 8)87png_error(png_ptr, "Too many bytes for PNG signature");8889png_ptr->sig_bytes = (png_byte)nb;90}9192/* Checks whether the supplied bytes match the PNG signature. We allow93* checking less than the full 8-byte signature so that those apps that94* already read the first few bytes of a file to determine the file type95* can simply check the remaining bytes for extra assurance. Returns96* an integer less than, equal to, or greater than zero if sig is found,97* respectively, to be less than, to match, or be greater than the correct98* PNG signature (this is the same behavior as strcmp, memcmp, etc).99*/100int PNGAPI101png_sig_cmp(png_const_bytep sig, size_t start, size_t num_to_check)102{103png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};104105if (num_to_check > 8)106num_to_check = 8;107108else if (num_to_check < 1)109return (-1);110111if (start > 7)112return (-1);113114if (start + num_to_check > 8)115num_to_check = 8 - start;116117return ((int)(memcmp(&sig[start], &png_signature[start], num_to_check)));118}119120#endif /* READ */121122#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)123/* Function to allocate memory for zlib */124PNG_FUNCTION(voidpf /* PRIVATE */,125png_zalloc,(voidpf png_ptr, uInt items, uInt size),PNG_ALLOCATED)126{127png_alloc_size_t num_bytes = size;128129if (png_ptr == NULL)130return NULL;131132if (items >= (~(png_alloc_size_t)0)/size)133{134png_warning (png_voidcast(png_structrp, png_ptr),135"Potential overflow in png_zalloc()");136return NULL;137}138139num_bytes *= items;140return png_malloc_warn(png_voidcast(png_structrp, png_ptr), num_bytes);141}142143/* Function to free memory for zlib */144void /* PRIVATE */145png_zfree(voidpf png_ptr, voidpf ptr)146{147png_free(png_voidcast(png_const_structrp,png_ptr), ptr);148}149150/* Reset the CRC variable to 32 bits of 1's. Care must be taken151* in case CRC is > 32 bits to leave the top bits 0.152*/153void /* PRIVATE */154png_reset_crc(png_structrp png_ptr)155{156/* The cast is safe because the crc is a 32-bit value. */157png_ptr->crc = (png_uint_32)crc32(0, Z_NULL, 0);158}159160/* Calculate the CRC over a section of data. We can only pass as161* much data to this routine as the largest single buffer size. We162* also check that this data will actually be used before going to the163* trouble of calculating it.164*/165void /* PRIVATE */166png_calculate_crc(png_structrp png_ptr, png_const_bytep ptr, size_t length)167{168int need_crc = 1;169170if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0)171{172if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==173(PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))174need_crc = 0;175}176177else /* critical */178{179if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0)180need_crc = 0;181}182183/* 'uLong' is defined in zlib.h as unsigned long; this means that on some184* systems it is a 64-bit value. crc32, however, returns 32 bits so the185* following cast is safe. 'uInt' may be no more than 16 bits, so it is186* necessary to perform a loop here.187*/188if (need_crc != 0 && length > 0)189{190uLong crc = png_ptr->crc; /* Should never issue a warning */191192do193{194uInt safe_length = (uInt)length;195#ifndef __COVERITY__196if (safe_length == 0)197safe_length = (uInt)-1; /* evil, but safe */198#endif199200crc = crc32(crc, ptr, safe_length);201202/* The following should never issue compiler warnings; if they do the203* target system has characteristics that will probably violate other204* assumptions within the libpng code.205*/206ptr += safe_length;207length -= safe_length;208}209while (length > 0);210211/* And the following is always safe because the crc is only 32 bits. */212png_ptr->crc = (png_uint_32)crc;213}214}215216/* Check a user supplied version number, called from both read and write217* functions that create a png_struct.218*/219int220png_user_version_check(png_structrp png_ptr, png_const_charp user_png_ver)221{222/* Libpng versions 1.0.0 and later are binary compatible if the version223* string matches through the second '.'; we must recompile any224* applications that use any older library version.225*/226227if (user_png_ver != NULL)228{229int i = -1;230int found_dots = 0;231232do233{234i++;235if (user_png_ver[i] != PNG_LIBPNG_VER_STRING[i])236png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;237if (user_png_ver[i] == '.')238found_dots++;239} while (found_dots < 2 && user_png_ver[i] != 0 &&240PNG_LIBPNG_VER_STRING[i] != 0);241}242243else244png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;245246if ((png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH) != 0)247{248#ifdef PNG_WARNINGS_SUPPORTED249size_t pos = 0;250char m[128];251252pos = png_safecat(m, (sizeof m), pos,253"Application built with libpng-");254pos = png_safecat(m, (sizeof m), pos, user_png_ver);255pos = png_safecat(m, (sizeof m), pos, " but running with ");256pos = png_safecat(m, (sizeof m), pos, PNG_LIBPNG_VER_STRING);257PNG_UNUSED(pos)258259png_warning(png_ptr, m);260#endif261262#ifdef PNG_ERROR_NUMBERS_SUPPORTED263png_ptr->flags = 0;264#endif265266return 0;267}268269/* Success return. */270return 1;271}272273/* Generic function to create a png_struct for either read or write - this274* contains the common initialization.275*/276PNG_FUNCTION(png_structp /* PRIVATE */,277png_create_png_struct,(png_const_charp user_png_ver, png_voidp error_ptr,278png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,279png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)280{281png_struct create_struct;282# ifdef PNG_SETJMP_SUPPORTED283jmp_buf create_jmp_buf;284# endif285286/* This temporary stack-allocated structure is used to provide a place to287* build enough context to allow the user provided memory allocator (if any)288* to be called.289*/290memset(&create_struct, 0, (sizeof create_struct));291292/* Added at libpng-1.2.6 */293# ifdef PNG_USER_LIMITS_SUPPORTED294create_struct.user_width_max = PNG_USER_WIDTH_MAX;295create_struct.user_height_max = PNG_USER_HEIGHT_MAX;296297# ifdef PNG_USER_CHUNK_CACHE_MAX298/* Added at libpng-1.2.43 and 1.4.0 */299create_struct.user_chunk_cache_max = PNG_USER_CHUNK_CACHE_MAX;300# endif301302# ifdef PNG_USER_CHUNK_MALLOC_MAX303/* Added at libpng-1.2.43 and 1.4.1, required only for read but exists304* in png_struct regardless.305*/306create_struct.user_chunk_malloc_max = PNG_USER_CHUNK_MALLOC_MAX;307# endif308# endif309310/* The following two API calls simply set fields in png_struct, so it is safe311* to do them now even though error handling is not yet set up.312*/313# ifdef PNG_USER_MEM_SUPPORTED314png_set_mem_fn(&create_struct, mem_ptr, malloc_fn, free_fn);315# else316PNG_UNUSED(mem_ptr)317PNG_UNUSED(malloc_fn)318PNG_UNUSED(free_fn)319# endif320321/* (*error_fn) can return control to the caller after the error_ptr is set,322* this will result in a memory leak unless the error_fn does something323* extremely sophisticated. The design lacks merit but is implicit in the324* API.325*/326png_set_error_fn(&create_struct, error_ptr, error_fn, warn_fn);327328# ifdef PNG_SETJMP_SUPPORTED329if (!setjmp(create_jmp_buf))330# endif331{332# ifdef PNG_SETJMP_SUPPORTED333/* Temporarily fake out the longjmp information until we have334* successfully completed this function. This only works if we have335* setjmp() support compiled in, but it is safe - this stuff should336* never happen.337*/338create_struct.jmp_buf_ptr = &create_jmp_buf;339create_struct.jmp_buf_size = 0; /*stack allocation*/340create_struct.longjmp_fn = longjmp;341# endif342/* Call the general version checker (shared with read and write code):343*/344if (png_user_version_check(&create_struct, user_png_ver) != 0)345{346png_structrp png_ptr = png_voidcast(png_structrp,347png_malloc_warn(&create_struct, (sizeof *png_ptr)));348349if (png_ptr != NULL)350{351/* png_ptr->zstream holds a back-pointer to the png_struct, so352* this can only be done now:353*/354create_struct.zstream.zalloc = png_zalloc;355create_struct.zstream.zfree = png_zfree;356create_struct.zstream.opaque = png_ptr;357358# ifdef PNG_SETJMP_SUPPORTED359/* Eliminate the local error handling: */360create_struct.jmp_buf_ptr = NULL;361create_struct.jmp_buf_size = 0;362create_struct.longjmp_fn = 0;363# endif364365*png_ptr = create_struct;366367/* This is the successful return point */368return png_ptr;369}370}371}372373/* A longjmp because of a bug in the application storage allocator or a374* simple failure to allocate the png_struct.375*/376return NULL;377}378379/* Allocate the memory for an info_struct for the application. */380PNG_FUNCTION(png_infop,PNGAPI381png_create_info_struct,(png_const_structrp png_ptr),PNG_ALLOCATED)382{383png_inforp info_ptr;384385png_debug(1, "in png_create_info_struct");386387if (png_ptr == NULL)388return NULL;389390/* Use the internal API that does not (or at least should not) error out, so391* that this call always returns ok. The application typically sets up the392* error handling *after* creating the info_struct because this is the way it393* has always been done in 'example.c'.394*/395info_ptr = png_voidcast(png_inforp, png_malloc_base(png_ptr,396(sizeof *info_ptr)));397398if (info_ptr != NULL)399memset(info_ptr, 0, (sizeof *info_ptr));400401return info_ptr;402}403404/* This function frees the memory associated with a single info struct.405* Normally, one would use either png_destroy_read_struct() or406* png_destroy_write_struct() to free an info struct, but this may be407* useful for some applications. From libpng 1.6.0 this function is also used408* internally to implement the png_info release part of the 'struct' destroy409* APIs. This ensures that all possible approaches free the same data (all of410* it).411*/412void PNGAPI413png_destroy_info_struct(png_const_structrp png_ptr, png_infopp info_ptr_ptr)414{415png_inforp info_ptr = NULL;416417png_debug(1, "in png_destroy_info_struct");418419if (png_ptr == NULL)420return;421422if (info_ptr_ptr != NULL)423info_ptr = *info_ptr_ptr;424425if (info_ptr != NULL)426{427/* Do this first in case of an error below; if the app implements its own428* memory management this can lead to png_free calling png_error, which429* will abort this routine and return control to the app error handler.430* An infinite loop may result if it then tries to free the same info431* ptr.432*/433*info_ptr_ptr = NULL;434435png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);436memset(info_ptr, 0, (sizeof *info_ptr));437png_free(png_ptr, info_ptr);438}439}440441/* Initialize the info structure. This is now an internal function (0.89)442* and applications using it are urged to use png_create_info_struct()443* instead. Use deprecated in 1.6.0, internal use removed (used internally it444* is just a memset).445*446* NOTE: it is almost inconceivable that this API is used because it bypasses447* the user-memory mechanism and the user error handling/warning mechanisms in448* those cases where it does anything other than a memset.449*/450PNG_FUNCTION(void,PNGAPI451png_info_init_3,(png_infopp ptr_ptr, size_t png_info_struct_size),452PNG_DEPRECATED)453{454png_inforp info_ptr = *ptr_ptr;455456png_debug(1, "in png_info_init_3");457458if (info_ptr == NULL)459return;460461if ((sizeof (png_info)) > png_info_struct_size)462{463*ptr_ptr = NULL;464/* The following line is why this API should not be used: */465free(info_ptr);466info_ptr = png_voidcast(png_inforp, png_malloc_base(NULL,467(sizeof *info_ptr)));468if (info_ptr == NULL)469return;470*ptr_ptr = info_ptr;471}472473/* Set everything to 0 */474memset(info_ptr, 0, (sizeof *info_ptr));475}476477/* The following API is not called internally */478void PNGAPI479png_data_freer(png_const_structrp png_ptr, png_inforp info_ptr,480int freer, png_uint_32 mask)481{482png_debug(1, "in png_data_freer");483484if (png_ptr == NULL || info_ptr == NULL)485return;486487if (freer == PNG_DESTROY_WILL_FREE_DATA)488info_ptr->free_me |= mask;489490else if (freer == PNG_USER_WILL_FREE_DATA)491info_ptr->free_me &= ~mask;492493else494png_error(png_ptr, "Unknown freer parameter in png_data_freer");495}496497void PNGAPI498png_free_data(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 mask,499int num)500{501png_debug(1, "in png_free_data");502503if (png_ptr == NULL || info_ptr == NULL)504return;505506#ifdef PNG_TEXT_SUPPORTED507/* Free text item num or (if num == -1) all text items */508if (info_ptr->text != NULL &&509((mask & PNG_FREE_TEXT) & info_ptr->free_me) != 0)510{511if (num != -1)512{513png_free(png_ptr, info_ptr->text[num].key);514info_ptr->text[num].key = NULL;515}516517else518{519int i;520521for (i = 0; i < info_ptr->num_text; i++)522png_free(png_ptr, info_ptr->text[i].key);523524png_free(png_ptr, info_ptr->text);525info_ptr->text = NULL;526info_ptr->num_text = 0;527info_ptr->max_text = 0;528}529}530#endif531532#ifdef PNG_tRNS_SUPPORTED533/* Free any tRNS entry */534if (((mask & PNG_FREE_TRNS) & info_ptr->free_me) != 0)535{536info_ptr->valid &= ~PNG_INFO_tRNS;537png_free(png_ptr, info_ptr->trans_alpha);538info_ptr->trans_alpha = NULL;539info_ptr->num_trans = 0;540}541#endif542543#ifdef PNG_sCAL_SUPPORTED544/* Free any sCAL entry */545if (((mask & PNG_FREE_SCAL) & info_ptr->free_me) != 0)546{547png_free(png_ptr, info_ptr->scal_s_width);548png_free(png_ptr, info_ptr->scal_s_height);549info_ptr->scal_s_width = NULL;550info_ptr->scal_s_height = NULL;551info_ptr->valid &= ~PNG_INFO_sCAL;552}553#endif554555#ifdef PNG_pCAL_SUPPORTED556/* Free any pCAL entry */557if (((mask & PNG_FREE_PCAL) & info_ptr->free_me) != 0)558{559png_free(png_ptr, info_ptr->pcal_purpose);560png_free(png_ptr, info_ptr->pcal_units);561info_ptr->pcal_purpose = NULL;562info_ptr->pcal_units = NULL;563564if (info_ptr->pcal_params != NULL)565{566int i;567568for (i = 0; i < info_ptr->pcal_nparams; i++)569png_free(png_ptr, info_ptr->pcal_params[i]);570571png_free(png_ptr, info_ptr->pcal_params);572info_ptr->pcal_params = NULL;573}574info_ptr->valid &= ~PNG_INFO_pCAL;575}576#endif577578#ifdef PNG_iCCP_SUPPORTED579/* Free any profile entry */580if (((mask & PNG_FREE_ICCP) & info_ptr->free_me) != 0)581{582png_free(png_ptr, info_ptr->iccp_name);583png_free(png_ptr, info_ptr->iccp_profile);584info_ptr->iccp_name = NULL;585info_ptr->iccp_profile = NULL;586info_ptr->valid &= ~PNG_INFO_iCCP;587}588#endif589590#ifdef PNG_sPLT_SUPPORTED591/* Free a given sPLT entry, or (if num == -1) all sPLT entries */592if (info_ptr->splt_palettes != NULL &&593((mask & PNG_FREE_SPLT) & info_ptr->free_me) != 0)594{595if (num != -1)596{597png_free(png_ptr, info_ptr->splt_palettes[num].name);598png_free(png_ptr, info_ptr->splt_palettes[num].entries);599info_ptr->splt_palettes[num].name = NULL;600info_ptr->splt_palettes[num].entries = NULL;601}602603else604{605int i;606607for (i = 0; i < info_ptr->splt_palettes_num; i++)608{609png_free(png_ptr, info_ptr->splt_palettes[i].name);610png_free(png_ptr, info_ptr->splt_palettes[i].entries);611}612613png_free(png_ptr, info_ptr->splt_palettes);614info_ptr->splt_palettes = NULL;615info_ptr->splt_palettes_num = 0;616info_ptr->valid &= ~PNG_INFO_sPLT;617}618}619#endif620621#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED622if (info_ptr->unknown_chunks != NULL &&623((mask & PNG_FREE_UNKN) & info_ptr->free_me) != 0)624{625if (num != -1)626{627png_free(png_ptr, info_ptr->unknown_chunks[num].data);628info_ptr->unknown_chunks[num].data = NULL;629}630631else632{633int i;634635for (i = 0; i < info_ptr->unknown_chunks_num; i++)636png_free(png_ptr, info_ptr->unknown_chunks[i].data);637638png_free(png_ptr, info_ptr->unknown_chunks);639info_ptr->unknown_chunks = NULL;640info_ptr->unknown_chunks_num = 0;641}642}643#endif644645#ifdef PNG_eXIf_SUPPORTED646/* Free any eXIf entry */647if (((mask & PNG_FREE_EXIF) & info_ptr->free_me) != 0)648{649# ifdef PNG_READ_eXIf_SUPPORTED650if (info_ptr->eXIf_buf)651{652png_free(png_ptr, info_ptr->eXIf_buf);653info_ptr->eXIf_buf = NULL;654}655# endif656if (info_ptr->exif)657{658png_free(png_ptr, info_ptr->exif);659info_ptr->exif = NULL;660}661info_ptr->valid &= ~PNG_INFO_eXIf;662}663#endif664665#ifdef PNG_hIST_SUPPORTED666/* Free any hIST entry */667if (((mask & PNG_FREE_HIST) & info_ptr->free_me) != 0)668{669png_free(png_ptr, info_ptr->hist);670info_ptr->hist = NULL;671info_ptr->valid &= ~PNG_INFO_hIST;672}673#endif674675/* Free any PLTE entry that was internally allocated */676if (((mask & PNG_FREE_PLTE) & info_ptr->free_me) != 0)677{678png_free(png_ptr, info_ptr->palette);679info_ptr->palette = NULL;680info_ptr->valid &= ~PNG_INFO_PLTE;681info_ptr->num_palette = 0;682}683684#ifdef PNG_INFO_IMAGE_SUPPORTED685/* Free any image bits attached to the info structure */686if (((mask & PNG_FREE_ROWS) & info_ptr->free_me) != 0)687{688if (info_ptr->row_pointers != NULL)689{690png_uint_32 row;691for (row = 0; row < info_ptr->height; row++)692png_free(png_ptr, info_ptr->row_pointers[row]);693694png_free(png_ptr, info_ptr->row_pointers);695info_ptr->row_pointers = NULL;696}697info_ptr->valid &= ~PNG_INFO_IDAT;698}699#endif700701if (num != -1)702mask &= ~PNG_FREE_MUL;703704info_ptr->free_me &= ~mask;705}706#endif /* READ || WRITE */707708/* This function returns a pointer to the io_ptr associated with the user709* functions. The application should free any memory associated with this710* pointer before png_write_destroy() or png_read_destroy() are called.711*/712png_voidp PNGAPI713png_get_io_ptr(png_const_structrp png_ptr)714{715if (png_ptr == NULL)716return (NULL);717718return (png_ptr->io_ptr);719}720721#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)722# ifdef PNG_STDIO_SUPPORTED723/* Initialize the default input/output functions for the PNG file. If you724* use your own read or write routines, you can call either png_set_read_fn()725* or png_set_write_fn() instead of png_init_io(). If you have defined726* PNG_NO_STDIO or otherwise disabled PNG_STDIO_SUPPORTED, you must use a727* function of your own because "FILE *" isn't necessarily available.728*/729void PNGAPI730png_init_io(png_structrp png_ptr, png_FILE_p fp)731{732png_debug(1, "in png_init_io");733734if (png_ptr == NULL)735return;736737png_ptr->io_ptr = (png_voidp)fp;738}739# endif740741# ifdef PNG_SAVE_INT_32_SUPPORTED742/* PNG signed integers are saved in 32-bit 2's complement format. ANSI C-90743* defines a cast of a signed integer to an unsigned integer either to preserve744* the value, if it is positive, or to calculate:745*746* (UNSIGNED_MAX+1) + integer747*748* Where UNSIGNED_MAX is the appropriate maximum unsigned value, so when the749* negative integral value is added the result will be an unsigned value750* correspnding to the 2's complement representation.751*/752void PNGAPI753png_save_int_32(png_bytep buf, png_int_32 i)754{755png_save_uint_32(buf, (png_uint_32)i);756}757# endif758759# ifdef PNG_TIME_RFC1123_SUPPORTED760/* Convert the supplied time into an RFC 1123 string suitable for use in761* a "Creation Time" or other text-based time string.762*/763int PNGAPI764png_convert_to_rfc1123_buffer(char out[29], png_const_timep ptime)765{766static const char short_months[12][4] =767{"Jan", "Feb", "Mar", "Apr", "May", "Jun",768"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};769770if (out == NULL)771return 0;772773if (ptime->year > 9999 /* RFC1123 limitation */ ||774ptime->month == 0 || ptime->month > 12 ||775ptime->day == 0 || ptime->day > 31 ||776ptime->hour > 23 || ptime->minute > 59 ||777ptime->second > 60)778return 0;779780{781size_t pos = 0;782char number_buf[5]; /* enough for a four-digit year */783784# define APPEND_STRING(string) pos = png_safecat(out, 29, pos, (string))785# define APPEND_NUMBER(format, value)\786APPEND_STRING(PNG_FORMAT_NUMBER(number_buf, format, (value)))787# define APPEND(ch) if (pos < 28) out[pos++] = (ch)788789APPEND_NUMBER(PNG_NUMBER_FORMAT_u, (unsigned)ptime->day);790APPEND(' ');791APPEND_STRING(short_months[(ptime->month - 1)]);792APPEND(' ');793APPEND_NUMBER(PNG_NUMBER_FORMAT_u, ptime->year);794APPEND(' ');795APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->hour);796APPEND(':');797APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->minute);798APPEND(':');799APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->second);800APPEND_STRING(" +0000"); /* This reliably terminates the buffer */801PNG_UNUSED (pos)802803# undef APPEND804# undef APPEND_NUMBER805# undef APPEND_STRING806}807808return 1;809}810811# if PNG_LIBPNG_VER < 10700812/* To do: remove the following from libpng-1.7 */813/* Original API that uses a private buffer in png_struct.814* Deprecated because it causes png_struct to carry a spurious temporary815* buffer (png_struct::time_buffer), better to have the caller pass this in.816*/817png_const_charp PNGAPI818png_convert_to_rfc1123(png_structrp png_ptr, png_const_timep ptime)819{820if (png_ptr != NULL)821{822/* The only failure above if png_ptr != NULL is from an invalid ptime */823if (png_convert_to_rfc1123_buffer(png_ptr->time_buffer, ptime) == 0)824png_warning(png_ptr, "Ignoring invalid time value");825826else827return png_ptr->time_buffer;828}829830return NULL;831}832# endif /* LIBPNG_VER < 10700 */833# endif /* TIME_RFC1123 */834835#endif /* READ || WRITE */836837png_const_charp PNGAPI838png_get_copyright(png_const_structrp png_ptr)839{840PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */841#ifdef PNG_STRING_COPYRIGHT842return PNG_STRING_COPYRIGHT843#else844return PNG_STRING_NEWLINE \845"libpng version 1.6.37" PNG_STRING_NEWLINE \846"Copyright (c) 2018-2019 Cosmin Truta" PNG_STRING_NEWLINE \847"Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson" \848PNG_STRING_NEWLINE \849"Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \850"Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \851PNG_STRING_NEWLINE;852#endif853}854855/* The following return the library version as a short string in the856* format 1.0.0 through 99.99.99zz. To get the version of *.h files857* used with your application, print out PNG_LIBPNG_VER_STRING, which858* is defined in png.h.859* Note: now there is no difference between png_get_libpng_ver() and860* png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,861* it is guaranteed that png.c uses the correct version of png.h.862*/863png_const_charp PNGAPI864png_get_libpng_ver(png_const_structrp png_ptr)865{866/* Version of *.c files used when building libpng */867return png_get_header_ver(png_ptr);868}869870png_const_charp PNGAPI871png_get_header_ver(png_const_structrp png_ptr)872{873/* Version of *.h files used when building libpng */874PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */875return PNG_LIBPNG_VER_STRING;876}877878png_const_charp PNGAPI879png_get_header_version(png_const_structrp png_ptr)880{881/* Returns longer string containing both version and date */882PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */883#ifdef __STDC__884return PNG_HEADER_VERSION_STRING885# ifndef PNG_READ_SUPPORTED886" (NO READ SUPPORT)"887# endif888PNG_STRING_NEWLINE;889#else890return PNG_HEADER_VERSION_STRING;891#endif892}893894#ifdef PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED895/* NOTE: this routine is not used internally! */896/* Build a grayscale palette. Palette is assumed to be 1 << bit_depth897* large of png_color. This lets grayscale images be treated as898* paletted. Most useful for gamma correction and simplification899* of code. This API is not used internally.900*/901void PNGAPI902png_build_grayscale_palette(int bit_depth, png_colorp palette)903{904int num_palette;905int color_inc;906int i;907int v;908909png_debug(1, "in png_do_build_grayscale_palette");910911if (palette == NULL)912return;913914switch (bit_depth)915{916case 1:917num_palette = 2;918color_inc = 0xff;919break;920921case 2:922num_palette = 4;923color_inc = 0x55;924break;925926case 4:927num_palette = 16;928color_inc = 0x11;929break;930931case 8:932num_palette = 256;933color_inc = 1;934break;935936default:937num_palette = 0;938color_inc = 0;939break;940}941942for (i = 0, v = 0; i < num_palette; i++, v += color_inc)943{944palette[i].red = (png_byte)(v & 0xff);945palette[i].green = (png_byte)(v & 0xff);946palette[i].blue = (png_byte)(v & 0xff);947}948}949#endif950951#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED952int PNGAPI953png_handle_as_unknown(png_const_structrp png_ptr, png_const_bytep chunk_name)954{955/* Check chunk_name and return "keep" value if it's on the list, else 0 */956png_const_bytep p, p_end;957958if (png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list == 0)959return PNG_HANDLE_CHUNK_AS_DEFAULT;960961p_end = png_ptr->chunk_list;962p = p_end + png_ptr->num_chunk_list*5; /* beyond end */963964/* The code is the fifth byte after each four byte string. Historically this965* code was always searched from the end of the list, this is no longer966* necessary because the 'set' routine handles duplicate entries correctly.967*/968do /* num_chunk_list > 0, so at least one */969{970p -= 5;971972if (memcmp(chunk_name, p, 4) == 0)973return p[4];974}975while (p > p_end);976977/* This means that known chunks should be processed and unknown chunks should978* be handled according to the value of png_ptr->unknown_default; this can be979* confusing because, as a result, there are two levels of defaulting for980* unknown chunks.981*/982return PNG_HANDLE_CHUNK_AS_DEFAULT;983}984985#if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) ||\986defined(PNG_HANDLE_AS_UNKNOWN_SUPPORTED)987int /* PRIVATE */988png_chunk_unknown_handling(png_const_structrp png_ptr, png_uint_32 chunk_name)989{990png_byte chunk_string[5];991992PNG_CSTRING_FROM_CHUNK(chunk_string, chunk_name);993return png_handle_as_unknown(png_ptr, chunk_string);994}995#endif /* READ_UNKNOWN_CHUNKS || HANDLE_AS_UNKNOWN */996#endif /* SET_UNKNOWN_CHUNKS */997998#ifdef PNG_READ_SUPPORTED999/* This function, added to libpng-1.0.6g, is untested. */1000int PNGAPI1001png_reset_zstream(png_structrp png_ptr)1002{1003if (png_ptr == NULL)1004return Z_STREAM_ERROR;10051006/* WARNING: this resets the window bits to the maximum! */1007return (inflateReset(&png_ptr->zstream));1008}1009#endif /* READ */10101011/* This function was added to libpng-1.0.7 */1012png_uint_32 PNGAPI1013png_access_version_number(void)1014{1015/* Version of *.c files used when building libpng */1016return((png_uint_32)PNG_LIBPNG_VER);1017}10181019#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)1020/* Ensure that png_ptr->zstream.msg holds some appropriate error message string.1021* If it doesn't 'ret' is used to set it to something appropriate, even in cases1022* like Z_OK or Z_STREAM_END where the error code is apparently a success code.1023*/1024void /* PRIVATE */1025png_zstream_error(png_structrp png_ptr, int ret)1026{1027/* Translate 'ret' into an appropriate error string, priority is given to the1028* one in zstream if set. This always returns a string, even in cases like1029* Z_OK or Z_STREAM_END where the error code is a success code.1030*/1031if (png_ptr->zstream.msg == NULL) switch (ret)1032{1033default:1034case Z_OK:1035png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected zlib return code");1036break;10371038case Z_STREAM_END:1039/* Normal exit */1040png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected end of LZ stream");1041break;10421043case Z_NEED_DICT:1044/* This means the deflate stream did not have a dictionary; this1045* indicates a bogus PNG.1046*/1047png_ptr->zstream.msg = PNGZ_MSG_CAST("missing LZ dictionary");1048break;10491050case Z_ERRNO:1051/* gz APIs only: should not happen */1052png_ptr->zstream.msg = PNGZ_MSG_CAST("zlib IO error");1053break;10541055case Z_STREAM_ERROR:1056/* internal libpng error */1057png_ptr->zstream.msg = PNGZ_MSG_CAST("bad parameters to zlib");1058break;10591060case Z_DATA_ERROR:1061png_ptr->zstream.msg = PNGZ_MSG_CAST("damaged LZ stream");1062break;10631064case Z_MEM_ERROR:1065png_ptr->zstream.msg = PNGZ_MSG_CAST("insufficient memory");1066break;10671068case Z_BUF_ERROR:1069/* End of input or output; not a problem if the caller is doing1070* incremental read or write.1071*/1072png_ptr->zstream.msg = PNGZ_MSG_CAST("truncated");1073break;10741075case Z_VERSION_ERROR:1076png_ptr->zstream.msg = PNGZ_MSG_CAST("unsupported zlib version");1077break;10781079case PNG_UNEXPECTED_ZLIB_RETURN:1080/* Compile errors here mean that zlib now uses the value co-opted in1081* pngpriv.h for PNG_UNEXPECTED_ZLIB_RETURN; update the switch above1082* and change pngpriv.h. Note that this message is "... return",1083* whereas the default/Z_OK one is "... return code".1084*/1085png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected zlib return");1086break;1087}1088}10891090/* png_convert_size: a PNGAPI but no longer in png.h, so deleted1091* at libpng 1.5.5!1092*/10931094/* Added at libpng version 1.2.34 and 1.4.0 (moved from pngset.c) */1095#ifdef PNG_GAMMA_SUPPORTED /* always set if COLORSPACE */1096static int1097png_colorspace_check_gamma(png_const_structrp png_ptr,1098png_colorspacerp colorspace, png_fixed_point gAMA, int from)1099/* This is called to check a new gamma value against an existing one. The1100* routine returns false if the new gamma value should not be written.1101*1102* 'from' says where the new gamma value comes from:1103*1104* 0: the new gamma value is the libpng estimate for an ICC profile1105* 1: the new gamma value comes from a gAMA chunk1106* 2: the new gamma value comes from an sRGB chunk1107*/1108{1109png_fixed_point gtest;11101111if ((colorspace->flags & PNG_COLORSPACE_HAVE_GAMMA) != 0 &&1112(png_muldiv(>est, colorspace->gamma, PNG_FP_1, gAMA) == 0 ||1113png_gamma_significant(gtest) != 0))1114{1115/* Either this is an sRGB image, in which case the calculated gamma1116* approximation should match, or this is an image with a profile and the1117* value libpng calculates for the gamma of the profile does not match the1118* value recorded in the file. The former, sRGB, case is an error, the1119* latter is just a warning.1120*/1121if ((colorspace->flags & PNG_COLORSPACE_FROM_sRGB) != 0 || from == 2)1122{1123png_chunk_report(png_ptr, "gamma value does not match sRGB",1124PNG_CHUNK_ERROR);1125/* Do not overwrite an sRGB value */1126return from == 2;1127}11281129else /* sRGB tag not involved */1130{1131png_chunk_report(png_ptr, "gamma value does not match libpng estimate",1132PNG_CHUNK_WARNING);1133return from == 1;1134}1135}11361137return 1;1138}11391140void /* PRIVATE */1141png_colorspace_set_gamma(png_const_structrp png_ptr,1142png_colorspacerp colorspace, png_fixed_point gAMA)1143{1144/* Changed in libpng-1.5.4 to limit the values to ensure overflow can't1145* occur. Since the fixed point representation is asymmetrical it is1146* possible for 1/gamma to overflow the limit of 21474 and this means the1147* gamma value must be at least 5/100000 and hence at most 20000.0. For1148* safety the limits here are a little narrower. The values are 0.00016 to1149* 6250.0, which are truly ridiculous gamma values (and will produce1150* displays that are all black or all white.)1151*1152* In 1.6.0 this test replaces the ones in pngrutil.c, in the gAMA chunk1153* handling code, which only required the value to be >0.1154*/1155png_const_charp errmsg;11561157if (gAMA < 16 || gAMA > 625000000)1158errmsg = "gamma value out of range";11591160# ifdef PNG_READ_gAMA_SUPPORTED1161/* Allow the application to set the gamma value more than once */1162else if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0 &&1163(colorspace->flags & PNG_COLORSPACE_FROM_gAMA) != 0)1164errmsg = "duplicate";1165# endif11661167/* Do nothing if the colorspace is already invalid */1168else if ((colorspace->flags & PNG_COLORSPACE_INVALID) != 0)1169return;11701171else1172{1173if (png_colorspace_check_gamma(png_ptr, colorspace, gAMA,11741/*from gAMA*/) != 0)1175{1176/* Store this gamma value. */1177colorspace->gamma = gAMA;1178colorspace->flags |=1179(PNG_COLORSPACE_HAVE_GAMMA | PNG_COLORSPACE_FROM_gAMA);1180}11811182/* At present if the check_gamma test fails the gamma of the colorspace is1183* not updated however the colorspace is not invalidated. This1184* corresponds to the case where the existing gamma comes from an sRGB1185* chunk or profile. An error message has already been output.1186*/1187return;1188}11891190/* Error exit - errmsg has been set. */1191colorspace->flags |= PNG_COLORSPACE_INVALID;1192png_chunk_report(png_ptr, errmsg, PNG_CHUNK_WRITE_ERROR);1193}11941195void /* PRIVATE */1196png_colorspace_sync_info(png_const_structrp png_ptr, png_inforp info_ptr)1197{1198if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)1199{1200/* Everything is invalid */1201info_ptr->valid &= ~(PNG_INFO_gAMA|PNG_INFO_cHRM|PNG_INFO_sRGB|1202PNG_INFO_iCCP);12031204# ifdef PNG_COLORSPACE_SUPPORTED1205/* Clean up the iCCP profile now if it won't be used. */1206png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, -1/*not used*/);1207# else1208PNG_UNUSED(png_ptr)1209# endif1210}12111212else1213{1214# ifdef PNG_COLORSPACE_SUPPORTED1215/* Leave the INFO_iCCP flag set if the pngset.c code has already set1216* it; this allows a PNG to contain a profile which matches sRGB and1217* yet still have that profile retrievable by the application.1218*/1219if ((info_ptr->colorspace.flags & PNG_COLORSPACE_MATCHES_sRGB) != 0)1220info_ptr->valid |= PNG_INFO_sRGB;12211222else1223info_ptr->valid &= ~PNG_INFO_sRGB;12241225if ((info_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0)1226info_ptr->valid |= PNG_INFO_cHRM;12271228else1229info_ptr->valid &= ~PNG_INFO_cHRM;1230# endif12311232if ((info_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_GAMMA) != 0)1233info_ptr->valid |= PNG_INFO_gAMA;12341235else1236info_ptr->valid &= ~PNG_INFO_gAMA;1237}1238}12391240#ifdef PNG_READ_SUPPORTED1241void /* PRIVATE */1242png_colorspace_sync(png_const_structrp png_ptr, png_inforp info_ptr)1243{1244if (info_ptr == NULL) /* reduce code size; check here not in the caller */1245return;12461247info_ptr->colorspace = png_ptr->colorspace;1248png_colorspace_sync_info(png_ptr, info_ptr);1249}1250#endif1251#endif /* GAMMA */12521253#ifdef PNG_COLORSPACE_SUPPORTED1254/* Added at libpng-1.5.5 to support read and write of true CIEXYZ values for1255* cHRM, as opposed to using chromaticities. These internal APIs return1256* non-zero on a parameter error. The X, Y and Z values are required to be1257* positive and less than 1.0.1258*/1259static int1260png_xy_from_XYZ(png_xy *xy, const png_XYZ *XYZ)1261{1262png_int_32 d, dwhite, whiteX, whiteY;12631264d = XYZ->red_X + XYZ->red_Y + XYZ->red_Z;1265if (png_muldiv(&xy->redx, XYZ->red_X, PNG_FP_1, d) == 0)1266return 1;1267if (png_muldiv(&xy->redy, XYZ->red_Y, PNG_FP_1, d) == 0)1268return 1;1269dwhite = d;1270whiteX = XYZ->red_X;1271whiteY = XYZ->red_Y;12721273d = XYZ->green_X + XYZ->green_Y + XYZ->green_Z;1274if (png_muldiv(&xy->greenx, XYZ->green_X, PNG_FP_1, d) == 0)1275return 1;1276if (png_muldiv(&xy->greeny, XYZ->green_Y, PNG_FP_1, d) == 0)1277return 1;1278dwhite += d;1279whiteX += XYZ->green_X;1280whiteY += XYZ->green_Y;12811282d = XYZ->blue_X + XYZ->blue_Y + XYZ->blue_Z;1283if (png_muldiv(&xy->bluex, XYZ->blue_X, PNG_FP_1, d) == 0)1284return 1;1285if (png_muldiv(&xy->bluey, XYZ->blue_Y, PNG_FP_1, d) == 0)1286return 1;1287dwhite += d;1288whiteX += XYZ->blue_X;1289whiteY += XYZ->blue_Y;12901291/* The reference white is simply the sum of the end-point (X,Y,Z) vectors,1292* thus:1293*/1294if (png_muldiv(&xy->whitex, whiteX, PNG_FP_1, dwhite) == 0)1295return 1;1296if (png_muldiv(&xy->whitey, whiteY, PNG_FP_1, dwhite) == 0)1297return 1;12981299return 0;1300}13011302static int1303png_XYZ_from_xy(png_XYZ *XYZ, const png_xy *xy)1304{1305png_fixed_point red_inverse, green_inverse, blue_scale;1306png_fixed_point left, right, denominator;13071308/* Check xy and, implicitly, z. Note that wide gamut color spaces typically1309* have end points with 0 tristimulus values (these are impossible end1310* points, but they are used to cover the possible colors). We check1311* xy->whitey against 5, not 0, to avoid a possible integer overflow.1312*/1313if (xy->redx < 0 || xy->redx > PNG_FP_1) return 1;1314if (xy->redy < 0 || xy->redy > PNG_FP_1-xy->redx) return 1;1315if (xy->greenx < 0 || xy->greenx > PNG_FP_1) return 1;1316if (xy->greeny < 0 || xy->greeny > PNG_FP_1-xy->greenx) return 1;1317if (xy->bluex < 0 || xy->bluex > PNG_FP_1) return 1;1318if (xy->bluey < 0 || xy->bluey > PNG_FP_1-xy->bluex) return 1;1319if (xy->whitex < 0 || xy->whitex > PNG_FP_1) return 1;1320if (xy->whitey < 5 || xy->whitey > PNG_FP_1-xy->whitex) return 1;13211322/* The reverse calculation is more difficult because the original tristimulus1323* value had 9 independent values (red,green,blue)x(X,Y,Z) however only 81324* derived values were recorded in the cHRM chunk;1325* (red,green,blue,white)x(x,y). This loses one degree of freedom and1326* therefore an arbitrary ninth value has to be introduced to undo the1327* original transformations.1328*1329* Think of the original end-points as points in (X,Y,Z) space. The1330* chromaticity values (c) have the property:1331*1332* C1333* c = ---------1334* X + Y + Z1335*1336* For each c (x,y,z) from the corresponding original C (X,Y,Z). Thus the1337* three chromaticity values (x,y,z) for each end-point obey the1338* relationship:1339*1340* x + y + z = 11341*1342* This describes the plane in (X,Y,Z) space that intersects each axis at the1343* value 1.0; call this the chromaticity plane. Thus the chromaticity1344* calculation has scaled each end-point so that it is on the x+y+z=1 plane1345* and chromaticity is the intersection of the vector from the origin to the1346* (X,Y,Z) value with the chromaticity plane.1347*1348* To fully invert the chromaticity calculation we would need the three1349* end-point scale factors, (red-scale, green-scale, blue-scale), but these1350* were not recorded. Instead we calculated the reference white (X,Y,Z) and1351* recorded the chromaticity of this. The reference white (X,Y,Z) would have1352* given all three of the scale factors since:1353*1354* color-C = color-c * color-scale1355* white-C = red-C + green-C + blue-C1356* = red-c*red-scale + green-c*green-scale + blue-c*blue-scale1357*1358* But cHRM records only white-x and white-y, so we have lost the white scale1359* factor:1360*1361* white-C = white-c*white-scale1362*1363* To handle this the inverse transformation makes an arbitrary assumption1364* about white-scale:1365*1366* Assume: white-Y = 1.01367* Hence: white-scale = 1/white-y1368* Or: red-Y + green-Y + blue-Y = 1.01369*1370* Notice the last statement of the assumption gives an equation in three of1371* the nine values we want to calculate. 8 more equations come from the1372* above routine as summarised at the top above (the chromaticity1373* calculation):1374*1375* Given: color-x = color-X / (color-X + color-Y + color-Z)1376* Hence: (color-x - 1)*color-X + color.x*color-Y + color.x*color-Z = 01377*1378* This is 9 simultaneous equations in the 9 variables "color-C" and can be1379* solved by Cramer's rule. Cramer's rule requires calculating 10 9x9 matrix1380* determinants, however this is not as bad as it seems because only 28 of1381* the total of 90 terms in the various matrices are non-zero. Nevertheless1382* Cramer's rule is notoriously numerically unstable because the determinant1383* calculation involves the difference of large, but similar, numbers. It is1384* difficult to be sure that the calculation is stable for real world values1385* and it is certain that it becomes unstable where the end points are close1386* together.1387*1388* So this code uses the perhaps slightly less optimal but more1389* understandable and totally obvious approach of calculating color-scale.1390*1391* This algorithm depends on the precision in white-scale and that is1392* (1/white-y), so we can immediately see that as white-y approaches 0 the1393* accuracy inherent in the cHRM chunk drops off substantially.1394*1395* libpng arithmetic: a simple inversion of the above equations1396* ------------------------------------------------------------1397*1398* white_scale = 1/white-y1399* white-X = white-x * white-scale1400* white-Y = 1.01401* white-Z = (1 - white-x - white-y) * white_scale1402*1403* white-C = red-C + green-C + blue-C1404* = red-c*red-scale + green-c*green-scale + blue-c*blue-scale1405*1406* This gives us three equations in (red-scale,green-scale,blue-scale) where1407* all the coefficients are now known:1408*1409* red-x*red-scale + green-x*green-scale + blue-x*blue-scale1410* = white-x/white-y1411* red-y*red-scale + green-y*green-scale + blue-y*blue-scale = 11412* red-z*red-scale + green-z*green-scale + blue-z*blue-scale1413* = (1 - white-x - white-y)/white-y1414*1415* In the last equation color-z is (1 - color-x - color-y) so we can add all1416* three equations together to get an alternative third:1417*1418* red-scale + green-scale + blue-scale = 1/white-y = white-scale1419*1420* So now we have a Cramer's rule solution where the determinants are just1421* 3x3 - far more tractible. Unfortunately 3x3 determinants still involve1422* multiplication of three coefficients so we can't guarantee to avoid1423* overflow in the libpng fixed point representation. Using Cramer's rule in1424* floating point is probably a good choice here, but it's not an option for1425* fixed point. Instead proceed to simplify the first two equations by1426* eliminating what is likely to be the largest value, blue-scale:1427*1428* blue-scale = white-scale - red-scale - green-scale1429*1430* Hence:1431*1432* (red-x - blue-x)*red-scale + (green-x - blue-x)*green-scale =1433* (white-x - blue-x)*white-scale1434*1435* (red-y - blue-y)*red-scale + (green-y - blue-y)*green-scale =1436* 1 - blue-y*white-scale1437*1438* And now we can trivially solve for (red-scale,green-scale):1439*1440* green-scale =1441* (white-x - blue-x)*white-scale - (red-x - blue-x)*red-scale1442* -----------------------------------------------------------1443* green-x - blue-x1444*1445* red-scale =1446* 1 - blue-y*white-scale - (green-y - blue-y) * green-scale1447* ---------------------------------------------------------1448* red-y - blue-y1449*1450* Hence:1451*1452* red-scale =1453* ( (green-x - blue-x) * (white-y - blue-y) -1454* (green-y - blue-y) * (white-x - blue-x) ) / white-y1455* -------------------------------------------------------------------------1456* (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)1457*1458* green-scale =1459* ( (red-y - blue-y) * (white-x - blue-x) -1460* (red-x - blue-x) * (white-y - blue-y) ) / white-y1461* -------------------------------------------------------------------------1462* (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)1463*1464* Accuracy:1465* The input values have 5 decimal digits of accuracy. The values are all in1466* the range 0 < value < 1, so simple products are in the same range but may1467* need up to 10 decimal digits to preserve the original precision and avoid1468* underflow. Because we are using a 32-bit signed representation we cannot1469* match this; the best is a little over 9 decimal digits, less than 10.1470*1471* The approach used here is to preserve the maximum precision within the1472* signed representation. Because the red-scale calculation above uses the1473* difference between two products of values that must be in the range -1..+11474* it is sufficient to divide the product by 7; ceil(100,000/32767*2). The1475* factor is irrelevant in the calculation because it is applied to both1476* numerator and denominator.1477*1478* Note that the values of the differences of the products of the1479* chromaticities in the above equations tend to be small, for example for1480* the sRGB chromaticities they are:1481*1482* red numerator: -0.047511483* green numerator: -0.087881484* denominator: -0.2241 (without white-y multiplication)1485*1486* The resultant Y coefficients from the chromaticities of some widely used1487* color space definitions are (to 15 decimal places):1488*1489* sRGB1490* 0.212639005871510 0.715168678767756 0.0721923153607341491* Kodak ProPhoto1492* 0.288071128229293 0.711843217810102 0.0000856539606051493* Adobe RGB1494* 0.297344975250536 0.627363566255466 0.0752914584939981495* Adobe Wide Gamut RGB1496* 0.258728243040113 0.724682314948566 0.0165894420113211497*/1498/* By the argument, above overflow should be impossible here. The return1499* value of 2 indicates an internal error to the caller.1500*/1501if (png_muldiv(&left, xy->greenx-xy->bluex, xy->redy - xy->bluey, 7) == 0)1502return 2;1503if (png_muldiv(&right, xy->greeny-xy->bluey, xy->redx - xy->bluex, 7) == 0)1504return 2;1505denominator = left - right;15061507/* Now find the red numerator. */1508if (png_muldiv(&left, xy->greenx-xy->bluex, xy->whitey-xy->bluey, 7) == 0)1509return 2;1510if (png_muldiv(&right, xy->greeny-xy->bluey, xy->whitex-xy->bluex, 7) == 0)1511return 2;15121513/* Overflow is possible here and it indicates an extreme set of PNG cHRM1514* chunk values. This calculation actually returns the reciprocal of the1515* scale value because this allows us to delay the multiplication of white-y1516* into the denominator, which tends to produce a small number.1517*/1518if (png_muldiv(&red_inverse, xy->whitey, denominator, left-right) == 0 ||1519red_inverse <= xy->whitey /* r+g+b scales = white scale */)1520return 1;15211522/* Similarly for green_inverse: */1523if (png_muldiv(&left, xy->redy-xy->bluey, xy->whitex-xy->bluex, 7) == 0)1524return 2;1525if (png_muldiv(&right, xy->redx-xy->bluex, xy->whitey-xy->bluey, 7) == 0)1526return 2;1527if (png_muldiv(&green_inverse, xy->whitey, denominator, left-right) == 0 ||1528green_inverse <= xy->whitey)1529return 1;15301531/* And the blue scale, the checks above guarantee this can't overflow but it1532* can still produce 0 for extreme cHRM values.1533*/1534blue_scale = png_reciprocal(xy->whitey) - png_reciprocal(red_inverse) -1535png_reciprocal(green_inverse);1536if (blue_scale <= 0)1537return 1;153815391540/* And fill in the png_XYZ: */1541if (png_muldiv(&XYZ->red_X, xy->redx, PNG_FP_1, red_inverse) == 0)1542return 1;1543if (png_muldiv(&XYZ->red_Y, xy->redy, PNG_FP_1, red_inverse) == 0)1544return 1;1545if (png_muldiv(&XYZ->red_Z, PNG_FP_1 - xy->redx - xy->redy, PNG_FP_1,1546red_inverse) == 0)1547return 1;15481549if (png_muldiv(&XYZ->green_X, xy->greenx, PNG_FP_1, green_inverse) == 0)1550return 1;1551if (png_muldiv(&XYZ->green_Y, xy->greeny, PNG_FP_1, green_inverse) == 0)1552return 1;1553if (png_muldiv(&XYZ->green_Z, PNG_FP_1 - xy->greenx - xy->greeny, PNG_FP_1,1554green_inverse) == 0)1555return 1;15561557if (png_muldiv(&XYZ->blue_X, xy->bluex, blue_scale, PNG_FP_1) == 0)1558return 1;1559if (png_muldiv(&XYZ->blue_Y, xy->bluey, blue_scale, PNG_FP_1) == 0)1560return 1;1561if (png_muldiv(&XYZ->blue_Z, PNG_FP_1 - xy->bluex - xy->bluey, blue_scale,1562PNG_FP_1) == 0)1563return 1;15641565return 0; /*success*/1566}15671568static int1569png_XYZ_normalize(png_XYZ *XYZ)1570{1571png_int_32 Y;15721573if (XYZ->red_Y < 0 || XYZ->green_Y < 0 || XYZ->blue_Y < 0 ||1574XYZ->red_X < 0 || XYZ->green_X < 0 || XYZ->blue_X < 0 ||1575XYZ->red_Z < 0 || XYZ->green_Z < 0 || XYZ->blue_Z < 0)1576return 1;15771578/* Normalize by scaling so the sum of the end-point Y values is PNG_FP_1.1579* IMPLEMENTATION NOTE: ANSI requires signed overflow not to occur, therefore1580* relying on addition of two positive values producing a negative one is not1581* safe.1582*/1583Y = XYZ->red_Y;1584if (0x7fffffff - Y < XYZ->green_X)1585return 1;1586Y += XYZ->green_Y;1587if (0x7fffffff - Y < XYZ->blue_X)1588return 1;1589Y += XYZ->blue_Y;15901591if (Y != PNG_FP_1)1592{1593if (png_muldiv(&XYZ->red_X, XYZ->red_X, PNG_FP_1, Y) == 0)1594return 1;1595if (png_muldiv(&XYZ->red_Y, XYZ->red_Y, PNG_FP_1, Y) == 0)1596return 1;1597if (png_muldiv(&XYZ->red_Z, XYZ->red_Z, PNG_FP_1, Y) == 0)1598return 1;15991600if (png_muldiv(&XYZ->green_X, XYZ->green_X, PNG_FP_1, Y) == 0)1601return 1;1602if (png_muldiv(&XYZ->green_Y, XYZ->green_Y, PNG_FP_1, Y) == 0)1603return 1;1604if (png_muldiv(&XYZ->green_Z, XYZ->green_Z, PNG_FP_1, Y) == 0)1605return 1;16061607if (png_muldiv(&XYZ->blue_X, XYZ->blue_X, PNG_FP_1, Y) == 0)1608return 1;1609if (png_muldiv(&XYZ->blue_Y, XYZ->blue_Y, PNG_FP_1, Y) == 0)1610return 1;1611if (png_muldiv(&XYZ->blue_Z, XYZ->blue_Z, PNG_FP_1, Y) == 0)1612return 1;1613}16141615return 0;1616}16171618static int1619png_colorspace_endpoints_match(const png_xy *xy1, const png_xy *xy2, int delta)1620{1621/* Allow an error of +/-0.01 (absolute value) on each chromaticity */1622if (PNG_OUT_OF_RANGE(xy1->whitex, xy2->whitex,delta) ||1623PNG_OUT_OF_RANGE(xy1->whitey, xy2->whitey,delta) ||1624PNG_OUT_OF_RANGE(xy1->redx, xy2->redx, delta) ||1625PNG_OUT_OF_RANGE(xy1->redy, xy2->redy, delta) ||1626PNG_OUT_OF_RANGE(xy1->greenx, xy2->greenx,delta) ||1627PNG_OUT_OF_RANGE(xy1->greeny, xy2->greeny,delta) ||1628PNG_OUT_OF_RANGE(xy1->bluex, xy2->bluex, delta) ||1629PNG_OUT_OF_RANGE(xy1->bluey, xy2->bluey, delta))1630return 0;1631return 1;1632}16331634/* Added in libpng-1.6.0, a different check for the validity of a set of cHRM1635* chunk chromaticities. Earlier checks used to simply look for the overflow1636* condition (where the determinant of the matrix to solve for XYZ ends up zero1637* because the chromaticity values are not all distinct.) Despite this it is1638* theoretically possible to produce chromaticities that are apparently valid1639* but that rapidly degrade to invalid, potentially crashing, sets because of1640* arithmetic inaccuracies when calculations are performed on them. The new1641* check is to round-trip xy -> XYZ -> xy and then check that the result is1642* within a small percentage of the original.1643*/1644static int1645png_colorspace_check_xy(png_XYZ *XYZ, const png_xy *xy)1646{1647int result;1648png_xy xy_test;16491650/* As a side-effect this routine also returns the XYZ endpoints. */1651result = png_XYZ_from_xy(XYZ, xy);1652if (result != 0)1653return result;16541655result = png_xy_from_XYZ(&xy_test, XYZ);1656if (result != 0)1657return result;16581659if (png_colorspace_endpoints_match(xy, &xy_test,16605/*actually, the math is pretty accurate*/) != 0)1661return 0;16621663/* Too much slip */1664return 1;1665}16661667/* This is the check going the other way. The XYZ is modified to normalize it1668* (another side-effect) and the xy chromaticities are returned.1669*/1670static int1671png_colorspace_check_XYZ(png_xy *xy, png_XYZ *XYZ)1672{1673int result;1674png_XYZ XYZtemp;16751676result = png_XYZ_normalize(XYZ);1677if (result != 0)1678return result;16791680result = png_xy_from_XYZ(xy, XYZ);1681if (result != 0)1682return result;16831684XYZtemp = *XYZ;1685return png_colorspace_check_xy(&XYZtemp, xy);1686}16871688/* Used to check for an endpoint match against sRGB */1689static const png_xy sRGB_xy = /* From ITU-R BT.709-3 */1690{1691/* color x y */1692/* red */ 64000, 33000,1693/* green */ 30000, 60000,1694/* blue */ 15000, 6000,1695/* white */ 31270, 329001696};16971698static int1699png_colorspace_set_xy_and_XYZ(png_const_structrp png_ptr,1700png_colorspacerp colorspace, const png_xy *xy, const png_XYZ *XYZ,1701int preferred)1702{1703if ((colorspace->flags & PNG_COLORSPACE_INVALID) != 0)1704return 0;17051706/* The consistency check is performed on the chromaticities; this factors out1707* variations because of the normalization (or not) of the end point Y1708* values.1709*/1710if (preferred < 2 &&1711(colorspace->flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0)1712{1713/* The end points must be reasonably close to any we already have. The1714* following allows an error of up to +/-.0011715*/1716if (png_colorspace_endpoints_match(xy, &colorspace->end_points_xy,1717100) == 0)1718{1719colorspace->flags |= PNG_COLORSPACE_INVALID;1720png_benign_error(png_ptr, "inconsistent chromaticities");1721return 0; /* failed */1722}17231724/* Only overwrite with preferred values */1725if (preferred == 0)1726return 1; /* ok, but no change */1727}17281729colorspace->end_points_xy = *xy;1730colorspace->end_points_XYZ = *XYZ;1731colorspace->flags |= PNG_COLORSPACE_HAVE_ENDPOINTS;17321733/* The end points are normally quoted to two decimal digits, so allow +/-0.011734* on this test.1735*/1736if (png_colorspace_endpoints_match(xy, &sRGB_xy, 1000) != 0)1737colorspace->flags |= PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB;17381739else1740colorspace->flags &= PNG_COLORSPACE_CANCEL(1741PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB);17421743return 2; /* ok and changed */1744}17451746int /* PRIVATE */1747png_colorspace_set_chromaticities(png_const_structrp png_ptr,1748png_colorspacerp colorspace, const png_xy *xy, int preferred)1749{1750/* We must check the end points to ensure they are reasonable - in the past1751* color management systems have crashed as a result of getting bogus1752* colorant values, while this isn't the fault of libpng it is the1753* responsibility of libpng because PNG carries the bomb and libpng is in a1754* position to protect against it.1755*/1756png_XYZ XYZ;17571758switch (png_colorspace_check_xy(&XYZ, xy))1759{1760case 0: /* success */1761return png_colorspace_set_xy_and_XYZ(png_ptr, colorspace, xy, &XYZ,1762preferred);17631764case 1:1765/* We can't invert the chromaticities so we can't produce value XYZ1766* values. Likely as not a color management system will fail too.1767*/1768colorspace->flags |= PNG_COLORSPACE_INVALID;1769png_benign_error(png_ptr, "invalid chromaticities");1770break;17711772default:1773/* libpng is broken; this should be a warning but if it happens we1774* want error reports so for the moment it is an error.1775*/1776colorspace->flags |= PNG_COLORSPACE_INVALID;1777png_error(png_ptr, "internal error checking chromaticities");1778}17791780return 0; /* failed */1781}17821783int /* PRIVATE */1784png_colorspace_set_endpoints(png_const_structrp png_ptr,1785png_colorspacerp colorspace, const png_XYZ *XYZ_in, int preferred)1786{1787png_XYZ XYZ = *XYZ_in;1788png_xy xy;17891790switch (png_colorspace_check_XYZ(&xy, &XYZ))1791{1792case 0:1793return png_colorspace_set_xy_and_XYZ(png_ptr, colorspace, &xy, &XYZ,1794preferred);17951796case 1:1797/* End points are invalid. */1798colorspace->flags |= PNG_COLORSPACE_INVALID;1799png_benign_error(png_ptr, "invalid end points");1800break;18011802default:1803colorspace->flags |= PNG_COLORSPACE_INVALID;1804png_error(png_ptr, "internal error checking chromaticities");1805}18061807return 0; /* failed */1808}18091810#if defined(PNG_sRGB_SUPPORTED) || defined(PNG_iCCP_SUPPORTED)1811/* Error message generation */1812static char1813png_icc_tag_char(png_uint_32 byte)1814{1815byte &= 0xff;1816if (byte >= 32 && byte <= 126)1817return (char)byte;1818else1819return '?';1820}18211822static void1823png_icc_tag_name(char *name, png_uint_32 tag)1824{1825name[0] = '\'';1826name[1] = png_icc_tag_char(tag >> 24);1827name[2] = png_icc_tag_char(tag >> 16);1828name[3] = png_icc_tag_char(tag >> 8);1829name[4] = png_icc_tag_char(tag );1830name[5] = '\'';1831}18321833static int1834is_ICC_signature_char(png_alloc_size_t it)1835{1836return it == 32 || (it >= 48 && it <= 57) || (it >= 65 && it <= 90) ||1837(it >= 97 && it <= 122);1838}18391840static int1841is_ICC_signature(png_alloc_size_t it)1842{1843return is_ICC_signature_char(it >> 24) /* checks all the top bits */ &&1844is_ICC_signature_char((it >> 16) & 0xff) &&1845is_ICC_signature_char((it >> 8) & 0xff) &&1846is_ICC_signature_char(it & 0xff);1847}18481849static int1850png_icc_profile_error(png_const_structrp png_ptr, png_colorspacerp colorspace,1851png_const_charp name, png_alloc_size_t value, png_const_charp reason)1852{1853size_t pos;1854char message[196]; /* see below for calculation */18551856if (colorspace != NULL)1857colorspace->flags |= PNG_COLORSPACE_INVALID;18581859pos = png_safecat(message, (sizeof message), 0, "profile '"); /* 9 chars */1860pos = png_safecat(message, pos+79, pos, name); /* Truncate to 79 chars */1861pos = png_safecat(message, (sizeof message), pos, "': "); /* +2 = 90 */1862if (is_ICC_signature(value) != 0)1863{1864/* So 'value' is at most 4 bytes and the following cast is safe */1865png_icc_tag_name(message+pos, (png_uint_32)value);1866pos += 6; /* total +8; less than the else clause */1867message[pos++] = ':';1868message[pos++] = ' ';1869}1870# ifdef PNG_WARNINGS_SUPPORTED1871else1872{1873char number[PNG_NUMBER_BUFFER_SIZE]; /* +24 = 114*/18741875pos = png_safecat(message, (sizeof message), pos,1876png_format_number(number, number+(sizeof number),1877PNG_NUMBER_FORMAT_x, value));1878pos = png_safecat(message, (sizeof message), pos, "h: "); /*+2 = 116*/1879}1880# endif1881/* The 'reason' is an arbitrary message, allow +79 maximum 195 */1882pos = png_safecat(message, (sizeof message), pos, reason);1883PNG_UNUSED(pos)18841885/* This is recoverable, but make it unconditionally an app_error on write to1886* avoid writing invalid ICC profiles into PNG files (i.e., we handle them1887* on read, with a warning, but on write unless the app turns off1888* application errors the PNG won't be written.)1889*/1890png_chunk_report(png_ptr, message,1891(colorspace != NULL) ? PNG_CHUNK_ERROR : PNG_CHUNK_WRITE_ERROR);18921893return 0;1894}1895#endif /* sRGB || iCCP */18961897#ifdef PNG_sRGB_SUPPORTED1898int /* PRIVATE */1899png_colorspace_set_sRGB(png_const_structrp png_ptr, png_colorspacerp colorspace,1900int intent)1901{1902/* sRGB sets known gamma, end points and (from the chunk) intent. */1903/* IMPORTANT: these are not necessarily the values found in an ICC profile1904* because ICC profiles store values adapted to a D50 environment; it is1905* expected that the ICC profile mediaWhitePointTag will be D50; see the1906* checks and code elsewhere to understand this better.1907*1908* These XYZ values, which are accurate to 5dp, produce rgb to gray1909* coefficients of (6968,23435,2366), which are reduced (because they add up1910* to 32769 not 32768) to (6968,23434,2366). These are the values that1911* libpng has traditionally used (and are the best values given the 15bit1912* algorithm used by the rgb to gray code.)1913*/1914static const png_XYZ sRGB_XYZ = /* D65 XYZ (*not* the D50 adapted values!) */1915{1916/* color X Y Z */1917/* red */ 41239, 21264, 1933,1918/* green */ 35758, 71517, 11919,1919/* blue */ 18048, 7219, 950531920};19211922/* Do nothing if the colorspace is already invalidated. */1923if ((colorspace->flags & PNG_COLORSPACE_INVALID) != 0)1924return 0;19251926/* Check the intent, then check for existing settings. It is valid for the1927* PNG file to have cHRM or gAMA chunks along with sRGB, but the values must1928* be consistent with the correct values. If, however, this function is1929* called below because an iCCP chunk matches sRGB then it is quite1930* conceivable that an older app recorded incorrect gAMA and cHRM because of1931* an incorrect calculation based on the values in the profile - this does1932* *not* invalidate the profile (though it still produces an error, which can1933* be ignored.)1934*/1935if (intent < 0 || intent >= PNG_sRGB_INTENT_LAST)1936return png_icc_profile_error(png_ptr, colorspace, "sRGB",1937(png_alloc_size_t)intent, "invalid sRGB rendering intent");19381939if ((colorspace->flags & PNG_COLORSPACE_HAVE_INTENT) != 0 &&1940colorspace->rendering_intent != intent)1941return png_icc_profile_error(png_ptr, colorspace, "sRGB",1942(png_alloc_size_t)intent, "inconsistent rendering intents");19431944if ((colorspace->flags & PNG_COLORSPACE_FROM_sRGB) != 0)1945{1946png_benign_error(png_ptr, "duplicate sRGB information ignored");1947return 0;1948}19491950/* If the standard sRGB cHRM chunk does not match the one from the PNG file1951* warn but overwrite the value with the correct one.1952*/1953if ((colorspace->flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0 &&1954!png_colorspace_endpoints_match(&sRGB_xy, &colorspace->end_points_xy,1955100))1956png_chunk_report(png_ptr, "cHRM chunk does not match sRGB",1957PNG_CHUNK_ERROR);19581959/* This check is just done for the error reporting - the routine always1960* returns true when the 'from' argument corresponds to sRGB (2).1961*/1962(void)png_colorspace_check_gamma(png_ptr, colorspace, PNG_GAMMA_sRGB_INVERSE,19632/*from sRGB*/);19641965/* intent: bugs in GCC force 'int' to be used as the parameter type. */1966colorspace->rendering_intent = (png_uint_16)intent;1967colorspace->flags |= PNG_COLORSPACE_HAVE_INTENT;19681969/* endpoints */1970colorspace->end_points_xy = sRGB_xy;1971colorspace->end_points_XYZ = sRGB_XYZ;1972colorspace->flags |=1973(PNG_COLORSPACE_HAVE_ENDPOINTS|PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB);19741975/* gamma */1976colorspace->gamma = PNG_GAMMA_sRGB_INVERSE;1977colorspace->flags |= PNG_COLORSPACE_HAVE_GAMMA;19781979/* Finally record that we have an sRGB profile */1980colorspace->flags |=1981(PNG_COLORSPACE_MATCHES_sRGB|PNG_COLORSPACE_FROM_sRGB);19821983return 1; /* set */1984}1985#endif /* sRGB */19861987#ifdef PNG_iCCP_SUPPORTED1988/* Encoded value of D50 as an ICC XYZNumber. From the ICC 2010 spec the value1989* is XYZ(0.9642,1.0,0.8249), which scales to:1990*1991* (63189.8112, 65536, 54060.6464)1992*/1993static const png_byte D50_nCIEXYZ[12] =1994{ 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d };19951996static int /* bool */1997icc_check_length(png_const_structrp png_ptr, png_colorspacerp colorspace,1998png_const_charp name, png_uint_32 profile_length)1999{2000if (profile_length < 132)2001return png_icc_profile_error(png_ptr, colorspace, name, profile_length,2002"too short");2003return 1;2004}20052006#ifdef PNG_READ_iCCP_SUPPORTED2007int /* PRIVATE */2008png_icc_check_length(png_const_structrp png_ptr, png_colorspacerp colorspace,2009png_const_charp name, png_uint_32 profile_length)2010{2011if (!icc_check_length(png_ptr, colorspace, name, profile_length))2012return 0;20132014/* This needs to be here because the 'normal' check is in2015* png_decompress_chunk, yet this happens after the attempt to2016* png_malloc_base the required data. We only need this on read; on write2017* the caller supplies the profile buffer so libpng doesn't allocate it. See2018* the call to icc_check_length below (the write case).2019*/2020# ifdef PNG_SET_USER_LIMITS_SUPPORTED2021else if (png_ptr->user_chunk_malloc_max > 0 &&2022png_ptr->user_chunk_malloc_max < profile_length)2023return png_icc_profile_error(png_ptr, colorspace, name, profile_length,2024"exceeds application limits");2025# elif PNG_USER_CHUNK_MALLOC_MAX > 02026else if (PNG_USER_CHUNK_MALLOC_MAX < profile_length)2027return png_icc_profile_error(png_ptr, colorspace, name, profile_length,2028"exceeds libpng limits");2029# else /* !SET_USER_LIMITS */2030/* This will get compiled out on all 32-bit and better systems. */2031else if (PNG_SIZE_MAX < profile_length)2032return png_icc_profile_error(png_ptr, colorspace, name, profile_length,2033"exceeds system limits");2034# endif /* !SET_USER_LIMITS */20352036return 1;2037}2038#endif /* READ_iCCP */20392040int /* PRIVATE */2041png_icc_check_header(png_const_structrp png_ptr, png_colorspacerp colorspace,2042png_const_charp name, png_uint_32 profile_length,2043png_const_bytep profile/* first 132 bytes only */, int color_type)2044{2045png_uint_32 temp;20462047/* Length check; this cannot be ignored in this code because profile_length2048* is used later to check the tag table, so even if the profile seems over2049* long profile_length from the caller must be correct. The caller can fix2050* this up on read or write by just passing in the profile header length.2051*/2052temp = png_get_uint_32(profile);2053if (temp != profile_length)2054return png_icc_profile_error(png_ptr, colorspace, name, temp,2055"length does not match profile");20562057temp = (png_uint_32) (*(profile+8));2058if (temp > 3 && (profile_length & 3))2059return png_icc_profile_error(png_ptr, colorspace, name, profile_length,2060"invalid length");20612062temp = png_get_uint_32(profile+128); /* tag count: 12 bytes/tag */2063if (temp > 357913930 || /* (2^32-4-132)/12: maximum possible tag count */2064profile_length < 132+12*temp) /* truncated tag table */2065return png_icc_profile_error(png_ptr, colorspace, name, temp,2066"tag count too large");20672068/* The 'intent' must be valid or we can't store it, ICC limits the intent to2069* 16 bits.2070*/2071temp = png_get_uint_32(profile+64);2072if (temp >= 0xffff) /* The ICC limit */2073return png_icc_profile_error(png_ptr, colorspace, name, temp,2074"invalid rendering intent");20752076/* This is just a warning because the profile may be valid in future2077* versions.2078*/2079if (temp >= PNG_sRGB_INTENT_LAST)2080(void)png_icc_profile_error(png_ptr, NULL, name, temp,2081"intent outside defined range");20822083/* At this point the tag table can't be checked because it hasn't necessarily2084* been loaded; however, various header fields can be checked. These checks2085* are for values permitted by the PNG spec in an ICC profile; the PNG spec2086* restricts the profiles that can be passed in an iCCP chunk (they must be2087* appropriate to processing PNG data!)2088*/20892090/* Data checks (could be skipped). These checks must be independent of the2091* version number; however, the version number doesn't accommodate changes in2092* the header fields (just the known tags and the interpretation of the2093* data.)2094*/2095temp = png_get_uint_32(profile+36); /* signature 'ascp' */2096if (temp != 0x61637370)2097return png_icc_profile_error(png_ptr, colorspace, name, temp,2098"invalid signature");20992100/* Currently the PCS illuminant/adopted white point (the computational2101* white point) are required to be D50,2102* however the profile contains a record of the illuminant so perhaps ICC2103* expects to be able to change this in the future (despite the rationale in2104* the introduction for using a fixed PCS adopted white.) Consequently the2105* following is just a warning.2106*/2107if (memcmp(profile+68, D50_nCIEXYZ, 12) != 0)2108(void)png_icc_profile_error(png_ptr, NULL, name, 0/*no tag value*/,2109"PCS illuminant is not D50");21102111/* The PNG spec requires this:2112* "If the iCCP chunk is present, the image samples conform to the colour2113* space represented by the embedded ICC profile as defined by the2114* International Color Consortium [ICC]. The colour space of the ICC profile2115* shall be an RGB colour space for colour images (PNG colour types 2, 3, and2116* 6), or a greyscale colour space for greyscale images (PNG colour types 02117* and 4)."2118*2119* This checking code ensures the embedded profile (on either read or write)2120* conforms to the specification requirements. Notice that an ICC 'gray'2121* color-space profile contains the information to transform the monochrome2122* data to XYZ or L*a*b (according to which PCS the profile uses) and this2123* should be used in preference to the standard libpng K channel replication2124* into R, G and B channels.2125*2126* Previously it was suggested that an RGB profile on grayscale data could be2127* handled. However it it is clear that using an RGB profile in this context2128* must be an error - there is no specification of what it means. Thus it is2129* almost certainly more correct to ignore the profile.2130*/2131temp = png_get_uint_32(profile+16); /* data colour space field */2132switch (temp)2133{2134case 0x52474220: /* 'RGB ' */2135if ((color_type & PNG_COLOR_MASK_COLOR) == 0)2136return png_icc_profile_error(png_ptr, colorspace, name, temp,2137"RGB color space not permitted on grayscale PNG");2138break;21392140case 0x47524159: /* 'GRAY' */2141if ((color_type & PNG_COLOR_MASK_COLOR) != 0)2142return png_icc_profile_error(png_ptr, colorspace, name, temp,2143"Gray color space not permitted on RGB PNG");2144break;21452146default:2147return png_icc_profile_error(png_ptr, colorspace, name, temp,2148"invalid ICC profile color space");2149}21502151/* It is up to the application to check that the profile class matches the2152* application requirements; the spec provides no guidance, but it's pretty2153* weird if the profile is not scanner ('scnr'), monitor ('mntr'), printer2154* ('prtr') or 'spac' (for generic color spaces). Issue a warning in these2155* cases. Issue an error for device link or abstract profiles - these don't2156* contain the records necessary to transform the color-space to anything2157* other than the target device (and not even that for an abstract profile).2158* Profiles of these classes may not be embedded in images.2159*/2160temp = png_get_uint_32(profile+12); /* profile/device class */2161switch (temp)2162{2163case 0x73636e72: /* 'scnr' */2164case 0x6d6e7472: /* 'mntr' */2165case 0x70727472: /* 'prtr' */2166case 0x73706163: /* 'spac' */2167/* All supported */2168break;21692170case 0x61627374: /* 'abst' */2171/* May not be embedded in an image */2172return png_icc_profile_error(png_ptr, colorspace, name, temp,2173"invalid embedded Abstract ICC profile");21742175case 0x6c696e6b: /* 'link' */2176/* DeviceLink profiles cannot be interpreted in a non-device specific2177* fashion, if an app uses the AToB0Tag in the profile the results are2178* undefined unless the result is sent to the intended device,2179* therefore a DeviceLink profile should not be found embedded in a2180* PNG.2181*/2182return png_icc_profile_error(png_ptr, colorspace, name, temp,2183"unexpected DeviceLink ICC profile class");21842185case 0x6e6d636c: /* 'nmcl' */2186/* A NamedColor profile is also device specific, however it doesn't2187* contain an AToB0 tag that is open to misinterpretation. Almost2188* certainly it will fail the tests below.2189*/2190(void)png_icc_profile_error(png_ptr, NULL, name, temp,2191"unexpected NamedColor ICC profile class");2192break;21932194default:2195/* To allow for future enhancements to the profile accept unrecognized2196* profile classes with a warning, these then hit the test below on the2197* tag content to ensure they are backward compatible with one of the2198* understood profiles.2199*/2200(void)png_icc_profile_error(png_ptr, NULL, name, temp,2201"unrecognized ICC profile class");2202break;2203}22042205/* For any profile other than a device link one the PCS must be encoded2206* either in XYZ or Lab.2207*/2208temp = png_get_uint_32(profile+20);2209switch (temp)2210{2211case 0x58595a20: /* 'XYZ ' */2212case 0x4c616220: /* 'Lab ' */2213break;22142215default:2216return png_icc_profile_error(png_ptr, colorspace, name, temp,2217"unexpected ICC PCS encoding");2218}22192220return 1;2221}22222223int /* PRIVATE */2224png_icc_check_tag_table(png_const_structrp png_ptr, png_colorspacerp colorspace,2225png_const_charp name, png_uint_32 profile_length,2226png_const_bytep profile /* header plus whole tag table */)2227{2228png_uint_32 tag_count = png_get_uint_32(profile+128);2229png_uint_32 itag;2230png_const_bytep tag = profile+132; /* The first tag */22312232/* First scan all the tags in the table and add bits to the icc_info value2233* (temporarily in 'tags').2234*/2235for (itag=0; itag < tag_count; ++itag, tag += 12)2236{2237png_uint_32 tag_id = png_get_uint_32(tag+0);2238png_uint_32 tag_start = png_get_uint_32(tag+4); /* must be aligned */2239png_uint_32 tag_length = png_get_uint_32(tag+8);/* not padded */22402241/* The ICC specification does not exclude zero length tags, therefore the2242* start might actually be anywhere if there is no data, but this would be2243* a clear abuse of the intent of the standard so the start is checked for2244* being in range. All defined tag types have an 8 byte header - a 4 byte2245* type signature then 0.2246*/22472248/* This is a hard error; potentially it can cause read outside the2249* profile.2250*/2251if (tag_start > profile_length || tag_length > profile_length - tag_start)2252return png_icc_profile_error(png_ptr, colorspace, name, tag_id,2253"ICC profile tag outside profile");22542255if ((tag_start & 3) != 0)2256{2257/* CNHP730S.icc shipped with Microsoft Windows 64 violates this; it is2258* only a warning here because libpng does not care about the2259* alignment.2260*/2261(void)png_icc_profile_error(png_ptr, NULL, name, tag_id,2262"ICC profile tag start not a multiple of 4");2263}2264}22652266return 1; /* success, maybe with warnings */2267}22682269#ifdef PNG_sRGB_SUPPORTED2270#if PNG_sRGB_PROFILE_CHECKS >= 02271/* Information about the known ICC sRGB profiles */2272static const struct2273{2274png_uint_32 adler, crc, length;2275png_uint_32 md5[4];2276png_byte have_md5;2277png_byte is_broken;2278png_uint_16 intent;22792280# define PNG_MD5(a,b,c,d) { a, b, c, d }, (a!=0)||(b!=0)||(c!=0)||(d!=0)2281# define PNG_ICC_CHECKSUM(adler, crc, md5, intent, broke, date, length, fname)\2282{ adler, crc, length, md5, broke, intent },22832284} png_sRGB_checks[] =2285{2286/* This data comes from contrib/tools/checksum-icc run on downloads of2287* all four ICC sRGB profiles from www.color.org.2288*/2289/* adler32, crc32, MD5[4], intent, date, length, file-name */2290PNG_ICC_CHECKSUM(0x0a3fd9f6, 0x3b8772b9,2291PNG_MD5(0x29f83dde, 0xaff255ae, 0x7842fae4, 0xca83390d), 0, 0,2292"2009/03/27 21:36:31", 3048, "sRGB_IEC61966-2-1_black_scaled.icc")22932294/* ICC sRGB v2 perceptual no black-compensation: */2295PNG_ICC_CHECKSUM(0x4909e5e1, 0x427ebb21,2296PNG_MD5(0xc95bd637, 0xe95d8a3b, 0x0df38f99, 0xc1320389), 1, 0,2297"2009/03/27 21:37:45", 3052, "sRGB_IEC61966-2-1_no_black_scaling.icc")22982299PNG_ICC_CHECKSUM(0xfd2144a1, 0x306fd8ae,2300PNG_MD5(0xfc663378, 0x37e2886b, 0xfd72e983, 0x8228f1b8), 0, 0,2301"2009/08/10 17:28:01", 60988, "sRGB_v4_ICC_preference_displayclass.icc")23022303/* ICC sRGB v4 perceptual */2304PNG_ICC_CHECKSUM(0x209c35d2, 0xbbef7812,2305PNG_MD5(0x34562abf, 0x994ccd06, 0x6d2c5721, 0xd0d68c5d), 0, 0,2306"2007/07/25 00:05:37", 60960, "sRGB_v4_ICC_preference.icc")23072308/* The following profiles have no known MD5 checksum. If there is a match2309* on the (empty) MD5 the other fields are used to attempt a match and2310* a warning is produced. The first two of these profiles have a 'cprt' tag2311* which suggests that they were also made by Hewlett Packard.2312*/2313PNG_ICC_CHECKSUM(0xa054d762, 0x5d5129ce,2314PNG_MD5(0x00000000, 0x00000000, 0x00000000, 0x00000000), 1, 0,2315"2004/07/21 18:57:42", 3024, "sRGB_IEC61966-2-1_noBPC.icc")23162317/* This is a 'mntr' (display) profile with a mediaWhitePointTag that does not2318* match the D50 PCS illuminant in the header (it is in fact the D65 values,2319* so the white point is recorded as the un-adapted value.) The profiles2320* below only differ in one byte - the intent - and are basically the same as2321* the previous profile except for the mediaWhitePointTag error and a missing2322* chromaticAdaptationTag.2323*/2324PNG_ICC_CHECKSUM(0xf784f3fb, 0x182ea552,2325PNG_MD5(0x00000000, 0x00000000, 0x00000000, 0x00000000), 0, 1/*broken*/,2326"1998/02/09 06:49:00", 3144, "HP-Microsoft sRGB v2 perceptual")23272328PNG_ICC_CHECKSUM(0x0398f3fc, 0xf29e526d,2329PNG_MD5(0x00000000, 0x00000000, 0x00000000, 0x00000000), 1, 1/*broken*/,2330"1998/02/09 06:49:00", 3144, "HP-Microsoft sRGB v2 media-relative")2331};23322333static int2334png_compare_ICC_profile_with_sRGB(png_const_structrp png_ptr,2335png_const_bytep profile, uLong adler)2336{2337/* The quick check is to verify just the MD5 signature and trust the2338* rest of the data. Because the profile has already been verified for2339* correctness this is safe. png_colorspace_set_sRGB will check the 'intent'2340* field too, so if the profile has been edited with an intent not defined2341* by sRGB (but maybe defined by a later ICC specification) the read of2342* the profile will fail at that point.2343*/23442345png_uint_32 length = 0;2346png_uint_32 intent = 0x10000; /* invalid */2347#if PNG_sRGB_PROFILE_CHECKS > 12348uLong crc = 0; /* the value for 0 length data */2349#endif2350unsigned int i;23512352#ifdef PNG_SET_OPTION_SUPPORTED2353/* First see if PNG_SKIP_sRGB_CHECK_PROFILE has been set to "on" */2354if (((png_ptr->options >> PNG_SKIP_sRGB_CHECK_PROFILE) & 3) ==2355PNG_OPTION_ON)2356return 0;2357#endif23582359for (i=0; i < (sizeof png_sRGB_checks) / (sizeof png_sRGB_checks[0]); ++i)2360{2361if (png_get_uint_32(profile+84) == png_sRGB_checks[i].md5[0] &&2362png_get_uint_32(profile+88) == png_sRGB_checks[i].md5[1] &&2363png_get_uint_32(profile+92) == png_sRGB_checks[i].md5[2] &&2364png_get_uint_32(profile+96) == png_sRGB_checks[i].md5[3])2365{2366/* This may be one of the old HP profiles without an MD5, in that2367* case we can only use the length and Adler32 (note that these2368* are not used by default if there is an MD5!)2369*/2370# if PNG_sRGB_PROFILE_CHECKS == 02371if (png_sRGB_checks[i].have_md5 != 0)2372return 1+png_sRGB_checks[i].is_broken;2373# endif23742375/* Profile is unsigned or more checks have been configured in. */2376if (length == 0)2377{2378length = png_get_uint_32(profile);2379intent = png_get_uint_32(profile+64);2380}23812382/* Length *and* intent must match */2383if (length == (png_uint_32) png_sRGB_checks[i].length &&2384intent == (png_uint_32) png_sRGB_checks[i].intent)2385{2386/* Now calculate the adler32 if not done already. */2387if (adler == 0)2388{2389adler = adler32(0, NULL, 0);2390adler = adler32(adler, profile, length);2391}23922393if (adler == png_sRGB_checks[i].adler)2394{2395/* These basic checks suggest that the data has not been2396* modified, but if the check level is more than 1 perform2397* our own crc32 checksum on the data.2398*/2399# if PNG_sRGB_PROFILE_CHECKS > 12400if (crc == 0)2401{2402crc = crc32(0, NULL, 0);2403crc = crc32(crc, profile, length);2404}24052406/* So this check must pass for the 'return' below to happen.2407*/2408if (crc == png_sRGB_checks[i].crc)2409# endif2410{2411if (png_sRGB_checks[i].is_broken != 0)2412{2413/* These profiles are known to have bad data that may cause2414* problems if they are used, therefore attempt to2415* discourage their use, skip the 'have_md5' warning below,2416* which is made irrelevant by this error.2417*/2418png_chunk_report(png_ptr, "known incorrect sRGB profile",2419PNG_CHUNK_ERROR);2420}24212422/* Warn that this being done; this isn't even an error since2423* the profile is perfectly valid, but it would be nice if2424* people used the up-to-date ones.2425*/2426else if (png_sRGB_checks[i].have_md5 == 0)2427{2428png_chunk_report(png_ptr,2429"out-of-date sRGB profile with no signature",2430PNG_CHUNK_WARNING);2431}24322433return 1+png_sRGB_checks[i].is_broken;2434}2435}24362437# if PNG_sRGB_PROFILE_CHECKS > 02438/* The signature matched, but the profile had been changed in some2439* way. This probably indicates a data error or uninformed hacking.2440* Fall through to "no match".2441*/2442png_chunk_report(png_ptr,2443"Not recognizing known sRGB profile that has been edited",2444PNG_CHUNK_WARNING);2445break;2446# endif2447}2448}2449}24502451return 0; /* no match */2452}24532454void /* PRIVATE */2455png_icc_set_sRGB(png_const_structrp png_ptr,2456png_colorspacerp colorspace, png_const_bytep profile, uLong adler)2457{2458/* Is this profile one of the known ICC sRGB profiles? If it is, just set2459* the sRGB information.2460*/2461if (png_compare_ICC_profile_with_sRGB(png_ptr, profile, adler) != 0)2462(void)png_colorspace_set_sRGB(png_ptr, colorspace,2463(int)/*already checked*/png_get_uint_32(profile+64));2464}2465#endif /* PNG_sRGB_PROFILE_CHECKS >= 0 */2466#endif /* sRGB */24672468int /* PRIVATE */2469png_colorspace_set_ICC(png_const_structrp png_ptr, png_colorspacerp colorspace,2470png_const_charp name, png_uint_32 profile_length, png_const_bytep profile,2471int color_type)2472{2473if ((colorspace->flags & PNG_COLORSPACE_INVALID) != 0)2474return 0;24752476if (icc_check_length(png_ptr, colorspace, name, profile_length) != 0 &&2477png_icc_check_header(png_ptr, colorspace, name, profile_length, profile,2478color_type) != 0 &&2479png_icc_check_tag_table(png_ptr, colorspace, name, profile_length,2480profile) != 0)2481{2482# if defined(PNG_sRGB_SUPPORTED) && PNG_sRGB_PROFILE_CHECKS >= 02483/* If no sRGB support, don't try storing sRGB information */2484png_icc_set_sRGB(png_ptr, colorspace, profile, 0);2485# endif2486return 1;2487}24882489/* Failure case */2490return 0;2491}2492#endif /* iCCP */24932494#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED2495void /* PRIVATE */2496png_colorspace_set_rgb_coefficients(png_structrp png_ptr)2497{2498/* Set the rgb_to_gray coefficients from the colorspace. */2499if (png_ptr->rgb_to_gray_coefficients_set == 0 &&2500(png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0)2501{2502/* png_set_background has not been called, get the coefficients from the Y2503* values of the colorspace colorants.2504*/2505png_fixed_point r = png_ptr->colorspace.end_points_XYZ.red_Y;2506png_fixed_point g = png_ptr->colorspace.end_points_XYZ.green_Y;2507png_fixed_point b = png_ptr->colorspace.end_points_XYZ.blue_Y;2508png_fixed_point total = r+g+b;25092510if (total > 0 &&2511r >= 0 && png_muldiv(&r, r, 32768, total) && r >= 0 && r <= 32768 &&2512g >= 0 && png_muldiv(&g, g, 32768, total) && g >= 0 && g <= 32768 &&2513b >= 0 && png_muldiv(&b, b, 32768, total) && b >= 0 && b <= 32768 &&2514r+g+b <= 32769)2515{2516/* We allow 0 coefficients here. r+g+b may be 32769 if two or2517* all of the coefficients were rounded up. Handle this by2518* reducing the *largest* coefficient by 1; this matches the2519* approach used for the default coefficients in pngrtran.c2520*/2521int add = 0;25222523if (r+g+b > 32768)2524add = -1;2525else if (r+g+b < 32768)2526add = 1;25272528if (add != 0)2529{2530if (g >= r && g >= b)2531g += add;2532else if (r >= g && r >= b)2533r += add;2534else2535b += add;2536}25372538/* Check for an internal error. */2539if (r+g+b != 32768)2540png_error(png_ptr,2541"internal error handling cHRM coefficients");25422543else2544{2545png_ptr->rgb_to_gray_red_coeff = (png_uint_16)r;2546png_ptr->rgb_to_gray_green_coeff = (png_uint_16)g;2547}2548}25492550/* This is a png_error at present even though it could be ignored -2551* it should never happen, but it is important that if it does, the2552* bug is fixed.2553*/2554else2555png_error(png_ptr, "internal error handling cHRM->XYZ");2556}2557}2558#endif /* READ_RGB_TO_GRAY */25592560#endif /* COLORSPACE */25612562#ifdef __GNUC__2563/* This exists solely to work round a warning from GNU C. */2564static int /* PRIVATE */2565png_gt(size_t a, size_t b)2566{2567return a > b;2568}2569#else2570# define png_gt(a,b) ((a) > (b))2571#endif25722573void /* PRIVATE */2574png_check_IHDR(png_const_structrp png_ptr,2575png_uint_32 width, png_uint_32 height, int bit_depth,2576int color_type, int interlace_type, int compression_type,2577int filter_type)2578{2579int error = 0;25802581/* Check for width and height valid values */2582if (width == 0)2583{2584png_warning(png_ptr, "Image width is zero in IHDR");2585error = 1;2586}25872588if (width > PNG_UINT_31_MAX)2589{2590png_warning(png_ptr, "Invalid image width in IHDR");2591error = 1;2592}25932594if (png_gt(((width + 7) & (~7U)),2595((PNG_SIZE_MAX2596- 48 /* big_row_buf hack */2597- 1) /* filter byte */2598/ 8) /* 8-byte RGBA pixels */2599- 1)) /* extra max_pixel_depth pad */2600{2601/* The size of the row must be within the limits of this architecture.2602* Because the read code can perform arbitrary transformations the2603* maximum size is checked here. Because the code in png_read_start_row2604* adds extra space "for safety's sake" in several places a conservative2605* limit is used here.2606*2607* NOTE: it would be far better to check the size that is actually used,2608* but the effect in the real world is minor and the changes are more2609* extensive, therefore much more dangerous and much more difficult to2610* write in a way that avoids compiler warnings.2611*/2612png_warning(png_ptr, "Image width is too large for this architecture");2613error = 1;2614}26152616#ifdef PNG_SET_USER_LIMITS_SUPPORTED2617if (width > png_ptr->user_width_max)2618#else2619if (width > PNG_USER_WIDTH_MAX)2620#endif2621{2622png_warning(png_ptr, "Image width exceeds user limit in IHDR");2623error = 1;2624}26252626if (height == 0)2627{2628png_warning(png_ptr, "Image height is zero in IHDR");2629error = 1;2630}26312632if (height > PNG_UINT_31_MAX)2633{2634png_warning(png_ptr, "Invalid image height in IHDR");2635error = 1;2636}26372638#ifdef PNG_SET_USER_LIMITS_SUPPORTED2639if (height > png_ptr->user_height_max)2640#else2641if (height > PNG_USER_HEIGHT_MAX)2642#endif2643{2644png_warning(png_ptr, "Image height exceeds user limit in IHDR");2645error = 1;2646}26472648/* Check other values */2649if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&2650bit_depth != 8 && bit_depth != 16)2651{2652png_warning(png_ptr, "Invalid bit depth in IHDR");2653error = 1;2654}26552656if (color_type < 0 || color_type == 1 ||2657color_type == 5 || color_type > 6)2658{2659png_warning(png_ptr, "Invalid color type in IHDR");2660error = 1;2661}26622663if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||2664((color_type == PNG_COLOR_TYPE_RGB ||2665color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||2666color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))2667{2668png_warning(png_ptr, "Invalid color type/bit depth combination in IHDR");2669error = 1;2670}26712672if (interlace_type >= PNG_INTERLACE_LAST)2673{2674png_warning(png_ptr, "Unknown interlace method in IHDR");2675error = 1;2676}26772678if (compression_type != PNG_COMPRESSION_TYPE_BASE)2679{2680png_warning(png_ptr, "Unknown compression method in IHDR");2681error = 1;2682}26832684#ifdef PNG_MNG_FEATURES_SUPPORTED2685/* Accept filter_method 64 (intrapixel differencing) only if2686* 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and2687* 2. Libpng did not read a PNG signature (this filter_method is only2688* used in PNG datastreams that are embedded in MNG datastreams) and2689* 3. The application called png_permit_mng_features with a mask that2690* included PNG_FLAG_MNG_FILTER_64 and2691* 4. The filter_method is 64 and2692* 5. The color_type is RGB or RGBA2693*/2694if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 &&2695png_ptr->mng_features_permitted != 0)2696png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");26972698if (filter_type != PNG_FILTER_TYPE_BASE)2699{2700if (!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&2701(filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&2702((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) == 0) &&2703(color_type == PNG_COLOR_TYPE_RGB ||2704color_type == PNG_COLOR_TYPE_RGB_ALPHA)))2705{2706png_warning(png_ptr, "Unknown filter method in IHDR");2707error = 1;2708}27092710if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0)2711{2712png_warning(png_ptr, "Invalid filter method in IHDR");2713error = 1;2714}2715}27162717#else2718if (filter_type != PNG_FILTER_TYPE_BASE)2719{2720png_warning(png_ptr, "Unknown filter method in IHDR");2721error = 1;2722}2723#endif27242725if (error == 1)2726png_error(png_ptr, "Invalid IHDR data");2727}27282729#if defined(PNG_sCAL_SUPPORTED) || defined(PNG_pCAL_SUPPORTED)2730/* ASCII to fp functions */2731/* Check an ASCII formatted floating point value, see the more detailed2732* comments in pngpriv.h2733*/2734/* The following is used internally to preserve the sticky flags */2735#define png_fp_add(state, flags) ((state) |= (flags))2736#define png_fp_set(state, value) ((state) = (value) | ((state) & PNG_FP_STICKY))27372738int /* PRIVATE */2739png_check_fp_number(png_const_charp string, size_t size, int *statep,2740png_size_tp whereami)2741{2742int state = *statep;2743size_t i = *whereami;27442745while (i < size)2746{2747int type;2748/* First find the type of the next character */2749switch (string[i])2750{2751case 43: type = PNG_FP_SAW_SIGN; break;2752case 45: type = PNG_FP_SAW_SIGN + PNG_FP_NEGATIVE; break;2753case 46: type = PNG_FP_SAW_DOT; break;2754case 48: type = PNG_FP_SAW_DIGIT; break;2755case 49: case 50: case 51: case 52:2756case 53: case 54: case 55: case 56:2757case 57: type = PNG_FP_SAW_DIGIT + PNG_FP_NONZERO; break;2758case 69:2759case 101: type = PNG_FP_SAW_E; break;2760default: goto PNG_FP_End;2761}27622763/* Now deal with this type according to the current2764* state, the type is arranged to not overlap the2765* bits of the PNG_FP_STATE.2766*/2767switch ((state & PNG_FP_STATE) + (type & PNG_FP_SAW_ANY))2768{2769case PNG_FP_INTEGER + PNG_FP_SAW_SIGN:2770if ((state & PNG_FP_SAW_ANY) != 0)2771goto PNG_FP_End; /* not a part of the number */27722773png_fp_add(state, type);2774break;27752776case PNG_FP_INTEGER + PNG_FP_SAW_DOT:2777/* Ok as trailer, ok as lead of fraction. */2778if ((state & PNG_FP_SAW_DOT) != 0) /* two dots */2779goto PNG_FP_End;27802781else if ((state & PNG_FP_SAW_DIGIT) != 0) /* trailing dot? */2782png_fp_add(state, type);27832784else2785png_fp_set(state, PNG_FP_FRACTION | type);27862787break;27882789case PNG_FP_INTEGER + PNG_FP_SAW_DIGIT:2790if ((state & PNG_FP_SAW_DOT) != 0) /* delayed fraction */2791png_fp_set(state, PNG_FP_FRACTION | PNG_FP_SAW_DOT);27922793png_fp_add(state, type | PNG_FP_WAS_VALID);27942795break;27962797case PNG_FP_INTEGER + PNG_FP_SAW_E:2798if ((state & PNG_FP_SAW_DIGIT) == 0)2799goto PNG_FP_End;28002801png_fp_set(state, PNG_FP_EXPONENT);28022803break;28042805/* case PNG_FP_FRACTION + PNG_FP_SAW_SIGN:2806goto PNG_FP_End; ** no sign in fraction */28072808/* case PNG_FP_FRACTION + PNG_FP_SAW_DOT:2809goto PNG_FP_End; ** Because SAW_DOT is always set */28102811case PNG_FP_FRACTION + PNG_FP_SAW_DIGIT:2812png_fp_add(state, type | PNG_FP_WAS_VALID);2813break;28142815case PNG_FP_FRACTION + PNG_FP_SAW_E:2816/* This is correct because the trailing '.' on an2817* integer is handled above - so we can only get here2818* with the sequence ".E" (with no preceding digits).2819*/2820if ((state & PNG_FP_SAW_DIGIT) == 0)2821goto PNG_FP_End;28222823png_fp_set(state, PNG_FP_EXPONENT);28242825break;28262827case PNG_FP_EXPONENT + PNG_FP_SAW_SIGN:2828if ((state & PNG_FP_SAW_ANY) != 0)2829goto PNG_FP_End; /* not a part of the number */28302831png_fp_add(state, PNG_FP_SAW_SIGN);28322833break;28342835/* case PNG_FP_EXPONENT + PNG_FP_SAW_DOT:2836goto PNG_FP_End; */28372838case PNG_FP_EXPONENT + PNG_FP_SAW_DIGIT:2839png_fp_add(state, PNG_FP_SAW_DIGIT | PNG_FP_WAS_VALID);28402841break;28422843/* case PNG_FP_EXPONEXT + PNG_FP_SAW_E:2844goto PNG_FP_End; */28452846default: goto PNG_FP_End; /* I.e. break 2 */2847}28482849/* The character seems ok, continue. */2850++i;2851}28522853PNG_FP_End:2854/* Here at the end, update the state and return the correct2855* return code.2856*/2857*statep = state;2858*whereami = i;28592860return (state & PNG_FP_SAW_DIGIT) != 0;2861}286228632864/* The same but for a complete string. */2865int2866png_check_fp_string(png_const_charp string, size_t size)2867{2868int state=0;2869size_t char_index=0;28702871if (png_check_fp_number(string, size, &state, &char_index) != 0 &&2872(char_index == size || string[char_index] == 0))2873return state /* must be non-zero - see above */;28742875return 0; /* i.e. fail */2876}2877#endif /* pCAL || sCAL */28782879#ifdef PNG_sCAL_SUPPORTED2880# ifdef PNG_FLOATING_POINT_SUPPORTED2881/* Utility used below - a simple accurate power of ten from an integral2882* exponent.2883*/2884static double2885png_pow10(int power)2886{2887int recip = 0;2888double d = 1;28892890/* Handle negative exponent with a reciprocal at the end because2891* 10 is exact whereas .1 is inexact in base 22892*/2893if (power < 0)2894{2895if (power < DBL_MIN_10_EXP) return 0;2896recip = 1; power = -power;2897}28982899if (power > 0)2900{2901/* Decompose power bitwise. */2902double mult = 10;2903do2904{2905if (power & 1) d *= mult;2906mult *= mult;2907power >>= 1;2908}2909while (power > 0);29102911if (recip != 0) d = 1/d;2912}2913/* else power is 0 and d is 1 */29142915return d;2916}29172918/* Function to format a floating point value in ASCII with a given2919* precision.2920*/2921#if GCC_STRICT_OVERFLOW2922#pragma GCC diagnostic push2923/* The problem arises below with exp_b10, which can never overflow because it2924* comes, originally, from frexp and is therefore limited to a range which is2925* typically +/-710 (log2(DBL_MAX)/log2(DBL_MIN)).2926*/2927#pragma GCC diagnostic warning "-Wstrict-overflow=2"2928#endif /* GCC_STRICT_OVERFLOW */2929void /* PRIVATE */2930png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, size_t size,2931double fp, unsigned int precision)2932{2933/* We use standard functions from math.h, but not printf because2934* that would require stdio. The caller must supply a buffer of2935* sufficient size or we will png_error. The tests on size and2936* the space in ascii[] consumed are indicated below.2937*/2938if (precision < 1)2939precision = DBL_DIG;29402941/* Enforce the limit of the implementation precision too. */2942if (precision > DBL_DIG+1)2943precision = DBL_DIG+1;29442945/* Basic sanity checks */2946if (size >= precision+5) /* See the requirements below. */2947{2948if (fp < 0)2949{2950fp = -fp;2951*ascii++ = 45; /* '-' PLUS 1 TOTAL 1 */2952--size;2953}29542955if (fp >= DBL_MIN && fp <= DBL_MAX)2956{2957int exp_b10; /* A base 10 exponent */2958double base; /* 10^exp_b10 */29592960/* First extract a base 10 exponent of the number,2961* the calculation below rounds down when converting2962* from base 2 to base 10 (multiply by log10(2) -2963* 0.3010, but 77/256 is 0.3008, so exp_b10 needs to2964* be increased. Note that the arithmetic shift2965* performs a floor() unlike C arithmetic - using a2966* C multiply would break the following for negative2967* exponents.2968*/2969(void)frexp(fp, &exp_b10); /* exponent to base 2 */29702971exp_b10 = (exp_b10 * 77) >> 8; /* <= exponent to base 10 */29722973/* Avoid underflow here. */2974base = png_pow10(exp_b10); /* May underflow */29752976while (base < DBL_MIN || base < fp)2977{2978/* And this may overflow. */2979double test = png_pow10(exp_b10+1);29802981if (test <= DBL_MAX)2982{2983++exp_b10; base = test;2984}29852986else2987break;2988}29892990/* Normalize fp and correct exp_b10, after this fp is in the2991* range [.1,1) and exp_b10 is both the exponent and the digit2992* *before* which the decimal point should be inserted2993* (starting with 0 for the first digit). Note that this2994* works even if 10^exp_b10 is out of range because of the2995* test on DBL_MAX above.2996*/2997fp /= base;2998while (fp >= 1)2999{3000fp /= 10; ++exp_b10;3001}30023003/* Because of the code above fp may, at this point, be3004* less than .1, this is ok because the code below can3005* handle the leading zeros this generates, so no attempt3006* is made to correct that here.3007*/30083009{3010unsigned int czero, clead, cdigits;3011char exponent[10];30123013/* Allow up to two leading zeros - this will not lengthen3014* the number compared to using E-n.3015*/3016if (exp_b10 < 0 && exp_b10 > -3) /* PLUS 3 TOTAL 4 */3017{3018czero = 0U-exp_b10; /* PLUS 2 digits: TOTAL 3 */3019exp_b10 = 0; /* Dot added below before first output. */3020}3021else3022czero = 0; /* No zeros to add */30233024/* Generate the digit list, stripping trailing zeros and3025* inserting a '.' before a digit if the exponent is 0.3026*/3027clead = czero; /* Count of leading zeros */3028cdigits = 0; /* Count of digits in list. */30293030do3031{3032double d;30333034fp *= 10;3035/* Use modf here, not floor and subtract, so that3036* the separation is done in one step. At the end3037* of the loop don't break the number into parts so3038* that the final digit is rounded.3039*/3040if (cdigits+czero+1 < precision+clead)3041fp = modf(fp, &d);30423043else3044{3045d = floor(fp + .5);30463047if (d > 9)3048{3049/* Rounding up to 10, handle that here. */3050if (czero > 0)3051{3052--czero; d = 1;3053if (cdigits == 0) --clead;3054}3055else3056{3057while (cdigits > 0 && d > 9)3058{3059int ch = *--ascii;30603061if (exp_b10 != (-1))3062++exp_b10;30633064else if (ch == 46)3065{3066ch = *--ascii; ++size;3067/* Advance exp_b10 to '1', so that the3068* decimal point happens after the3069* previous digit.3070*/3071exp_b10 = 1;3072}30733074--cdigits;3075d = ch - 47; /* I.e. 1+(ch-48) */3076}30773078/* Did we reach the beginning? If so adjust the3079* exponent but take into account the leading3080* decimal point.3081*/3082if (d > 9) /* cdigits == 0 */3083{3084if (exp_b10 == (-1))3085{3086/* Leading decimal point (plus zeros?), if3087* we lose the decimal point here it must3088* be reentered below.3089*/3090int ch = *--ascii;30913092if (ch == 46)3093{3094++size; exp_b10 = 1;3095}30963097/* Else lost a leading zero, so 'exp_b10' is3098* still ok at (-1)3099*/3100}3101else3102++exp_b10;31033104/* In all cases we output a '1' */3105d = 1;3106}3107}3108}3109fp = 0; /* Guarantees termination below. */3110}31113112if (d == 0)3113{3114++czero;3115if (cdigits == 0) ++clead;3116}3117else3118{3119/* Included embedded zeros in the digit count. */3120cdigits += czero - clead;3121clead = 0;31223123while (czero > 0)3124{3125/* exp_b10 == (-1) means we just output the decimal3126* place - after the DP don't adjust 'exp_b10' any3127* more!3128*/3129if (exp_b10 != (-1))3130{3131if (exp_b10 == 0)3132{3133*ascii++ = 46; --size;3134}3135/* PLUS 1: TOTAL 4 */3136--exp_b10;3137}3138*ascii++ = 48; --czero;3139}31403141if (exp_b10 != (-1))3142{3143if (exp_b10 == 0)3144{3145*ascii++ = 46; --size; /* counted above */3146}31473148--exp_b10;3149}3150*ascii++ = (char)(48 + (int)d); ++cdigits;3151}3152}3153while (cdigits+czero < precision+clead && fp > DBL_MIN);31543155/* The total output count (max) is now 4+precision */31563157/* Check for an exponent, if we don't need one we are3158* done and just need to terminate the string. At this3159* point, exp_b10==(-1) is effectively a flag: it got3160* to '-1' because of the decrement, after outputting3161* the decimal point above. (The exponent required is3162* *not* -1.)3163*/3164if (exp_b10 >= (-1) && exp_b10 <= 2)3165{3166/* The following only happens if we didn't output the3167* leading zeros above for negative exponent, so this3168* doesn't add to the digit requirement. Note that the3169* two zeros here can only be output if the two leading3170* zeros were *not* output, so this doesn't increase3171* the output count.3172*/3173while (exp_b10-- > 0) *ascii++ = 48;31743175*ascii = 0;31763177/* Total buffer requirement (including the '\0') is3178* 5+precision - see check at the start.3179*/3180return;3181}31823183/* Here if an exponent is required, adjust size for3184* the digits we output but did not count. The total3185* digit output here so far is at most 1+precision - no3186* decimal point and no leading or trailing zeros have3187* been output.3188*/3189size -= cdigits;31903191*ascii++ = 69; --size; /* 'E': PLUS 1 TOTAL 2+precision */31923193/* The following use of an unsigned temporary avoids ambiguities in3194* the signed arithmetic on exp_b10 and permits GCC at least to do3195* better optimization.3196*/3197{3198unsigned int uexp_b10;31993200if (exp_b10 < 0)3201{3202*ascii++ = 45; --size; /* '-': PLUS 1 TOTAL 3+precision */3203uexp_b10 = 0U-exp_b10;3204}32053206else3207uexp_b10 = 0U+exp_b10;32083209cdigits = 0;32103211while (uexp_b10 > 0)3212{3213exponent[cdigits++] = (char)(48 + uexp_b10 % 10);3214uexp_b10 /= 10;3215}3216}32173218/* Need another size check here for the exponent digits, so3219* this need not be considered above.3220*/3221if (size > cdigits)3222{3223while (cdigits > 0) *ascii++ = exponent[--cdigits];32243225*ascii = 0;32263227return;3228}3229}3230}3231else if (!(fp >= DBL_MIN))3232{3233*ascii++ = 48; /* '0' */3234*ascii = 0;3235return;3236}3237else3238{3239*ascii++ = 105; /* 'i' */3240*ascii++ = 110; /* 'n' */3241*ascii++ = 102; /* 'f' */3242*ascii = 0;3243return;3244}3245}32463247/* Here on buffer too small. */3248png_error(png_ptr, "ASCII conversion buffer too small");3249}3250#if GCC_STRICT_OVERFLOW3251#pragma GCC diagnostic pop3252#endif /* GCC_STRICT_OVERFLOW */32533254# endif /* FLOATING_POINT */32553256# ifdef PNG_FIXED_POINT_SUPPORTED3257/* Function to format a fixed point value in ASCII.3258*/3259void /* PRIVATE */3260png_ascii_from_fixed(png_const_structrp png_ptr, png_charp ascii,3261size_t size, png_fixed_point fp)3262{3263/* Require space for 10 decimal digits, a decimal point, a minus sign and a3264* trailing \0, 13 characters:3265*/3266if (size > 12)3267{3268png_uint_32 num;32693270/* Avoid overflow here on the minimum integer. */3271if (fp < 0)3272{3273*ascii++ = 45; num = (png_uint_32)(-fp);3274}3275else3276num = (png_uint_32)fp;32773278if (num <= 0x80000000) /* else overflowed */3279{3280unsigned int ndigits = 0, first = 16 /* flag value */;3281char digits[10];32823283while (num)3284{3285/* Split the low digit off num: */3286unsigned int tmp = num/10;3287num -= tmp*10;3288digits[ndigits++] = (char)(48 + num);3289/* Record the first non-zero digit, note that this is a number3290* starting at 1, it's not actually the array index.3291*/3292if (first == 16 && num > 0)3293first = ndigits;3294num = tmp;3295}32963297if (ndigits > 0)3298{3299while (ndigits > 5) *ascii++ = digits[--ndigits];3300/* The remaining digits are fractional digits, ndigits is '5' or3301* smaller at this point. It is certainly not zero. Check for a3302* non-zero fractional digit:3303*/3304if (first <= 5)3305{3306unsigned int i;3307*ascii++ = 46; /* decimal point */3308/* ndigits may be <5 for small numbers, output leading zeros3309* then ndigits digits to first:3310*/3311i = 5;3312while (ndigits < i)3313{3314*ascii++ = 48; --i;3315}3316while (ndigits >= first) *ascii++ = digits[--ndigits];3317/* Don't output the trailing zeros! */3318}3319}3320else3321*ascii++ = 48;33223323/* And null terminate the string: */3324*ascii = 0;3325return;3326}3327}33283329/* Here on buffer too small. */3330png_error(png_ptr, "ASCII conversion buffer too small");3331}3332# endif /* FIXED_POINT */3333#endif /* SCAL */33343335#if defined(PNG_FLOATING_POINT_SUPPORTED) && \3336!defined(PNG_FIXED_POINT_MACRO_SUPPORTED) && \3337(defined(PNG_gAMA_SUPPORTED) || defined(PNG_cHRM_SUPPORTED) || \3338defined(PNG_sCAL_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) || \3339defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)) || \3340(defined(PNG_sCAL_SUPPORTED) && \3341defined(PNG_FLOATING_ARITHMETIC_SUPPORTED))3342png_fixed_point3343png_fixed(png_const_structrp png_ptr, double fp, png_const_charp text)3344{3345double r = floor(100000 * fp + .5);33463347if (r > 2147483647. || r < -2147483648.)3348png_fixed_error(png_ptr, text);33493350# ifndef PNG_ERROR_TEXT_SUPPORTED3351PNG_UNUSED(text)3352# endif33533354return (png_fixed_point)r;3355}3356#endif33573358#if defined(PNG_GAMMA_SUPPORTED) || defined(PNG_COLORSPACE_SUPPORTED) ||\3359defined(PNG_INCH_CONVERSIONS_SUPPORTED) || defined(PNG_READ_pHYs_SUPPORTED)3360/* muldiv functions */3361/* This API takes signed arguments and rounds the result to the nearest3362* integer (or, for a fixed point number - the standard argument - to3363* the nearest .00001). Overflow and divide by zero are signalled in3364* the result, a boolean - true on success, false on overflow.3365*/3366#if GCC_STRICT_OVERFLOW /* from above */3367/* It is not obvious which comparison below gets optimized in such a way that3368* signed overflow would change the result; looking through the code does not3369* reveal any tests which have the form GCC complains about, so presumably the3370* optimizer is moving an add or subtract into the 'if' somewhere.3371*/3372#pragma GCC diagnostic push3373#pragma GCC diagnostic warning "-Wstrict-overflow=2"3374#endif /* GCC_STRICT_OVERFLOW */3375int3376png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times,3377png_int_32 divisor)3378{3379/* Return a * times / divisor, rounded. */3380if (divisor != 0)3381{3382if (a == 0 || times == 0)3383{3384*res = 0;3385return 1;3386}3387else3388{3389#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3390double r = a;3391r *= times;3392r /= divisor;3393r = floor(r+.5);33943395/* A png_fixed_point is a 32-bit integer. */3396if (r <= 2147483647. && r >= -2147483648.)3397{3398*res = (png_fixed_point)r;3399return 1;3400}3401#else3402int negative = 0;3403png_uint_32 A, T, D;3404png_uint_32 s16, s32, s00;34053406if (a < 0)3407negative = 1, A = -a;3408else3409A = a;34103411if (times < 0)3412negative = !negative, T = -times;3413else3414T = times;34153416if (divisor < 0)3417negative = !negative, D = -divisor;3418else3419D = divisor;34203421/* Following can't overflow because the arguments only3422* have 31 bits each, however the result may be 32 bits.3423*/3424s16 = (A >> 16) * (T & 0xffff) +3425(A & 0xffff) * (T >> 16);3426/* Can't overflow because the a*times bit is only 303427* bits at most.3428*/3429s32 = (A >> 16) * (T >> 16) + (s16 >> 16);3430s00 = (A & 0xffff) * (T & 0xffff);34313432s16 = (s16 & 0xffff) << 16;3433s00 += s16;34343435if (s00 < s16)3436++s32; /* carry */34373438if (s32 < D) /* else overflow */3439{3440/* s32.s00 is now the 64-bit product, do a standard3441* division, we know that s32 < D, so the maximum3442* required shift is 31.3443*/3444int bitshift = 32;3445png_fixed_point result = 0; /* NOTE: signed */34463447while (--bitshift >= 0)3448{3449png_uint_32 d32, d00;34503451if (bitshift > 0)3452d32 = D >> (32-bitshift), d00 = D << bitshift;34533454else3455d32 = 0, d00 = D;34563457if (s32 > d32)3458{3459if (s00 < d00) --s32; /* carry */3460s32 -= d32, s00 -= d00, result += 1<<bitshift;3461}34623463else3464if (s32 == d32 && s00 >= d00)3465s32 = 0, s00 -= d00, result += 1<<bitshift;3466}34673468/* Handle the rounding. */3469if (s00 >= (D >> 1))3470++result;34713472if (negative != 0)3473result = -result;34743475/* Check for overflow. */3476if ((negative != 0 && result <= 0) ||3477(negative == 0 && result >= 0))3478{3479*res = result;3480return 1;3481}3482}3483#endif3484}3485}34863487return 0;3488}3489#if GCC_STRICT_OVERFLOW3490#pragma GCC diagnostic pop3491#endif /* GCC_STRICT_OVERFLOW */3492#endif /* READ_GAMMA || INCH_CONVERSIONS */34933494#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_INCH_CONVERSIONS_SUPPORTED)3495/* The following is for when the caller doesn't much care about the3496* result.3497*/3498png_fixed_point3499png_muldiv_warn(png_const_structrp png_ptr, png_fixed_point a, png_int_32 times,3500png_int_32 divisor)3501{3502png_fixed_point result;35033504if (png_muldiv(&result, a, times, divisor) != 0)3505return result;35063507png_warning(png_ptr, "fixed point overflow ignored");3508return 0;3509}3510#endif35113512#ifdef PNG_GAMMA_SUPPORTED /* more fixed point functions for gamma */3513/* Calculate a reciprocal, return 0 on div-by-zero or overflow. */3514png_fixed_point3515png_reciprocal(png_fixed_point a)3516{3517#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3518double r = floor(1E10/a+.5);35193520if (r <= 2147483647. && r >= -2147483648.)3521return (png_fixed_point)r;3522#else3523png_fixed_point res;35243525if (png_muldiv(&res, 100000, 100000, a) != 0)3526return res;3527#endif35283529return 0; /* error/overflow */3530}35313532/* This is the shared test on whether a gamma value is 'significant' - whether3533* it is worth doing gamma correction.3534*/3535int /* PRIVATE */3536png_gamma_significant(png_fixed_point gamma_val)3537{3538return gamma_val < PNG_FP_1 - PNG_GAMMA_THRESHOLD_FIXED ||3539gamma_val > PNG_FP_1 + PNG_GAMMA_THRESHOLD_FIXED;3540}3541#endif35423543#ifdef PNG_READ_GAMMA_SUPPORTED3544#ifdef PNG_16BIT_SUPPORTED3545/* A local convenience routine. */3546static png_fixed_point3547png_product2(png_fixed_point a, png_fixed_point b)3548{3549/* The required result is 1/a * 1/b; the following preserves accuracy. */3550#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3551double r = a * 1E-5;3552r *= b;3553r = floor(r+.5);35543555if (r <= 2147483647. && r >= -2147483648.)3556return (png_fixed_point)r;3557#else3558png_fixed_point res;35593560if (png_muldiv(&res, a, b, 100000) != 0)3561return res;3562#endif35633564return 0; /* overflow */3565}3566#endif /* 16BIT */35673568/* The inverse of the above. */3569png_fixed_point3570png_reciprocal2(png_fixed_point a, png_fixed_point b)3571{3572/* The required result is 1/a * 1/b; the following preserves accuracy. */3573#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3574if (a != 0 && b != 0)3575{3576double r = 1E15/a;3577r /= b;3578r = floor(r+.5);35793580if (r <= 2147483647. && r >= -2147483648.)3581return (png_fixed_point)r;3582}3583#else3584/* This may overflow because the range of png_fixed_point isn't symmetric,3585* but this API is only used for the product of file and screen gamma so it3586* doesn't matter that the smallest number it can produce is 1/21474, not3587* 1/1000003588*/3589png_fixed_point res = png_product2(a, b);35903591if (res != 0)3592return png_reciprocal(res);3593#endif35943595return 0; /* overflow */3596}3597#endif /* READ_GAMMA */35983599#ifdef PNG_READ_GAMMA_SUPPORTED /* gamma table code */3600#ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED3601/* Fixed point gamma.3602*3603* The code to calculate the tables used below can be found in the shell script3604* contrib/tools/intgamma.sh3605*3606* To calculate gamma this code implements fast log() and exp() calls using only3607* fixed point arithmetic. This code has sufficient precision for either 8-bit3608* or 16-bit sample values.3609*3610* The tables used here were calculated using simple 'bc' programs, but C double3611* precision floating point arithmetic would work fine.3612*3613* 8-bit log table3614* This is a table of -log(value/255)/log(2) for 'value' in the range 128 to3615* 255, so it's the base 2 logarithm of a normalized 8-bit floating point3616* mantissa. The numbers are 32-bit fractions.3617*/3618static const png_uint_323619png_8bit_l2[128] =3620{36214270715492U, 4222494797U, 4174646467U, 4127164793U, 4080044201U, 4033279239U,36223986864580U, 3940795015U, 3895065449U, 3849670902U, 3804606499U, 3759867474U,36233715449162U, 3671346997U, 3627556511U, 3584073329U, 3540893168U, 3498011834U,36243455425220U, 3413129301U, 3371120137U, 3329393864U, 3287946700U, 3246774933U,36253205874930U, 3165243125U, 3124876025U, 3084770202U, 3044922296U, 3005329011U,36262965987113U, 2926893432U, 2888044853U, 2849438323U, 2811070844U, 2772939474U,36272735041326U, 2697373562U, 2659933400U, 2622718104U, 2585724991U, 2548951424U,36282512394810U, 2476052606U, 2439922311U, 2404001468U, 2368287663U, 2332778523U,36292297471715U, 2262364947U, 2227455964U, 2192742551U, 2158222529U, 2123893754U,36302089754119U, 2055801552U, 2022034013U, 1988449497U, 1955046031U, 1921821672U,36311888774511U, 1855902668U, 1823204291U, 1790677560U, 1758320682U, 1726131893U,36321694109454U, 1662251657U, 1630556815U, 1599023271U, 1567649391U, 1536433567U,36331505374214U, 1474469770U, 1443718700U, 1413119487U, 1382670639U, 1352370686U,36341322218179U, 1292211689U, 1262349810U, 1232631153U, 1203054352U, 1173618059U,36351144320946U, 1115161701U, 1086139034U, 1057251672U, 1028498358U, 999877854U,3636971388940U, 943030410U, 914801076U, 886699767U, 858725327U, 830876614U,3637803152505U, 775551890U, 748073672U, 720716771U, 693480120U, 666362667U,3638639363374U, 612481215U, 585715177U, 559064263U, 532527486U, 506103872U,3639479792461U, 453592303U, 427502463U, 401522014U, 375650043U, 349885648U,3640324227938U, 298676034U, 273229066U, 247886176U, 222646516U, 197509248U,3641172473545U, 147538590U, 122703574U, 97967701U, 73330182U, 48790236U,364224347096U, 0U36433644#if 03645/* The following are the values for 16-bit tables - these work fine for the3646* 8-bit conversions but produce very slightly larger errors in the 16-bit3647* log (about 1.2 as opposed to 0.7 absolute error in the final value). To3648* use these all the shifts below must be adjusted appropriately.3649*/365065166, 64430, 63700, 62976, 62257, 61543, 60835, 60132, 59434, 58741, 58054,365157371, 56693, 56020, 55352, 54689, 54030, 53375, 52726, 52080, 51439, 50803,365250170, 49542, 48918, 48298, 47682, 47070, 46462, 45858, 45257, 44661, 44068,365343479, 42894, 42312, 41733, 41159, 40587, 40020, 39455, 38894, 38336, 37782,365437230, 36682, 36137, 35595, 35057, 34521, 33988, 33459, 32932, 32408, 31887,365531369, 30854, 30341, 29832, 29325, 28820, 28319, 27820, 27324, 26830, 26339,365625850, 25364, 24880, 24399, 23920, 23444, 22970, 22499, 22029, 21562, 21098,365720636, 20175, 19718, 19262, 18808, 18357, 17908, 17461, 17016, 16573, 16132,365815694, 15257, 14822, 14390, 13959, 13530, 13103, 12678, 12255, 11834, 11415,365910997, 10582, 10168, 9756, 9346, 8937, 8531, 8126, 7723, 7321, 6921, 6523,36606127, 5732, 5339, 4947, 4557, 4169, 3782, 3397, 3014, 2632, 2251, 1872, 1495,36611119, 744, 3723662#endif3663};36643665static png_int_323666png_log8bit(unsigned int x)3667{3668unsigned int lg2 = 0;3669/* Each time 'x' is multiplied by 2, 1 must be subtracted off the final log,3670* because the log is actually negate that means adding 1. The final3671* returned value thus has the range 0 (for 255 input) to 7.994 (for 13672* input), return -1 for the overflow (log 0) case, - so the result is3673* always at most 19 bits.3674*/3675if ((x &= 0xff) == 0)3676return -1;36773678if ((x & 0xf0) == 0)3679lg2 = 4, x <<= 4;36803681if ((x & 0xc0) == 0)3682lg2 += 2, x <<= 2;36833684if ((x & 0x80) == 0)3685lg2 += 1, x <<= 1;36863687/* result is at most 19 bits, so this cast is safe: */3688return (png_int_32)((lg2 << 16) + ((png_8bit_l2[x-128]+32768)>>16));3689}36903691/* The above gives exact (to 16 binary places) log2 values for 8-bit images,3692* for 16-bit images we use the most significant 8 bits of the 16-bit value to3693* get an approximation then multiply the approximation by a correction factor3694* determined by the remaining up to 8 bits. This requires an additional step3695* in the 16-bit case.3696*3697* We want log2(value/65535), we have log2(v'/255), where:3698*3699* value = v' * 256 + v''3700* = v' * f3701*3702* So f is value/v', which is equal to (256+v''/v') since v' is in the range 1283703* to 255 and v'' is in the range 0 to 255 f will be in the range 256 to less3704* than 258. The final factor also needs to correct for the fact that our 8-bit3705* value is scaled by 255, whereas the 16-bit values must be scaled by 65535.3706*3707* This gives a final formula using a calculated value 'x' which is value/v' and3708* scaling by 65536 to match the above table:3709*3710* log2(x/257) * 655363711*3712* Since these numbers are so close to '1' we can use simple linear3713* interpolation between the two end values 256/257 (result -368.61) and 258/2573714* (result 367.179). The values used below are scaled by a further 64 to give3715* 16-bit precision in the interpolation:3716*3717* Start (256): -235913718* Zero (257): 03719* End (258): 234993720*/3721#ifdef PNG_16BIT_SUPPORTED3722static png_int_323723png_log16bit(png_uint_32 x)3724{3725unsigned int lg2 = 0;37263727/* As above, but now the input has 16 bits. */3728if ((x &= 0xffff) == 0)3729return -1;37303731if ((x & 0xff00) == 0)3732lg2 = 8, x <<= 8;37333734if ((x & 0xf000) == 0)3735lg2 += 4, x <<= 4;37363737if ((x & 0xc000) == 0)3738lg2 += 2, x <<= 2;37393740if ((x & 0x8000) == 0)3741lg2 += 1, x <<= 1;37423743/* Calculate the base logarithm from the top 8 bits as a 28-bit fractional3744* value.3745*/3746lg2 <<= 28;3747lg2 += (png_8bit_l2[(x>>8)-128]+8) >> 4;37483749/* Now we need to interpolate the factor, this requires a division by the top3750* 8 bits. Do this with maximum precision.3751*/3752x = ((x << 16) + (x >> 9)) / (x >> 8);37533754/* Since we divided by the top 8 bits of 'x' there will be a '1' at 1<<24,3755* the value at 1<<16 (ignoring this) will be 0 or 1; this gives us exactly3756* 16 bits to interpolate to get the low bits of the result. Round the3757* answer. Note that the end point values are scaled by 64 to retain overall3758* precision and that 'lg2' is current scaled by an extra 12 bits, so adjust3759* the overall scaling by 6-12. Round at every step.3760*/3761x -= 1U << 24;37623763if (x <= 65536U) /* <= '257' */3764lg2 += ((23591U * (65536U-x)) + (1U << (16+6-12-1))) >> (16+6-12);37653766else3767lg2 -= ((23499U * (x-65536U)) + (1U << (16+6-12-1))) >> (16+6-12);37683769/* Safe, because the result can't have more than 20 bits: */3770return (png_int_32)((lg2 + 2048) >> 12);3771}3772#endif /* 16BIT */37733774/* The 'exp()' case must invert the above, taking a 20-bit fixed point3775* logarithmic value and returning a 16 or 8-bit number as appropriate. In3776* each case only the low 16 bits are relevant - the fraction - since the3777* integer bits (the top 4) simply determine a shift.3778*3779* The worst case is the 16-bit distinction between 65535 and 65534. This3780* requires perhaps spurious accuracy in the decoding of the logarithm to3781* distinguish log2(65535/65534.5) - 10^-5 or 17 bits. There is little chance3782* of getting this accuracy in practice.3783*3784* To deal with this the following exp() function works out the exponent of the3785* fractional part of the logarithm by using an accurate 32-bit value from the3786* top four fractional bits then multiplying in the remaining bits.3787*/3788static const png_uint_323789png_32bit_exp[16] =3790{3791/* NOTE: the first entry is deliberately set to the maximum 32-bit value. */37924294967295U, 4112874773U, 3938502376U, 3771522796U, 3611622603U, 3458501653U,37933311872529U, 3171459999U, 3037000500U, 2908241642U, 2784941738U, 2666869345U,37942553802834U, 2445529972U, 2341847524U, 2242560872U3795};37963797/* Adjustment table; provided to explain the numbers in the code below. */3798#if 03799for (i=11;i>=0;--i){ print i, " ", (1 - e(-(2^i)/65536*l(2))) * 2^(32-i), "\n"}380011 44937.64284865548751208448380110 45180.9873484558510116044838029 45303.3193698068735931187238038 45364.6511059532301887078438047 45395.3585036178962461491238056 45410.7225971510203750809638065 45418.4072441322072231116838074 45422.2502178689817300172838083 45424.1718673229841904435238092 45425.1327326994081146470438101 45425.6131755503555864166438110 45425.853399516549438504963812#endif38133814static png_uint_323815png_exp(png_fixed_point x)3816{3817if (x > 0 && x <= 0xfffff) /* Else overflow or zero (underflow) */3818{3819/* Obtain a 4-bit approximation */3820png_uint_32 e = png_32bit_exp[(x >> 12) & 0x0f];38213822/* Incorporate the low 12 bits - these decrease the returned value by3823* multiplying by a number less than 1 if the bit is set. The multiplier3824* is determined by the above table and the shift. Notice that the values3825* converge on 45426 and this is used to allow linear interpolation of the3826* low bits.3827*/3828if (x & 0x800)3829e -= (((e >> 16) * 44938U) + 16U) >> 5;38303831if (x & 0x400)3832e -= (((e >> 16) * 45181U) + 32U) >> 6;38333834if (x & 0x200)3835e -= (((e >> 16) * 45303U) + 64U) >> 7;38363837if (x & 0x100)3838e -= (((e >> 16) * 45365U) + 128U) >> 8;38393840if (x & 0x080)3841e -= (((e >> 16) * 45395U) + 256U) >> 9;38423843if (x & 0x040)3844e -= (((e >> 16) * 45410U) + 512U) >> 10;38453846/* And handle the low 6 bits in a single block. */3847e -= (((e >> 16) * 355U * (x & 0x3fU)) + 256U) >> 9;38483849/* Handle the upper bits of x. */3850e >>= x >> 16;3851return e;3852}38533854/* Check for overflow */3855if (x <= 0)3856return png_32bit_exp[0];38573858/* Else underflow */3859return 0;3860}38613862static png_byte3863png_exp8bit(png_fixed_point lg2)3864{3865/* Get a 32-bit value: */3866png_uint_32 x = png_exp(lg2);38673868/* Convert the 32-bit value to 0..255 by multiplying by 256-1. Note that the3869* second, rounding, step can't overflow because of the first, subtraction,3870* step.3871*/3872x -= x >> 8;3873return (png_byte)(((x + 0x7fffffU) >> 24) & 0xff);3874}38753876#ifdef PNG_16BIT_SUPPORTED3877static png_uint_163878png_exp16bit(png_fixed_point lg2)3879{3880/* Get a 32-bit value: */3881png_uint_32 x = png_exp(lg2);38823883/* Convert the 32-bit value to 0..65535 by multiplying by 65536-1: */3884x -= x >> 16;3885return (png_uint_16)((x + 32767U) >> 16);3886}3887#endif /* 16BIT */3888#endif /* FLOATING_ARITHMETIC */38893890png_byte3891png_gamma_8bit_correct(unsigned int value, png_fixed_point gamma_val)3892{3893if (value > 0 && value < 255)3894{3895# ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3896/* 'value' is unsigned, ANSI-C90 requires the compiler to correctly3897* convert this to a floating point value. This includes values that3898* would overflow if 'value' were to be converted to 'int'.3899*3900* Apparently GCC, however, does an intermediate conversion to (int)3901* on some (ARM) but not all (x86) platforms, possibly because of3902* hardware FP limitations. (E.g. if the hardware conversion always3903* assumes the integer register contains a signed value.) This results3904* in ANSI-C undefined behavior for large values.3905*3906* Other implementations on the same machine might actually be ANSI-C903907* conformant and therefore compile spurious extra code for the large3908* values.3909*3910* We can be reasonably sure that an unsigned to float conversion3911* won't be faster than an int to float one. Therefore this code3912* assumes responsibility for the undefined behavior, which it knows3913* can't happen because of the check above.3914*3915* Note the argument to this routine is an (unsigned int) because, on3916* 16-bit platforms, it is assigned a value which might be out of3917* range for an (int); that would result in undefined behavior in the3918* caller if the *argument* ('value') were to be declared (int).3919*/3920double r = floor(255*pow((int)/*SAFE*/value/255.,gamma_val*.00001)+.5);3921return (png_byte)r;3922# else3923png_int_32 lg2 = png_log8bit(value);3924png_fixed_point res;39253926if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1) != 0)3927return png_exp8bit(res);39283929/* Overflow. */3930value = 0;3931# endif3932}39333934return (png_byte)(value & 0xff);3935}39363937#ifdef PNG_16BIT_SUPPORTED3938png_uint_163939png_gamma_16bit_correct(unsigned int value, png_fixed_point gamma_val)3940{3941if (value > 0 && value < 65535)3942{3943# ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3944/* The same (unsigned int)->(double) constraints apply here as above,3945* however in this case the (unsigned int) to (int) conversion can3946* overflow on an ANSI-C90 compliant system so the cast needs to ensure3947* that this is not possible.3948*/3949double r = floor(65535*pow((png_int_32)value/65535.,3950gamma_val*.00001)+.5);3951return (png_uint_16)r;3952# else3953png_int_32 lg2 = png_log16bit(value);3954png_fixed_point res;39553956if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1) != 0)3957return png_exp16bit(res);39583959/* Overflow. */3960value = 0;3961# endif3962}39633964return (png_uint_16)value;3965}3966#endif /* 16BIT */39673968/* This does the right thing based on the bit_depth field of the3969* png_struct, interpreting values as 8-bit or 16-bit. While the result3970* is nominally a 16-bit value if bit depth is 8 then the result is3971* 8-bit (as are the arguments.)3972*/3973png_uint_16 /* PRIVATE */3974png_gamma_correct(png_structrp png_ptr, unsigned int value,3975png_fixed_point gamma_val)3976{3977if (png_ptr->bit_depth == 8)3978return png_gamma_8bit_correct(value, gamma_val);39793980#ifdef PNG_16BIT_SUPPORTED3981else3982return png_gamma_16bit_correct(value, gamma_val);3983#else3984/* should not reach this */3985return 0;3986#endif /* 16BIT */3987}39883989#ifdef PNG_16BIT_SUPPORTED3990/* Internal function to build a single 16-bit table - the table consists of3991* 'num' 256 entry subtables, where 'num' is determined by 'shift' - the amount3992* to shift the input values right (or 16-number_of_signifiant_bits).3993*3994* The caller is responsible for ensuring that the table gets cleaned up on3995* png_error (i.e. if one of the mallocs below fails) - i.e. the *table argument3996* should be somewhere that will be cleaned.3997*/3998static void3999png_build_16bit_table(png_structrp png_ptr, png_uint_16pp *ptable,4000unsigned int shift, png_fixed_point gamma_val)4001{4002/* Various values derived from 'shift': */4003unsigned int num = 1U << (8U - shift);4004#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED4005/* CSE the division and work round wacky GCC warnings (see the comments4006* in png_gamma_8bit_correct for where these come from.)4007*/4008double fmax = 1.0 / (((png_int_32)1 << (16U - shift)) - 1);4009#endif4010unsigned int max = (1U << (16U - shift)) - 1U;4011unsigned int max_by_2 = 1U << (15U - shift);4012unsigned int i;40134014png_uint_16pp table = *ptable =4015(png_uint_16pp)png_calloc(png_ptr, num * (sizeof (png_uint_16p)));40164017for (i = 0; i < num; i++)4018{4019png_uint_16p sub_table = table[i] =4020(png_uint_16p)png_malloc(png_ptr, 256 * (sizeof (png_uint_16)));40214022/* The 'threshold' test is repeated here because it can arise for one of4023* the 16-bit tables even if the others don't hit it.4024*/4025if (png_gamma_significant(gamma_val) != 0)4026{4027/* The old code would overflow at the end and this would cause the4028* 'pow' function to return a result >1, resulting in an4029* arithmetic error. This code follows the spec exactly; ig is4030* the recovered input sample, it always has 8-16 bits.4031*4032* We want input * 65535/max, rounded, the arithmetic fits in 324033* bits (unsigned) so long as max <= 32767.4034*/4035unsigned int j;4036for (j = 0; j < 256; j++)4037{4038png_uint_32 ig = (j << (8-shift)) + i;4039# ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED4040/* Inline the 'max' scaling operation: */4041/* See png_gamma_8bit_correct for why the cast to (int) is4042* required here.4043*/4044double d = floor(65535.*pow(ig*fmax, gamma_val*.00001)+.5);4045sub_table[j] = (png_uint_16)d;4046# else4047if (shift != 0)4048ig = (ig * 65535U + max_by_2)/max;40494050sub_table[j] = png_gamma_16bit_correct(ig, gamma_val);4051# endif4052}4053}4054else4055{4056/* We must still build a table, but do it the fast way. */4057unsigned int j;40584059for (j = 0; j < 256; j++)4060{4061png_uint_32 ig = (j << (8-shift)) + i;40624063if (shift != 0)4064ig = (ig * 65535U + max_by_2)/max;40654066sub_table[j] = (png_uint_16)ig;4067}4068}4069}4070}40714072/* NOTE: this function expects the *inverse* of the overall gamma transformation4073* required.4074*/4075static void4076png_build_16to8_table(png_structrp png_ptr, png_uint_16pp *ptable,4077unsigned int shift, png_fixed_point gamma_val)4078{4079unsigned int num = 1U << (8U - shift);4080unsigned int max = (1U << (16U - shift))-1U;4081unsigned int i;4082png_uint_32 last;40834084png_uint_16pp table = *ptable =4085(png_uint_16pp)png_calloc(png_ptr, num * (sizeof (png_uint_16p)));40864087/* 'num' is the number of tables and also the number of low bits of low4088* bits of the input 16-bit value used to select a table. Each table is4089* itself indexed by the high 8 bits of the value.4090*/4091for (i = 0; i < num; i++)4092table[i] = (png_uint_16p)png_malloc(png_ptr,4093256 * (sizeof (png_uint_16)));40944095/* 'gamma_val' is set to the reciprocal of the value calculated above, so4096* pow(out,g) is an *input* value. 'last' is the last input value set.4097*4098* In the loop 'i' is used to find output values. Since the output is4099* 8-bit there are only 256 possible values. The tables are set up to4100* select the closest possible output value for each input by finding4101* the input value at the boundary between each pair of output values4102* and filling the table up to that boundary with the lower output4103* value.4104*4105* The boundary values are 0.5,1.5..253.5,254.5. Since these are 9-bit4106* values the code below uses a 16-bit value in i; the values start at4107* 128.5 (for 0.5) and step by 257, for a total of 254 values (the last4108* entries are filled with 255). Start i at 128 and fill all 'last'4109* table entries <= 'max'4110*/4111last = 0;4112for (i = 0; i < 255; ++i) /* 8-bit output value */4113{4114/* Find the corresponding maximum input value */4115png_uint_16 out = (png_uint_16)(i * 257U); /* 16-bit output value */41164117/* Find the boundary value in 16 bits: */4118png_uint_32 bound = png_gamma_16bit_correct(out+128U, gamma_val);41194120/* Adjust (round) to (16-shift) bits: */4121bound = (bound * max + 32768U)/65535U + 1U;41224123while (last < bound)4124{4125table[last & (0xffU >> shift)][last >> (8U - shift)] = out;4126last++;4127}4128}41294130/* And fill in the final entries. */4131while (last < (num << 8))4132{4133table[last & (0xff >> shift)][last >> (8U - shift)] = 65535U;4134last++;4135}4136}4137#endif /* 16BIT */41384139/* Build a single 8-bit table: same as the 16-bit case but much simpler (and4140* typically much faster). Note that libpng currently does no sBIT processing4141* (apparently contrary to the spec) so a 256-entry table is always generated.4142*/4143static void4144png_build_8bit_table(png_structrp png_ptr, png_bytepp ptable,4145png_fixed_point gamma_val)4146{4147unsigned int i;4148png_bytep table = *ptable = (png_bytep)png_malloc(png_ptr, 256);41494150if (png_gamma_significant(gamma_val) != 0)4151for (i=0; i<256; i++)4152table[i] = png_gamma_8bit_correct(i, gamma_val);41534154else4155for (i=0; i<256; ++i)4156table[i] = (png_byte)(i & 0xff);4157}41584159/* Used from png_read_destroy and below to release the memory used by the gamma4160* tables.4161*/4162void /* PRIVATE */4163png_destroy_gamma_table(png_structrp png_ptr)4164{4165png_free(png_ptr, png_ptr->gamma_table);4166png_ptr->gamma_table = NULL;41674168#ifdef PNG_16BIT_SUPPORTED4169if (png_ptr->gamma_16_table != NULL)4170{4171int i;4172int istop = (1 << (8 - png_ptr->gamma_shift));4173for (i = 0; i < istop; i++)4174{4175png_free(png_ptr, png_ptr->gamma_16_table[i]);4176}4177png_free(png_ptr, png_ptr->gamma_16_table);4178png_ptr->gamma_16_table = NULL;4179}4180#endif /* 16BIT */41814182#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \4183defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \4184defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)4185png_free(png_ptr, png_ptr->gamma_from_1);4186png_ptr->gamma_from_1 = NULL;4187png_free(png_ptr, png_ptr->gamma_to_1);4188png_ptr->gamma_to_1 = NULL;41894190#ifdef PNG_16BIT_SUPPORTED4191if (png_ptr->gamma_16_from_1 != NULL)4192{4193int i;4194int istop = (1 << (8 - png_ptr->gamma_shift));4195for (i = 0; i < istop; i++)4196{4197png_free(png_ptr, png_ptr->gamma_16_from_1[i]);4198}4199png_free(png_ptr, png_ptr->gamma_16_from_1);4200png_ptr->gamma_16_from_1 = NULL;4201}4202if (png_ptr->gamma_16_to_1 != NULL)4203{4204int i;4205int istop = (1 << (8 - png_ptr->gamma_shift));4206for (i = 0; i < istop; i++)4207{4208png_free(png_ptr, png_ptr->gamma_16_to_1[i]);4209}4210png_free(png_ptr, png_ptr->gamma_16_to_1);4211png_ptr->gamma_16_to_1 = NULL;4212}4213#endif /* 16BIT */4214#endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */4215}42164217/* We build the 8- or 16-bit gamma tables here. Note that for 16-bit4218* tables, we don't make a full table if we are reducing to 8-bit in4219* the future. Note also how the gamma_16 tables are segmented so that4220* we don't need to allocate > 64K chunks for a full 16-bit table.4221*/4222void /* PRIVATE */4223png_build_gamma_table(png_structrp png_ptr, int bit_depth)4224{4225png_debug(1, "in png_build_gamma_table");42264227/* Remove any existing table; this copes with multiple calls to4228* png_read_update_info. The warning is because building the gamma tables4229* multiple times is a performance hit - it's harmless but the ability to4230* call png_read_update_info() multiple times is new in 1.5.6 so it seems4231* sensible to warn if the app introduces such a hit.4232*/4233if (png_ptr->gamma_table != NULL || png_ptr->gamma_16_table != NULL)4234{4235png_warning(png_ptr, "gamma table being rebuilt");4236png_destroy_gamma_table(png_ptr);4237}42384239if (bit_depth <= 8)4240{4241png_build_8bit_table(png_ptr, &png_ptr->gamma_table,4242png_ptr->screen_gamma > 0 ?4243png_reciprocal2(png_ptr->colorspace.gamma,4244png_ptr->screen_gamma) : PNG_FP_1);42454246#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \4247defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \4248defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)4249if ((png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY)) != 0)4250{4251png_build_8bit_table(png_ptr, &png_ptr->gamma_to_1,4252png_reciprocal(png_ptr->colorspace.gamma));42534254png_build_8bit_table(png_ptr, &png_ptr->gamma_from_1,4255png_ptr->screen_gamma > 0 ?4256png_reciprocal(png_ptr->screen_gamma) :4257png_ptr->colorspace.gamma/* Probably doing rgb_to_gray */);4258}4259#endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */4260}4261#ifdef PNG_16BIT_SUPPORTED4262else4263{4264png_byte shift, sig_bit;42654266if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)4267{4268sig_bit = png_ptr->sig_bit.red;42694270if (png_ptr->sig_bit.green > sig_bit)4271sig_bit = png_ptr->sig_bit.green;42724273if (png_ptr->sig_bit.blue > sig_bit)4274sig_bit = png_ptr->sig_bit.blue;4275}4276else4277sig_bit = png_ptr->sig_bit.gray;42784279/* 16-bit gamma code uses this equation:4280*4281* ov = table[(iv & 0xff) >> gamma_shift][iv >> 8]4282*4283* Where 'iv' is the input color value and 'ov' is the output value -4284* pow(iv, gamma).4285*4286* Thus the gamma table consists of up to 256 256-entry tables. The table4287* is selected by the (8-gamma_shift) most significant of the low 8 bits4288* of the color value then indexed by the upper 8 bits:4289*4290* table[low bits][high 8 bits]4291*4292* So the table 'n' corresponds to all those 'iv' of:4293*4294* <all high 8-bit values><n << gamma_shift>..<(n+1 << gamma_shift)-1>4295*4296*/4297if (sig_bit > 0 && sig_bit < 16U)4298/* shift == insignificant bits */4299shift = (png_byte)((16U - sig_bit) & 0xff);43004301else4302shift = 0; /* keep all 16 bits */43034304if ((png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8)) != 0)4305{4306/* PNG_MAX_GAMMA_8 is the number of bits to keep - effectively4307* the significant bits in the *input* when the output will4308* eventually be 8 bits. By default it is 11.4309*/4310if (shift < (16U - PNG_MAX_GAMMA_8))4311shift = (16U - PNG_MAX_GAMMA_8);4312}43134314if (shift > 8U)4315shift = 8U; /* Guarantees at least one table! */43164317png_ptr->gamma_shift = shift;43184319/* NOTE: prior to 1.5.4 this test used to include PNG_BACKGROUND (now4320* PNG_COMPOSE). This effectively smashed the background calculation for4321* 16-bit output because the 8-bit table assumes the result will be4322* reduced to 8 bits.4323*/4324if ((png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8)) != 0)4325png_build_16to8_table(png_ptr, &png_ptr->gamma_16_table, shift,4326png_ptr->screen_gamma > 0 ? png_product2(png_ptr->colorspace.gamma,4327png_ptr->screen_gamma) : PNG_FP_1);43284329else4330png_build_16bit_table(png_ptr, &png_ptr->gamma_16_table, shift,4331png_ptr->screen_gamma > 0 ? png_reciprocal2(png_ptr->colorspace.gamma,4332png_ptr->screen_gamma) : PNG_FP_1);43334334#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \4335defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \4336defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)4337if ((png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY)) != 0)4338{4339png_build_16bit_table(png_ptr, &png_ptr->gamma_16_to_1, shift,4340png_reciprocal(png_ptr->colorspace.gamma));43414342/* Notice that the '16 from 1' table should be full precision, however4343* the lookup on this table still uses gamma_shift, so it can't be.4344* TODO: fix this.4345*/4346png_build_16bit_table(png_ptr, &png_ptr->gamma_16_from_1, shift,4347png_ptr->screen_gamma > 0 ? png_reciprocal(png_ptr->screen_gamma) :4348png_ptr->colorspace.gamma/* Probably doing rgb_to_gray */);4349}4350#endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */4351}4352#endif /* 16BIT */4353}4354#endif /* READ_GAMMA */43554356/* HARDWARE OR SOFTWARE OPTION SUPPORT */4357#ifdef PNG_SET_OPTION_SUPPORTED4358int PNGAPI4359png_set_option(png_structrp png_ptr, int option, int onoff)4360{4361if (png_ptr != NULL && option >= 0 && option < PNG_OPTION_NEXT &&4362(option & 1) == 0)4363{4364png_uint_32 mask = 3U << option;4365png_uint_32 setting = (2U + (onoff != 0)) << option;4366png_uint_32 current = png_ptr->options;43674368png_ptr->options = (png_uint_32)((current & ~mask) | setting);43694370return (int)(current & mask) >> option;4371}43724373return PNG_OPTION_INVALID;4374}4375#endif43764377/* sRGB support */4378#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\4379defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)4380/* sRGB conversion tables; these are machine generated with the code in4381* contrib/tools/makesRGB.c. The actual sRGB transfer curve defined in the4382* specification (see the article at https://en.wikipedia.org/wiki/SRGB)4383* is used, not the gamma=1/2.2 approximation use elsewhere in libpng.4384* The sRGB to linear table is exact (to the nearest 16-bit linear fraction).4385* The inverse (linear to sRGB) table has accuracies as follows:4386*4387* For all possible (255*65535+1) input values:4388*4389* error: -0.515566 - 0.625971, 79441 (0.475369%) of readings inexact4390*4391* For the input values corresponding to the 65536 16-bit values:4392*4393* error: -0.513727 - 0.607759, 308 (0.469978%) of readings inexact4394*4395* In all cases the inexact readings are only off by one.4396*/43974398#ifdef PNG_SIMPLIFIED_READ_SUPPORTED4399/* The convert-to-sRGB table is only currently required for read. */4400const png_uint_16 png_sRGB_table[256] =4401{44020,20,40,60,80,99,119,139,4403159,179,199,219,241,264,288,313,4404340,367,396,427,458,491,526,562,4405599,637,677,718,761,805,851,898,4406947,997,1048,1101,1156,1212,1270,1330,44071391,1453,1517,1583,1651,1720,1790,1863,44081937,2013,2090,2170,2250,2333,2418,2504,44092592,2681,2773,2866,2961,3058,3157,3258,44103360,3464,3570,3678,3788,3900,4014,4129,44114247,4366,4488,4611,4736,4864,4993,5124,44125257,5392,5530,5669,5810,5953,6099,6246,44136395,6547,6700,6856,7014,7174,7335,7500,44147666,7834,8004,8177,8352,8528,8708,8889,44159072,9258,9445,9635,9828,10022,10219,10417,441610619,10822,11028,11235,11446,11658,11873,12090,441712309,12530,12754,12980,13209,13440,13673,13909,441814146,14387,14629,14874,15122,15371,15623,15878,441916135,16394,16656,16920,17187,17456,17727,18001,442018277,18556,18837,19121,19407,19696,19987,20281,442120577,20876,21177,21481,21787,22096,22407,22721,442223038,23357,23678,24002,24329,24658,24990,25325,442325662,26001,26344,26688,27036,27386,27739,28094,442428452,28813,29176,29542,29911,30282,30656,31033,442531412,31794,32179,32567,32957,33350,33745,34143,442634544,34948,35355,35764,36176,36591,37008,37429,442737852,38278,38706,39138,39572,40009,40449,40891,442841337,41785,42236,42690,43147,43606,44069,44534,442945002,45473,45947,46423,46903,47385,47871,48359,443048850,49344,49841,50341,50844,51349,51858,52369,443152884,53401,53921,54445,54971,55500,56032,56567,443257105,57646,58190,58737,59287,59840,60396,60955,443361517,62082,62650,63221,63795,64372,64952,655354434};4435#endif /* SIMPLIFIED_READ */44364437/* The base/delta tables are required for both read and write (but currently4438* only the simplified versions.)4439*/4440const png_uint_16 png_sRGB_base[512] =4441{4442128,1782,3383,4644,5675,6564,7357,8074,44438732,9346,9921,10463,10977,11466,11935,12384,444412816,13233,13634,14024,14402,14769,15125,15473,444515812,16142,16466,16781,17090,17393,17690,17981,444618266,18546,18822,19093,19359,19621,19879,20133,444720383,20630,20873,21113,21349,21583,21813,22041,444822265,22487,22707,22923,23138,23350,23559,23767,444923972,24175,24376,24575,24772,24967,25160,25352,445025542,25730,25916,26101,26284,26465,26645,26823,445127000,27176,27350,27523,27695,27865,28034,28201,445228368,28533,28697,28860,29021,29182,29341,29500,445329657,29813,29969,30123,30276,30429,30580,30730,445430880,31028,31176,31323,31469,31614,31758,31902,445532045,32186,32327,32468,32607,32746,32884,33021,445633158,33294,33429,33564,33697,33831,33963,34095,445734226,34357,34486,34616,34744,34873,35000,35127,445835253,35379,35504,35629,35753,35876,35999,36122,445936244,36365,36486,36606,36726,36845,36964,37083,446037201,37318,37435,37551,37668,37783,37898,38013,446138127,38241,38354,38467,38580,38692,38803,38915,446239026,39136,39246,39356,39465,39574,39682,39790,446339898,40005,40112,40219,40325,40431,40537,40642,446440747,40851,40955,41059,41163,41266,41369,41471,446541573,41675,41777,41878,41979,42079,42179,42279,446642379,42478,42577,42676,42775,42873,42971,43068,446743165,43262,43359,43456,43552,43648,43743,43839,446843934,44028,44123,44217,44311,44405,44499,44592,446944685,44778,44870,44962,45054,45146,45238,45329,447045420,45511,45601,45692,45782,45872,45961,46051,447146140,46229,46318,46406,46494,46583,46670,46758,447246846,46933,47020,47107,47193,47280,47366,47452,447347538,47623,47709,47794,47879,47964,48048,48133,447448217,48301,48385,48468,48552,48635,48718,48801,447548884,48966,49048,49131,49213,49294,49376,49458,447649539,49620,49701,49782,49862,49943,50023,50103,447750183,50263,50342,50422,50501,50580,50659,50738,447850816,50895,50973,51051,51129,51207,51285,51362,447951439,51517,51594,51671,51747,51824,51900,51977,448052053,52129,52205,52280,52356,52432,52507,52582,448152657,52732,52807,52881,52956,53030,53104,53178,448253252,53326,53400,53473,53546,53620,53693,53766,448353839,53911,53984,54056,54129,54201,54273,54345,448454417,54489,54560,54632,54703,54774,54845,54916,448554987,55058,55129,55199,55269,55340,55410,55480,448655550,55620,55689,55759,55828,55898,55967,56036,448756105,56174,56243,56311,56380,56448,56517,56585,448856653,56721,56789,56857,56924,56992,57059,57127,448957194,57261,57328,57395,57462,57529,57595,57662,449057728,57795,57861,57927,57993,58059,58125,58191,449158256,58322,58387,58453,58518,58583,58648,58713,449258778,58843,58908,58972,59037,59101,59165,59230,449359294,59358,59422,59486,59549,59613,59677,59740,449459804,59867,59930,59993,60056,60119,60182,60245,449560308,60370,60433,60495,60558,60620,60682,60744,449660806,60868,60930,60992,61054,61115,61177,61238,449761300,61361,61422,61483,61544,61605,61666,61727,449861788,61848,61909,61969,62030,62090,62150,62211,449962271,62331,62391,62450,62510,62570,62630,62689,450062749,62808,62867,62927,62986,63045,63104,63163,450163222,63281,63340,63398,63457,63515,63574,63632,450263691,63749,63807,63865,63923,63981,64039,64097,450364155,64212,64270,64328,64385,64443,64500,64557,450464614,64672,64729,64786,64843,64900,64956,65013,450565070,65126,65183,65239,65296,65352,65409,654654506};45074508const png_byte png_sRGB_delta[512] =4509{4510207,201,158,129,113,100,90,82,77,72,68,64,61,59,56,54,451152,50,49,47,46,45,43,42,41,40,39,39,38,37,36,36,451235,34,34,33,33,32,32,31,31,30,30,30,29,29,28,28,451328,27,27,27,27,26,26,26,25,25,25,25,24,24,24,24,451423,23,23,23,23,22,22,22,22,22,22,21,21,21,21,21,451521,20,20,20,20,20,20,20,20,19,19,19,19,19,19,19,451619,18,18,18,18,18,18,18,18,18,18,17,17,17,17,17,451717,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,451816,16,16,16,15,15,15,15,15,15,15,15,15,15,15,15,451915,15,15,15,14,14,14,14,14,14,14,14,14,14,14,14,452014,14,14,14,14,14,14,13,13,13,13,13,13,13,13,13,452113,13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,452212,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,452312,12,12,12,12,12,12,12,12,12,12,12,11,11,11,11,452411,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,452511,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,452611,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,452710,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,452810,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,452910,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,45309,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,45319,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,45329,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,45339,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,45348,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,45358,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,45368,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,45378,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,45388,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,45397,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,45407,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,45417,7,7,7,7,7,7,7,7,7,7,7,7,7,7,74542};4543#endif /* SIMPLIFIED READ/WRITE sRGB support */45444545/* SIMPLIFIED READ/WRITE SUPPORT */4546#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\4547defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)4548static int4549png_image_free_function(png_voidp argument)4550{4551png_imagep image = png_voidcast(png_imagep, argument);4552png_controlp cp = image->opaque;4553png_control c;45544555/* Double check that we have a png_ptr - it should be impossible to get here4556* without one.4557*/4558if (cp->png_ptr == NULL)4559return 0;45604561/* First free any data held in the control structure. */4562# ifdef PNG_STDIO_SUPPORTED4563if (cp->owned_file != 0)4564{4565FILE *fp = png_voidcast(FILE*, cp->png_ptr->io_ptr);4566cp->owned_file = 0;45674568/* Ignore errors here. */4569if (fp != NULL)4570{4571cp->png_ptr->io_ptr = NULL;4572(void)fclose(fp);4573}4574}4575# endif45764577/* Copy the control structure so that the original, allocated, version can be4578* safely freed. Notice that a png_error here stops the remainder of the4579* cleanup, but this is probably fine because that would indicate bad memory4580* problems anyway.4581*/4582c = *cp;4583image->opaque = &c;4584png_free(c.png_ptr, cp);45854586/* Then the structures, calling the correct API. */4587if (c.for_write != 0)4588{4589# ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED4590png_destroy_write_struct(&c.png_ptr, &c.info_ptr);4591# else4592png_error(c.png_ptr, "simplified write not supported");4593# endif4594}4595else4596{4597# ifdef PNG_SIMPLIFIED_READ_SUPPORTED4598png_destroy_read_struct(&c.png_ptr, &c.info_ptr, NULL);4599# else4600png_error(c.png_ptr, "simplified read not supported");4601# endif4602}46034604/* Success. */4605return 1;4606}46074608void PNGAPI4609png_image_free(png_imagep image)4610{4611/* Safely call the real function, but only if doing so is safe at this point4612* (if not inside an error handling context). Otherwise assume4613* png_safe_execute will call this API after the return.4614*/4615if (image != NULL && image->opaque != NULL &&4616image->opaque->error_buf == NULL)4617{4618png_image_free_function(image);4619image->opaque = NULL;4620}4621}46224623int /* PRIVATE */4624png_image_error(png_imagep image, png_const_charp error_message)4625{4626/* Utility to log an error. */4627png_safecat(image->message, (sizeof image->message), 0, error_message);4628image->warning_or_error |= PNG_IMAGE_ERROR;4629png_image_free(image);4630return 0;4631}46324633#endif /* SIMPLIFIED READ/WRITE */4634#endif /* READ || WRITE */463546364637