/* png.c - location for general purpose libpng functions1*2* Copyright (c) 2018-2025 Cosmin Truta3* Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson4* Copyright (c) 1996-1997 Andreas Dilger5* Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.6*7* This code is released under the libpng license.8* For conditions of distribution and use, see the disclaimer9* and license in png.h10*/1112#include "pngpriv.h"1314/* Generate a compiler error if there is an old png.h in the search path. */15typedef png_libpng_version_1_6_48 Your_png_h_is_not_version_1_6_48;1617/* Sanity check the chunks definitions - PNG_KNOWN_CHUNKS from pngpriv.h and the18* corresponding macro definitions. This causes a compile time failure if19* something is wrong but generates no code.20*21* (1) The first check is that the PNG_CHUNK(cHNK, index) 'index' values must22* increment from 0 to the last value.23*/24#define PNG_CHUNK(cHNK, index) != (index) || ((index)+1)2526#if 0 PNG_KNOWN_CHUNKS < 027# error PNG_KNOWN_CHUNKS chunk definitions are not in order28#endif2930#undef PNG_CHUNK3132/* (2) The chunk name macros, png_cHNK, must all be valid and defined. Since33* this is a preprocessor test undefined pp-tokens come out as zero and will34* fail this test.35*/36#define PNG_CHUNK(cHNK, index) !PNG_CHUNK_NAME_VALID(png_ ## cHNK) ||3738#if PNG_KNOWN_CHUNKS 039# error png_cHNK not defined for some known cHNK40#endif4142#undef PNG_CHUNK4344/* Tells libpng that we have already handled the first "num_bytes" bytes45* of the PNG file signature. If the PNG data is embedded into another46* stream we can set num_bytes = 8 so that libpng will not attempt to read47* or write any of the magic bytes before it starts on the IHDR.48*/4950#ifdef PNG_READ_SUPPORTED51void PNGAPI52png_set_sig_bytes(png_structrp png_ptr, int num_bytes)53{54unsigned int nb = (unsigned int)num_bytes;5556png_debug(1, "in png_set_sig_bytes");5758if (png_ptr == NULL)59return;6061if (num_bytes < 0)62nb = 0;6364if (nb > 8)65png_error(png_ptr, "Too many bytes for PNG signature");6667png_ptr->sig_bytes = (png_byte)nb;68}6970/* Checks whether the supplied bytes match the PNG signature. We allow71* checking less than the full 8-byte signature so that those apps that72* already read the first few bytes of a file to determine the file type73* can simply check the remaining bytes for extra assurance. Returns74* an integer less than, equal to, or greater than zero if sig is found,75* respectively, to be less than, to match, or be greater than the correct76* PNG signature (this is the same behavior as strcmp, memcmp, etc).77*/78int PNGAPI79png_sig_cmp(png_const_bytep sig, size_t start, size_t num_to_check)80{81static const png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};8283if (num_to_check > 8)84num_to_check = 8;8586else if (num_to_check < 1)87return -1;8889if (start > 7)90return -1;9192if (start + num_to_check > 8)93num_to_check = 8 - start;9495return memcmp(&sig[start], &png_signature[start], num_to_check);96}9798#endif /* READ */99100#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)101/* Function to allocate memory for zlib */102PNG_FUNCTION(voidpf /* PRIVATE */,103png_zalloc,(voidpf png_ptr, uInt items, uInt size),PNG_ALLOCATED)104{105png_alloc_size_t num_bytes = size;106107if (png_ptr == NULL)108return NULL;109110if (items >= (~(png_alloc_size_t)0)/size)111{112png_warning (png_voidcast(png_structrp, png_ptr),113"Potential overflow in png_zalloc()");114return NULL;115}116117num_bytes *= items;118return png_malloc_warn(png_voidcast(png_structrp, png_ptr), num_bytes);119}120121/* Function to free memory for zlib */122void /* PRIVATE */123png_zfree(voidpf png_ptr, voidpf ptr)124{125png_free(png_voidcast(png_const_structrp,png_ptr), ptr);126}127128/* Reset the CRC variable to 32 bits of 1's. Care must be taken129* in case CRC is > 32 bits to leave the top bits 0.130*/131void /* PRIVATE */132png_reset_crc(png_structrp png_ptr)133{134/* The cast is safe because the crc is a 32-bit value. */135png_ptr->crc = (png_uint_32)crc32(0, Z_NULL, 0);136}137138/* Calculate the CRC over a section of data. We can only pass as139* much data to this routine as the largest single buffer size. We140* also check that this data will actually be used before going to the141* trouble of calculating it.142*/143void /* PRIVATE */144png_calculate_crc(png_structrp png_ptr, png_const_bytep ptr, size_t length)145{146int need_crc = 1;147148if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0)149{150if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==151(PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))152need_crc = 0;153}154155else /* critical */156{157if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0)158need_crc = 0;159}160161/* 'uLong' is defined in zlib.h as unsigned long; this means that on some162* systems it is a 64-bit value. crc32, however, returns 32 bits so the163* following cast is safe. 'uInt' may be no more than 16 bits, so it is164* necessary to perform a loop here.165*/166if (need_crc != 0 && length > 0)167{168uLong crc = png_ptr->crc; /* Should never issue a warning */169170do171{172uInt safe_length = (uInt)length;173#ifndef __COVERITY__174if (safe_length == 0)175safe_length = (uInt)-1; /* evil, but safe */176#endif177178crc = crc32(crc, ptr, safe_length);179180/* The following should never issue compiler warnings; if they do the181* target system has characteristics that will probably violate other182* assumptions within the libpng code.183*/184ptr += safe_length;185length -= safe_length;186}187while (length > 0);188189/* And the following is always safe because the crc is only 32 bits. */190png_ptr->crc = (png_uint_32)crc;191}192}193194/* Check a user supplied version number, called from both read and write195* functions that create a png_struct.196*/197int198png_user_version_check(png_structrp png_ptr, png_const_charp user_png_ver)199{200/* Libpng versions 1.0.0 and later are binary compatible if the version201* string matches through the second '.'; we must recompile any202* applications that use any older library version.203*/204205if (user_png_ver != NULL)206{207int i = -1;208int found_dots = 0;209210do211{212i++;213if (user_png_ver[i] != PNG_LIBPNG_VER_STRING[i])214png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;215if (user_png_ver[i] == '.')216found_dots++;217} while (found_dots < 2 && user_png_ver[i] != 0 &&218PNG_LIBPNG_VER_STRING[i] != 0);219}220221else222png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;223224if ((png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH) != 0)225{226#ifdef PNG_WARNINGS_SUPPORTED227size_t pos = 0;228char m[128];229230pos = png_safecat(m, (sizeof m), pos,231"Application built with libpng-");232pos = png_safecat(m, (sizeof m), pos, user_png_ver);233pos = png_safecat(m, (sizeof m), pos, " but running with ");234pos = png_safecat(m, (sizeof m), pos, PNG_LIBPNG_VER_STRING);235PNG_UNUSED(pos)236237png_warning(png_ptr, m);238#endif239240#ifdef PNG_ERROR_NUMBERS_SUPPORTED241png_ptr->flags = 0;242#endif243244return 0;245}246247/* Success return. */248return 1;249}250251/* Generic function to create a png_struct for either read or write - this252* contains the common initialization.253*/254PNG_FUNCTION(png_structp /* PRIVATE */,255png_create_png_struct,(png_const_charp user_png_ver, png_voidp error_ptr,256png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,257png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)258{259png_struct create_struct;260# ifdef PNG_SETJMP_SUPPORTED261jmp_buf create_jmp_buf;262# endif263264/* This temporary stack-allocated structure is used to provide a place to265* build enough context to allow the user provided memory allocator (if any)266* to be called.267*/268memset(&create_struct, 0, (sizeof create_struct));269270# ifdef PNG_USER_LIMITS_SUPPORTED271create_struct.user_width_max = PNG_USER_WIDTH_MAX;272create_struct.user_height_max = PNG_USER_HEIGHT_MAX;273274# ifdef PNG_USER_CHUNK_CACHE_MAX275create_struct.user_chunk_cache_max = PNG_USER_CHUNK_CACHE_MAX;276# endif277278# if PNG_USER_CHUNK_MALLOC_MAX > 0 /* default to compile-time limit */279create_struct.user_chunk_malloc_max = PNG_USER_CHUNK_MALLOC_MAX;280281/* No compile-time limit, so initialize to the system limit: */282# elif defined PNG_MAX_MALLOC_64K /* legacy system limit */283create_struct.user_chunk_malloc_max = 65536U;284285# else /* modern system limit SIZE_MAX (C99) */286create_struct.user_chunk_malloc_max = PNG_SIZE_MAX;287# endif288# endif289290/* The following two API calls simply set fields in png_struct, so it is safe291* to do them now even though error handling is not yet set up.292*/293# ifdef PNG_USER_MEM_SUPPORTED294png_set_mem_fn(&create_struct, mem_ptr, malloc_fn, free_fn);295# else296PNG_UNUSED(mem_ptr)297PNG_UNUSED(malloc_fn)298PNG_UNUSED(free_fn)299# endif300301/* (*error_fn) can return control to the caller after the error_ptr is set,302* this will result in a memory leak unless the error_fn does something303* extremely sophisticated. The design lacks merit but is implicit in the304* API.305*/306png_set_error_fn(&create_struct, error_ptr, error_fn, warn_fn);307308# ifdef PNG_SETJMP_SUPPORTED309if (!setjmp(create_jmp_buf))310# endif311{312# ifdef PNG_SETJMP_SUPPORTED313/* Temporarily fake out the longjmp information until we have314* successfully completed this function. This only works if we have315* setjmp() support compiled in, but it is safe - this stuff should316* never happen.317*/318create_struct.jmp_buf_ptr = &create_jmp_buf;319create_struct.jmp_buf_size = 0; /*stack allocation*/320create_struct.longjmp_fn = longjmp;321# endif322/* Call the general version checker (shared with read and write code):323*/324if (png_user_version_check(&create_struct, user_png_ver) != 0)325{326png_structrp png_ptr = png_voidcast(png_structrp,327png_malloc_warn(&create_struct, (sizeof *png_ptr)));328329if (png_ptr != NULL)330{331/* png_ptr->zstream holds a back-pointer to the png_struct, so332* this can only be done now:333*/334create_struct.zstream.zalloc = png_zalloc;335create_struct.zstream.zfree = png_zfree;336create_struct.zstream.opaque = png_ptr;337338# ifdef PNG_SETJMP_SUPPORTED339/* Eliminate the local error handling: */340create_struct.jmp_buf_ptr = NULL;341create_struct.jmp_buf_size = 0;342create_struct.longjmp_fn = 0;343# endif344345*png_ptr = create_struct;346347/* This is the successful return point */348return png_ptr;349}350}351}352353/* A longjmp because of a bug in the application storage allocator or a354* simple failure to allocate the png_struct.355*/356return NULL;357}358359/* Allocate the memory for an info_struct for the application. */360PNG_FUNCTION(png_infop,PNGAPI361png_create_info_struct,(png_const_structrp png_ptr),PNG_ALLOCATED)362{363png_inforp info_ptr;364365png_debug(1, "in png_create_info_struct");366367if (png_ptr == NULL)368return NULL;369370/* Use the internal API that does not (or at least should not) error out, so371* that this call always returns ok. The application typically sets up the372* error handling *after* creating the info_struct because this is the way it373* has always been done in 'example.c'.374*/375info_ptr = png_voidcast(png_inforp, png_malloc_base(png_ptr,376(sizeof *info_ptr)));377378if (info_ptr != NULL)379memset(info_ptr, 0, (sizeof *info_ptr));380381return info_ptr;382}383384/* This function frees the memory associated with a single info struct.385* Normally, one would use either png_destroy_read_struct() or386* png_destroy_write_struct() to free an info struct, but this may be387* useful for some applications. From libpng 1.6.0 this function is also used388* internally to implement the png_info release part of the 'struct' destroy389* APIs. This ensures that all possible approaches free the same data (all of390* it).391*/392void PNGAPI393png_destroy_info_struct(png_const_structrp png_ptr, png_infopp info_ptr_ptr)394{395png_inforp info_ptr = NULL;396397png_debug(1, "in png_destroy_info_struct");398399if (png_ptr == NULL)400return;401402if (info_ptr_ptr != NULL)403info_ptr = *info_ptr_ptr;404405if (info_ptr != NULL)406{407/* Do this first in case of an error below; if the app implements its own408* memory management this can lead to png_free calling png_error, which409* will abort this routine and return control to the app error handler.410* An infinite loop may result if it then tries to free the same info411* ptr.412*/413*info_ptr_ptr = NULL;414415png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);416memset(info_ptr, 0, (sizeof *info_ptr));417png_free(png_ptr, info_ptr);418}419}420421/* Initialize the info structure. This is now an internal function (0.89)422* and applications using it are urged to use png_create_info_struct()423* instead. Use deprecated in 1.6.0, internal use removed (used internally it424* is just a memset).425*426* NOTE: it is almost inconceivable that this API is used because it bypasses427* the user-memory mechanism and the user error handling/warning mechanisms in428* those cases where it does anything other than a memset.429*/430PNG_FUNCTION(void,PNGAPI431png_info_init_3,(png_infopp ptr_ptr, size_t png_info_struct_size),432PNG_DEPRECATED)433{434png_inforp info_ptr = *ptr_ptr;435436png_debug(1, "in png_info_init_3");437438if (info_ptr == NULL)439return;440441if ((sizeof (png_info)) > png_info_struct_size)442{443*ptr_ptr = NULL;444/* The following line is why this API should not be used: */445free(info_ptr);446info_ptr = png_voidcast(png_inforp, png_malloc_base(NULL,447(sizeof *info_ptr)));448if (info_ptr == NULL)449return;450*ptr_ptr = info_ptr;451}452453/* Set everything to 0 */454memset(info_ptr, 0, (sizeof *info_ptr));455}456457void PNGAPI458png_data_freer(png_const_structrp png_ptr, png_inforp info_ptr,459int freer, png_uint_32 mask)460{461png_debug(1, "in png_data_freer");462463if (png_ptr == NULL || info_ptr == NULL)464return;465466if (freer == PNG_DESTROY_WILL_FREE_DATA)467info_ptr->free_me |= mask;468469else if (freer == PNG_USER_WILL_FREE_DATA)470info_ptr->free_me &= ~mask;471472else473png_error(png_ptr, "Unknown freer parameter in png_data_freer");474}475476void PNGAPI477png_free_data(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 mask,478int num)479{480png_debug(1, "in png_free_data");481482if (png_ptr == NULL || info_ptr == NULL)483return;484485#ifdef PNG_TEXT_SUPPORTED486/* Free text item num or (if num == -1) all text items */487if (info_ptr->text != NULL &&488((mask & PNG_FREE_TEXT) & info_ptr->free_me) != 0)489{490if (num != -1)491{492png_free(png_ptr, info_ptr->text[num].key);493info_ptr->text[num].key = NULL;494}495496else497{498int i;499500for (i = 0; i < info_ptr->num_text; i++)501png_free(png_ptr, info_ptr->text[i].key);502503png_free(png_ptr, info_ptr->text);504info_ptr->text = NULL;505info_ptr->num_text = 0;506info_ptr->max_text = 0;507}508}509#endif510511#ifdef PNG_tRNS_SUPPORTED512/* Free any tRNS entry */513if (((mask & PNG_FREE_TRNS) & info_ptr->free_me) != 0)514{515info_ptr->valid &= ~PNG_INFO_tRNS;516png_free(png_ptr, info_ptr->trans_alpha);517info_ptr->trans_alpha = NULL;518info_ptr->num_trans = 0;519}520#endif521522#ifdef PNG_sCAL_SUPPORTED523/* Free any sCAL entry */524if (((mask & PNG_FREE_SCAL) & info_ptr->free_me) != 0)525{526png_free(png_ptr, info_ptr->scal_s_width);527png_free(png_ptr, info_ptr->scal_s_height);528info_ptr->scal_s_width = NULL;529info_ptr->scal_s_height = NULL;530info_ptr->valid &= ~PNG_INFO_sCAL;531}532#endif533534#ifdef PNG_pCAL_SUPPORTED535/* Free any pCAL entry */536if (((mask & PNG_FREE_PCAL) & info_ptr->free_me) != 0)537{538png_free(png_ptr, info_ptr->pcal_purpose);539png_free(png_ptr, info_ptr->pcal_units);540info_ptr->pcal_purpose = NULL;541info_ptr->pcal_units = NULL;542543if (info_ptr->pcal_params != NULL)544{545int i;546547for (i = 0; i < info_ptr->pcal_nparams; i++)548png_free(png_ptr, info_ptr->pcal_params[i]);549550png_free(png_ptr, info_ptr->pcal_params);551info_ptr->pcal_params = NULL;552}553info_ptr->valid &= ~PNG_INFO_pCAL;554}555#endif556557#ifdef PNG_iCCP_SUPPORTED558/* Free any profile entry */559if (((mask & PNG_FREE_ICCP) & info_ptr->free_me) != 0)560{561png_free(png_ptr, info_ptr->iccp_name);562png_free(png_ptr, info_ptr->iccp_profile);563info_ptr->iccp_name = NULL;564info_ptr->iccp_profile = NULL;565info_ptr->valid &= ~PNG_INFO_iCCP;566}567#endif568569#ifdef PNG_sPLT_SUPPORTED570/* Free a given sPLT entry, or (if num == -1) all sPLT entries */571if (info_ptr->splt_palettes != NULL &&572((mask & PNG_FREE_SPLT) & info_ptr->free_me) != 0)573{574if (num != -1)575{576png_free(png_ptr, info_ptr->splt_palettes[num].name);577png_free(png_ptr, info_ptr->splt_palettes[num].entries);578info_ptr->splt_palettes[num].name = NULL;579info_ptr->splt_palettes[num].entries = NULL;580}581582else583{584int i;585586for (i = 0; i < info_ptr->splt_palettes_num; i++)587{588png_free(png_ptr, info_ptr->splt_palettes[i].name);589png_free(png_ptr, info_ptr->splt_palettes[i].entries);590}591592png_free(png_ptr, info_ptr->splt_palettes);593info_ptr->splt_palettes = NULL;594info_ptr->splt_palettes_num = 0;595info_ptr->valid &= ~PNG_INFO_sPLT;596}597}598#endif599600#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED601if (info_ptr->unknown_chunks != NULL &&602((mask & PNG_FREE_UNKN) & info_ptr->free_me) != 0)603{604if (num != -1)605{606png_free(png_ptr, info_ptr->unknown_chunks[num].data);607info_ptr->unknown_chunks[num].data = NULL;608}609610else611{612int i;613614for (i = 0; i < info_ptr->unknown_chunks_num; i++)615png_free(png_ptr, info_ptr->unknown_chunks[i].data);616617png_free(png_ptr, info_ptr->unknown_chunks);618info_ptr->unknown_chunks = NULL;619info_ptr->unknown_chunks_num = 0;620}621}622#endif623624#ifdef PNG_eXIf_SUPPORTED625/* Free any eXIf entry */626if (((mask & PNG_FREE_EXIF) & info_ptr->free_me) != 0)627{628if (info_ptr->exif)629{630png_free(png_ptr, info_ptr->exif);631info_ptr->exif = NULL;632}633info_ptr->valid &= ~PNG_INFO_eXIf;634}635#endif636637#ifdef PNG_hIST_SUPPORTED638/* Free any hIST entry */639if (((mask & PNG_FREE_HIST) & info_ptr->free_me) != 0)640{641png_free(png_ptr, info_ptr->hist);642info_ptr->hist = NULL;643info_ptr->valid &= ~PNG_INFO_hIST;644}645#endif646647/* Free any PLTE entry that was internally allocated */648if (((mask & PNG_FREE_PLTE) & info_ptr->free_me) != 0)649{650png_free(png_ptr, info_ptr->palette);651info_ptr->palette = NULL;652info_ptr->valid &= ~PNG_INFO_PLTE;653info_ptr->num_palette = 0;654}655656#ifdef PNG_INFO_IMAGE_SUPPORTED657/* Free any image bits attached to the info structure */658if (((mask & PNG_FREE_ROWS) & info_ptr->free_me) != 0)659{660if (info_ptr->row_pointers != NULL)661{662png_uint_32 row;663for (row = 0; row < info_ptr->height; row++)664png_free(png_ptr, info_ptr->row_pointers[row]);665666png_free(png_ptr, info_ptr->row_pointers);667info_ptr->row_pointers = NULL;668}669info_ptr->valid &= ~PNG_INFO_IDAT;670}671#endif672673if (num != -1)674mask &= ~PNG_FREE_MUL;675676info_ptr->free_me &= ~mask;677}678#endif /* READ || WRITE */679680/* This function returns a pointer to the io_ptr associated with the user681* functions. The application should free any memory associated with this682* pointer before png_write_destroy() or png_read_destroy() are called.683*/684png_voidp PNGAPI685png_get_io_ptr(png_const_structrp png_ptr)686{687if (png_ptr == NULL)688return NULL;689690return png_ptr->io_ptr;691}692693#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)694# ifdef PNG_STDIO_SUPPORTED695/* Initialize the default input/output functions for the PNG file. If you696* use your own read or write routines, you can call either png_set_read_fn()697* or png_set_write_fn() instead of png_init_io(). If you have defined698* PNG_NO_STDIO or otherwise disabled PNG_STDIO_SUPPORTED, you must use a699* function of your own because "FILE *" isn't necessarily available.700*/701void PNGAPI702png_init_io(png_structrp png_ptr, FILE *fp)703{704png_debug(1, "in png_init_io");705706if (png_ptr == NULL)707return;708709png_ptr->io_ptr = (png_voidp)fp;710}711# endif712713# ifdef PNG_SAVE_INT_32_SUPPORTED714/* PNG signed integers are saved in 32-bit 2's complement format. ANSI C-90715* defines a cast of a signed integer to an unsigned integer either to preserve716* the value, if it is positive, or to calculate:717*718* (UNSIGNED_MAX+1) + integer719*720* Where UNSIGNED_MAX is the appropriate maximum unsigned value, so when the721* negative integral value is added the result will be an unsigned value722* corresponding to the 2's complement representation.723*/724void PNGAPI725png_save_int_32(png_bytep buf, png_int_32 i)726{727png_save_uint_32(buf, (png_uint_32)i);728}729# endif730731# ifdef PNG_TIME_RFC1123_SUPPORTED732/* Convert the supplied time into an RFC 1123 string suitable for use in733* a "Creation Time" or other text-based time string.734*/735int PNGAPI736png_convert_to_rfc1123_buffer(char out[29], png_const_timep ptime)737{738static const char short_months[12][4] =739{"Jan", "Feb", "Mar", "Apr", "May", "Jun",740"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};741742if (out == NULL)743return 0;744745if (ptime->year > 9999 /* RFC1123 limitation */ ||746ptime->month == 0 || ptime->month > 12 ||747ptime->day == 0 || ptime->day > 31 ||748ptime->hour > 23 || ptime->minute > 59 ||749ptime->second > 60)750return 0;751752{753size_t pos = 0;754char number_buf[5] = {0, 0, 0, 0, 0}; /* enough for a four-digit year */755756# define APPEND_STRING(string) pos = png_safecat(out, 29, pos, (string))757# define APPEND_NUMBER(format, value)\758APPEND_STRING(PNG_FORMAT_NUMBER(number_buf, format, (value)))759# define APPEND(ch) if (pos < 28) out[pos++] = (ch)760761APPEND_NUMBER(PNG_NUMBER_FORMAT_u, (unsigned)ptime->day);762APPEND(' ');763APPEND_STRING(short_months[(ptime->month - 1)]);764APPEND(' ');765APPEND_NUMBER(PNG_NUMBER_FORMAT_u, ptime->year);766APPEND(' ');767APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->hour);768APPEND(':');769APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->minute);770APPEND(':');771APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->second);772APPEND_STRING(" +0000"); /* This reliably terminates the buffer */773PNG_UNUSED (pos)774775# undef APPEND776# undef APPEND_NUMBER777# undef APPEND_STRING778}779780return 1;781}782783# if PNG_LIBPNG_VER < 10700784/* To do: remove the following from libpng-1.7 */785/* Original API that uses a private buffer in png_struct.786* Deprecated because it causes png_struct to carry a spurious temporary787* buffer (png_struct::time_buffer), better to have the caller pass this in.788*/789png_const_charp PNGAPI790png_convert_to_rfc1123(png_structrp png_ptr, png_const_timep ptime)791{792if (png_ptr != NULL)793{794/* The only failure above if png_ptr != NULL is from an invalid ptime */795if (png_convert_to_rfc1123_buffer(png_ptr->time_buffer, ptime) == 0)796png_warning(png_ptr, "Ignoring invalid time value");797798else799return png_ptr->time_buffer;800}801802return NULL;803}804# endif /* LIBPNG_VER < 10700 */805# endif /* TIME_RFC1123 */806807#endif /* READ || WRITE */808809png_const_charp PNGAPI810png_get_copyright(png_const_structrp png_ptr)811{812PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */813#ifdef PNG_STRING_COPYRIGHT814return PNG_STRING_COPYRIGHT815#else816return PNG_STRING_NEWLINE \817"libpng version 1.6.48" PNG_STRING_NEWLINE \818"Copyright (c) 2018-2025 Cosmin Truta" PNG_STRING_NEWLINE \819"Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson" \820PNG_STRING_NEWLINE \821"Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \822"Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \823PNG_STRING_NEWLINE;824#endif825}826827/* The following return the library version as a short string in the828* format 1.0.0 through 99.99.99zz. To get the version of *.h files829* used with your application, print out PNG_LIBPNG_VER_STRING, which830* is defined in png.h.831* Note: now there is no difference between png_get_libpng_ver() and832* png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,833* it is guaranteed that png.c uses the correct version of png.h.834*/835png_const_charp PNGAPI836png_get_libpng_ver(png_const_structrp png_ptr)837{838/* Version of *.c files used when building libpng */839return png_get_header_ver(png_ptr);840}841842png_const_charp PNGAPI843png_get_header_ver(png_const_structrp png_ptr)844{845/* Version of *.h files used when building libpng */846PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */847return PNG_LIBPNG_VER_STRING;848}849850png_const_charp PNGAPI851png_get_header_version(png_const_structrp png_ptr)852{853/* Returns longer string containing both version and date */854PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */855#ifdef __STDC__856return PNG_HEADER_VERSION_STRING857# ifndef PNG_READ_SUPPORTED858" (NO READ SUPPORT)"859# endif860PNG_STRING_NEWLINE;861#else862return PNG_HEADER_VERSION_STRING;863#endif864}865866#ifdef PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED867/* NOTE: this routine is not used internally! */868/* Build a grayscale palette. Palette is assumed to be 1 << bit_depth869* large of png_color. This lets grayscale images be treated as870* paletted. Most useful for gamma correction and simplification871* of code. This API is not used internally.872*/873void PNGAPI874png_build_grayscale_palette(int bit_depth, png_colorp palette)875{876int num_palette;877int color_inc;878int i;879int v;880881png_debug(1, "in png_do_build_grayscale_palette");882883if (palette == NULL)884return;885886switch (bit_depth)887{888case 1:889num_palette = 2;890color_inc = 0xff;891break;892893case 2:894num_palette = 4;895color_inc = 0x55;896break;897898case 4:899num_palette = 16;900color_inc = 0x11;901break;902903case 8:904num_palette = 256;905color_inc = 1;906break;907908default:909num_palette = 0;910color_inc = 0;911break;912}913914for (i = 0, v = 0; i < num_palette; i++, v += color_inc)915{916palette[i].red = (png_byte)(v & 0xff);917palette[i].green = (png_byte)(v & 0xff);918palette[i].blue = (png_byte)(v & 0xff);919}920}921#endif922923#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED924int PNGAPI925png_handle_as_unknown(png_const_structrp png_ptr, png_const_bytep chunk_name)926{927/* Check chunk_name and return "keep" value if it's on the list, else 0 */928png_const_bytep p, p_end;929930if (png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list == 0)931return PNG_HANDLE_CHUNK_AS_DEFAULT;932933p_end = png_ptr->chunk_list;934p = p_end + png_ptr->num_chunk_list*5; /* beyond end */935936/* The code is the fifth byte after each four byte string. Historically this937* code was always searched from the end of the list, this is no longer938* necessary because the 'set' routine handles duplicate entries correctly.939*/940do /* num_chunk_list > 0, so at least one */941{942p -= 5;943944if (memcmp(chunk_name, p, 4) == 0)945return p[4];946}947while (p > p_end);948949/* This means that known chunks should be processed and unknown chunks should950* be handled according to the value of png_ptr->unknown_default; this can be951* confusing because, as a result, there are two levels of defaulting for952* unknown chunks.953*/954return PNG_HANDLE_CHUNK_AS_DEFAULT;955}956957#if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) ||\958defined(PNG_HANDLE_AS_UNKNOWN_SUPPORTED)959int /* PRIVATE */960png_chunk_unknown_handling(png_const_structrp png_ptr, png_uint_32 chunk_name)961{962png_byte chunk_string[5];963964PNG_CSTRING_FROM_CHUNK(chunk_string, chunk_name);965return png_handle_as_unknown(png_ptr, chunk_string);966}967#endif /* READ_UNKNOWN_CHUNKS || HANDLE_AS_UNKNOWN */968#endif /* SET_UNKNOWN_CHUNKS */969970#ifdef PNG_READ_SUPPORTED971/* This function, added to libpng-1.0.6g, is untested. */972int PNGAPI973png_reset_zstream(png_structrp png_ptr)974{975if (png_ptr == NULL)976return Z_STREAM_ERROR;977978/* WARNING: this resets the window bits to the maximum! */979return inflateReset(&png_ptr->zstream);980}981#endif /* READ */982983/* This function was added to libpng-1.0.7 */984png_uint_32 PNGAPI985png_access_version_number(void)986{987/* Version of *.c files used when building libpng */988return (png_uint_32)PNG_LIBPNG_VER;989}990991#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)992/* Ensure that png_ptr->zstream.msg holds some appropriate error message string.993* If it doesn't 'ret' is used to set it to something appropriate, even in cases994* like Z_OK or Z_STREAM_END where the error code is apparently a success code.995*/996void /* PRIVATE */997png_zstream_error(png_structrp png_ptr, int ret)998{999/* Translate 'ret' into an appropriate error string, priority is given to the1000* one in zstream if set. This always returns a string, even in cases like1001* Z_OK or Z_STREAM_END where the error code is a success code.1002*/1003if (png_ptr->zstream.msg == NULL) switch (ret)1004{1005default:1006case Z_OK:1007png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected zlib return code");1008break;10091010case Z_STREAM_END:1011/* Normal exit */1012png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected end of LZ stream");1013break;10141015case Z_NEED_DICT:1016/* This means the deflate stream did not have a dictionary; this1017* indicates a bogus PNG.1018*/1019png_ptr->zstream.msg = PNGZ_MSG_CAST("missing LZ dictionary");1020break;10211022case Z_ERRNO:1023/* gz APIs only: should not happen */1024png_ptr->zstream.msg = PNGZ_MSG_CAST("zlib IO error");1025break;10261027case Z_STREAM_ERROR:1028/* internal libpng error */1029png_ptr->zstream.msg = PNGZ_MSG_CAST("bad parameters to zlib");1030break;10311032case Z_DATA_ERROR:1033png_ptr->zstream.msg = PNGZ_MSG_CAST("damaged LZ stream");1034break;10351036case Z_MEM_ERROR:1037png_ptr->zstream.msg = PNGZ_MSG_CAST("insufficient memory");1038break;10391040case Z_BUF_ERROR:1041/* End of input or output; not a problem if the caller is doing1042* incremental read or write.1043*/1044png_ptr->zstream.msg = PNGZ_MSG_CAST("truncated");1045break;10461047case Z_VERSION_ERROR:1048png_ptr->zstream.msg = PNGZ_MSG_CAST("unsupported zlib version");1049break;10501051case PNG_UNEXPECTED_ZLIB_RETURN:1052/* Compile errors here mean that zlib now uses the value co-opted in1053* pngpriv.h for PNG_UNEXPECTED_ZLIB_RETURN; update the switch above1054* and change pngpriv.h. Note that this message is "... return",1055* whereas the default/Z_OK one is "... return code".1056*/1057png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected zlib return");1058break;1059}1060}10611062#ifdef PNG_COLORSPACE_SUPPORTED1063static png_int_321064png_fp_add(png_int_32 addend0, png_int_32 addend1, int *error)1065{1066/* Safely add two fixed point values setting an error flag and returning 0.51067* on overflow.1068* IMPLEMENTATION NOTE: ANSI requires signed overflow not to occur, therefore1069* relying on addition of two positive values producing a negative one is not1070* safe.1071*/1072if (addend0 > 0)1073{1074if (0x7fffffff - addend0 >= addend1)1075return addend0+addend1;1076}1077else if (addend0 < 0)1078{1079if (-0x7fffffff - addend0 <= addend1)1080return addend0+addend1;1081}1082else1083return addend1;10841085*error = 1;1086return PNG_FP_1/2;1087}10881089static png_int_321090png_fp_sub(png_int_32 addend0, png_int_32 addend1, int *error)1091{1092/* As above but calculate addend0-addend1. */1093if (addend1 > 0)1094{1095if (-0x7fffffff + addend1 <= addend0)1096return addend0-addend1;1097}1098else if (addend1 < 0)1099{1100if (0x7fffffff + addend1 >= addend0)1101return addend0-addend1;1102}1103else1104return addend0;11051106*error = 1;1107return PNG_FP_1/2;1108}11091110static int1111png_safe_add(png_int_32 *addend0_and_result, png_int_32 addend1,1112png_int_32 addend2)1113{1114/* Safely add three integers. Returns 0 on success, 1 on overflow. Does not1115* set the result on overflow.1116*/1117int error = 0;1118int result = png_fp_add(*addend0_and_result,1119png_fp_add(addend1, addend2, &error),1120&error);1121if (!error) *addend0_and_result = result;1122return error;1123}11241125/* Added at libpng-1.5.5 to support read and write of true CIEXYZ values for1126* cHRM, as opposed to using chromaticities. These internal APIs return1127* non-zero on a parameter error. The X, Y and Z values are required to be1128* positive and less than 1.0.1129*/1130int /* PRIVATE */1131png_xy_from_XYZ(png_xy *xy, const png_XYZ *XYZ)1132{1133/* NOTE: returns 0 on success, 1 means error. */1134png_int_32 d, dred, dgreen, dblue, dwhite, whiteX, whiteY;11351136/* 'd' in each of the blocks below is just X+Y+Z for each component,1137* x, y and z are X,Y,Z/(X+Y+Z).1138*/1139d = XYZ->red_X;1140if (png_safe_add(&d, XYZ->red_Y, XYZ->red_Z))1141return 1;1142dred = d;1143if (png_muldiv(&xy->redx, XYZ->red_X, PNG_FP_1, dred) == 0)1144return 1;1145if (png_muldiv(&xy->redy, XYZ->red_Y, PNG_FP_1, dred) == 0)1146return 1;11471148d = XYZ->green_X;1149if (png_safe_add(&d, XYZ->green_Y, XYZ->green_Z))1150return 1;1151dgreen = d;1152if (png_muldiv(&xy->greenx, XYZ->green_X, PNG_FP_1, dgreen) == 0)1153return 1;1154if (png_muldiv(&xy->greeny, XYZ->green_Y, PNG_FP_1, dgreen) == 0)1155return 1;11561157d = XYZ->blue_X;1158if (png_safe_add(&d, XYZ->blue_Y, XYZ->blue_Z))1159return 1;1160dblue = d;1161if (png_muldiv(&xy->bluex, XYZ->blue_X, PNG_FP_1, dblue) == 0)1162return 1;1163if (png_muldiv(&xy->bluey, XYZ->blue_Y, PNG_FP_1, dblue) == 0)1164return 1;11651166/* The reference white is simply the sum of the end-point (X,Y,Z) vectors so1167* the fillowing calculates (X+Y+Z) of the reference white (media white,1168* encoding white) itself:1169*/1170d = dblue;1171if (png_safe_add(&d, dred, dgreen))1172return 1;1173dwhite = d;11741175/* Find the white X,Y values from the sum of the red, green and blue X,Y1176* values.1177*/1178d = XYZ->red_X;1179if (png_safe_add(&d, XYZ->green_X, XYZ->blue_X))1180return 1;1181whiteX = d;11821183d = XYZ->red_Y;1184if (png_safe_add(&d, XYZ->green_Y, XYZ->blue_Y))1185return 1;1186whiteY = d;11871188if (png_muldiv(&xy->whitex, whiteX, PNG_FP_1, dwhite) == 0)1189return 1;1190if (png_muldiv(&xy->whitey, whiteY, PNG_FP_1, dwhite) == 0)1191return 1;11921193return 0;1194}11951196int /* PRIVATE */1197png_XYZ_from_xy(png_XYZ *XYZ, const png_xy *xy)1198{1199/* NOTE: returns 0 on success, 1 means error. */1200png_fixed_point red_inverse, green_inverse, blue_scale;1201png_fixed_point left, right, denominator;12021203/* Check xy and, implicitly, z. Note that wide gamut color spaces typically1204* have end points with 0 tristimulus values (these are impossible end1205* points, but they are used to cover the possible colors). We check1206* xy->whitey against 5, not 0, to avoid a possible integer overflow.1207*1208* The limits here will *not* accept ACES AP0, where bluey is -77001209* (-0.0770) because the PNG spec itself requires the xy values to be1210* unsigned. whitey is also required to be 5 or more to avoid overflow.1211*1212* Instead the upper limits have been relaxed to accomodate ACES AP1 where1213* redz ends up as -600 (-0.006). ProPhotoRGB was already "in range."1214* The new limit accomodates the AP0 and AP1 ranges for z but not AP0 redy.1215*/1216const png_fixed_point fpLimit = PNG_FP_1+(PNG_FP_1/10);1217if (xy->redx < 0 || xy->redx > fpLimit) return 1;1218if (xy->redy < 0 || xy->redy > fpLimit-xy->redx) return 1;1219if (xy->greenx < 0 || xy->greenx > fpLimit) return 1;1220if (xy->greeny < 0 || xy->greeny > fpLimit-xy->greenx) return 1;1221if (xy->bluex < 0 || xy->bluex > fpLimit) return 1;1222if (xy->bluey < 0 || xy->bluey > fpLimit-xy->bluex) return 1;1223if (xy->whitex < 0 || xy->whitex > fpLimit) return 1;1224if (xy->whitey < 5 || xy->whitey > fpLimit-xy->whitex) return 1;12251226/* The reverse calculation is more difficult because the original tristimulus1227* value had 9 independent values (red,green,blue)x(X,Y,Z) however only 81228* derived values were recorded in the cHRM chunk;1229* (red,green,blue,white)x(x,y). This loses one degree of freedom and1230* therefore an arbitrary ninth value has to be introduced to undo the1231* original transformations.1232*1233* Think of the original end-points as points in (X,Y,Z) space. The1234* chromaticity values (c) have the property:1235*1236* C1237* c = ---------1238* X + Y + Z1239*1240* For each c (x,y,z) from the corresponding original C (X,Y,Z). Thus the1241* three chromaticity values (x,y,z) for each end-point obey the1242* relationship:1243*1244* x + y + z = 11245*1246* This describes the plane in (X,Y,Z) space that intersects each axis at the1247* value 1.0; call this the chromaticity plane. Thus the chromaticity1248* calculation has scaled each end-point so that it is on the x+y+z=1 plane1249* and chromaticity is the intersection of the vector from the origin to the1250* (X,Y,Z) value with the chromaticity plane.1251*1252* To fully invert the chromaticity calculation we would need the three1253* end-point scale factors, (red-scale, green-scale, blue-scale), but these1254* were not recorded. Instead we calculated the reference white (X,Y,Z) and1255* recorded the chromaticity of this. The reference white (X,Y,Z) would have1256* given all three of the scale factors since:1257*1258* color-C = color-c * color-scale1259* white-C = red-C + green-C + blue-C1260* = red-c*red-scale + green-c*green-scale + blue-c*blue-scale1261*1262* But cHRM records only white-x and white-y, so we have lost the white scale1263* factor:1264*1265* white-C = white-c*white-scale1266*1267* To handle this the inverse transformation makes an arbitrary assumption1268* about white-scale:1269*1270* Assume: white-Y = 1.01271* Hence: white-scale = 1/white-y1272* Or: red-Y + green-Y + blue-Y = 1.01273*1274* Notice the last statement of the assumption gives an equation in three of1275* the nine values we want to calculate. 8 more equations come from the1276* above routine as summarised at the top above (the chromaticity1277* calculation):1278*1279* Given: color-x = color-X / (color-X + color-Y + color-Z)1280* Hence: (color-x - 1)*color-X + color.x*color-Y + color.x*color-Z = 01281*1282* This is 9 simultaneous equations in the 9 variables "color-C" and can be1283* solved by Cramer's rule. Cramer's rule requires calculating 10 9x9 matrix1284* determinants, however this is not as bad as it seems because only 28 of1285* the total of 90 terms in the various matrices are non-zero. Nevertheless1286* Cramer's rule is notoriously numerically unstable because the determinant1287* calculation involves the difference of large, but similar, numbers. It is1288* difficult to be sure that the calculation is stable for real world values1289* and it is certain that it becomes unstable where the end points are close1290* together.1291*1292* So this code uses the perhaps slightly less optimal but more1293* understandable and totally obvious approach of calculating color-scale.1294*1295* This algorithm depends on the precision in white-scale and that is1296* (1/white-y), so we can immediately see that as white-y approaches 0 the1297* accuracy inherent in the cHRM chunk drops off substantially.1298*1299* libpng arithmetic: a simple inversion of the above equations1300* ------------------------------------------------------------1301*1302* white_scale = 1/white-y1303* white-X = white-x * white-scale1304* white-Y = 1.01305* white-Z = (1 - white-x - white-y) * white_scale1306*1307* white-C = red-C + green-C + blue-C1308* = red-c*red-scale + green-c*green-scale + blue-c*blue-scale1309*1310* This gives us three equations in (red-scale,green-scale,blue-scale) where1311* all the coefficients are now known:1312*1313* red-x*red-scale + green-x*green-scale + blue-x*blue-scale1314* = white-x/white-y1315* red-y*red-scale + green-y*green-scale + blue-y*blue-scale = 11316* red-z*red-scale + green-z*green-scale + blue-z*blue-scale1317* = (1 - white-x - white-y)/white-y1318*1319* In the last equation color-z is (1 - color-x - color-y) so we can add all1320* three equations together to get an alternative third:1321*1322* red-scale + green-scale + blue-scale = 1/white-y = white-scale1323*1324* So now we have a Cramer's rule solution where the determinants are just1325* 3x3 - far more tractible. Unfortunately 3x3 determinants still involve1326* multiplication of three coefficients so we can't guarantee to avoid1327* overflow in the libpng fixed point representation. Using Cramer's rule in1328* floating point is probably a good choice here, but it's not an option for1329* fixed point. Instead proceed to simplify the first two equations by1330* eliminating what is likely to be the largest value, blue-scale:1331*1332* blue-scale = white-scale - red-scale - green-scale1333*1334* Hence:1335*1336* (red-x - blue-x)*red-scale + (green-x - blue-x)*green-scale =1337* (white-x - blue-x)*white-scale1338*1339* (red-y - blue-y)*red-scale + (green-y - blue-y)*green-scale =1340* 1 - blue-y*white-scale1341*1342* And now we can trivially solve for (red-scale,green-scale):1343*1344* green-scale =1345* (white-x - blue-x)*white-scale - (red-x - blue-x)*red-scale1346* -----------------------------------------------------------1347* green-x - blue-x1348*1349* red-scale =1350* 1 - blue-y*white-scale - (green-y - blue-y) * green-scale1351* ---------------------------------------------------------1352* red-y - blue-y1353*1354* Hence:1355*1356* red-scale =1357* ( (green-x - blue-x) * (white-y - blue-y) -1358* (green-y - blue-y) * (white-x - blue-x) ) / white-y1359* -------------------------------------------------------------------------1360* (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)1361*1362* green-scale =1363* ( (red-y - blue-y) * (white-x - blue-x) -1364* (red-x - blue-x) * (white-y - blue-y) ) / white-y1365* -------------------------------------------------------------------------1366* (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)1367*1368* Accuracy:1369* The input values have 5 decimal digits of accuracy.1370*1371* In the previous implementation the values were all in the range 0 < value1372* < 1, so simple products are in the same range but may need up to 101373* decimal digits to preserve the original precision and avoid underflow.1374* Because we are using a 32-bit signed representation we cannot match this;1375* the best is a little over 9 decimal digits, less than 10.1376*1377* This range has now been extended to allow values up to 1.1, or 110,000 in1378* fixed point.1379*1380* The approach used here is to preserve the maximum precision within the1381* signed representation. Because the red-scale calculation above uses the1382* difference between two products of values that must be in the range1383* -1.1..+1.1 it is sufficient to divide the product by 8;1384* ceil(121,000/32767*2). The factor is irrelevant in the calculation1385* because it is applied to both numerator and denominator.1386*1387* Note that the values of the differences of the products of the1388* chromaticities in the above equations tend to be small, for example for1389* the sRGB chromaticities they are:1390*1391* red numerator: -0.047511392* green numerator: -0.087881393* denominator: -0.2241 (without white-y multiplication)1394*1395* The resultant Y coefficients from the chromaticities of some widely used1396* color space definitions are (to 15 decimal places):1397*1398* sRGB1399* 0.212639005871510 0.715168678767756 0.0721923153607341400* Kodak ProPhoto1401* 0.288071128229293 0.711843217810102 0.0000856539606051402* Adobe RGB1403* 0.297344975250536 0.627363566255466 0.0752914584939981404* Adobe Wide Gamut RGB1405* 0.258728243040113 0.724682314948566 0.0165894420113211406*/1407{1408int error = 0;14091410/* By the argument above overflow should be impossible here, however the1411* code now simply returns a failure code. The xy subtracts in the1412* arguments to png_muldiv are *not* checked for overflow because the1413* checks at the start guarantee they are in the range 0..110000 and1414* png_fixed_point is a 32-bit signed number.1415*/1416if (png_muldiv(&left, xy->greenx-xy->bluex, xy->redy - xy->bluey, 8) == 0)1417return 1;1418if (png_muldiv(&right, xy->greeny-xy->bluey, xy->redx - xy->bluex, 8) ==14190)1420return 1;1421denominator = png_fp_sub(left, right, &error);1422if (error) return 1;14231424/* Now find the red numerator. */1425if (png_muldiv(&left, xy->greenx-xy->bluex, xy->whitey-xy->bluey, 8) == 0)1426return 1;1427if (png_muldiv(&right, xy->greeny-xy->bluey, xy->whitex-xy->bluex, 8) ==14280)1429return 1;14301431/* Overflow is possible here and it indicates an extreme set of PNG cHRM1432* chunk values. This calculation actually returns the reciprocal of the1433* scale value because this allows us to delay the multiplication of1434* white-y into the denominator, which tends to produce a small number.1435*/1436if (png_muldiv(&red_inverse, xy->whitey, denominator,1437png_fp_sub(left, right, &error)) == 0 || error ||1438red_inverse <= xy->whitey /* r+g+b scales = white scale */)1439return 1;14401441/* Similarly for green_inverse: */1442if (png_muldiv(&left, xy->redy-xy->bluey, xy->whitex-xy->bluex, 8) == 0)1443return 1;1444if (png_muldiv(&right, xy->redx-xy->bluex, xy->whitey-xy->bluey, 8) == 0)1445return 1;1446if (png_muldiv(&green_inverse, xy->whitey, denominator,1447png_fp_sub(left, right, &error)) == 0 || error ||1448green_inverse <= xy->whitey)1449return 1;14501451/* And the blue scale, the checks above guarantee this can't overflow but1452* it can still produce 0 for extreme cHRM values.1453*/1454blue_scale = png_fp_sub(png_fp_sub(png_reciprocal(xy->whitey),1455png_reciprocal(red_inverse), &error),1456png_reciprocal(green_inverse), &error);1457if (error || blue_scale <= 0)1458return 1;1459}14601461/* And fill in the png_XYZ. Again the subtracts are safe because of the1462* checks on the xy values at the start (the subtracts just calculate the1463* corresponding z values.)1464*/1465if (png_muldiv(&XYZ->red_X, xy->redx, PNG_FP_1, red_inverse) == 0)1466return 1;1467if (png_muldiv(&XYZ->red_Y, xy->redy, PNG_FP_1, red_inverse) == 0)1468return 1;1469if (png_muldiv(&XYZ->red_Z, PNG_FP_1 - xy->redx - xy->redy, PNG_FP_1,1470red_inverse) == 0)1471return 1;14721473if (png_muldiv(&XYZ->green_X, xy->greenx, PNG_FP_1, green_inverse) == 0)1474return 1;1475if (png_muldiv(&XYZ->green_Y, xy->greeny, PNG_FP_1, green_inverse) == 0)1476return 1;1477if (png_muldiv(&XYZ->green_Z, PNG_FP_1 - xy->greenx - xy->greeny, PNG_FP_1,1478green_inverse) == 0)1479return 1;14801481if (png_muldiv(&XYZ->blue_X, xy->bluex, blue_scale, PNG_FP_1) == 0)1482return 1;1483if (png_muldiv(&XYZ->blue_Y, xy->bluey, blue_scale, PNG_FP_1) == 0)1484return 1;1485if (png_muldiv(&XYZ->blue_Z, PNG_FP_1 - xy->bluex - xy->bluey, blue_scale,1486PNG_FP_1) == 0)1487return 1;14881489return 0; /*success*/1490}1491#endif /* COLORSPACE */14921493#ifdef PNG_READ_iCCP_SUPPORTED1494/* Error message generation */1495static char1496png_icc_tag_char(png_uint_32 byte)1497{1498byte &= 0xff;1499if (byte >= 32 && byte <= 126)1500return (char)byte;1501else1502return '?';1503}15041505static void1506png_icc_tag_name(char *name, png_uint_32 tag)1507{1508name[0] = '\'';1509name[1] = png_icc_tag_char(tag >> 24);1510name[2] = png_icc_tag_char(tag >> 16);1511name[3] = png_icc_tag_char(tag >> 8);1512name[4] = png_icc_tag_char(tag );1513name[5] = '\'';1514}15151516static int1517is_ICC_signature_char(png_alloc_size_t it)1518{1519return it == 32 || (it >= 48 && it <= 57) || (it >= 65 && it <= 90) ||1520(it >= 97 && it <= 122);1521}15221523static int1524is_ICC_signature(png_alloc_size_t it)1525{1526return is_ICC_signature_char(it >> 24) /* checks all the top bits */ &&1527is_ICC_signature_char((it >> 16) & 0xff) &&1528is_ICC_signature_char((it >> 8) & 0xff) &&1529is_ICC_signature_char(it & 0xff);1530}15311532static int1533png_icc_profile_error(png_const_structrp png_ptr, png_const_charp name,1534png_alloc_size_t value, png_const_charp reason)1535{1536size_t pos;1537char message[196]; /* see below for calculation */15381539pos = png_safecat(message, (sizeof message), 0, "profile '"); /* 9 chars */1540pos = png_safecat(message, pos+79, pos, name); /* Truncate to 79 chars */1541pos = png_safecat(message, (sizeof message), pos, "': "); /* +2 = 90 */1542if (is_ICC_signature(value) != 0)1543{1544/* So 'value' is at most 4 bytes and the following cast is safe */1545png_icc_tag_name(message+pos, (png_uint_32)value);1546pos += 6; /* total +8; less than the else clause */1547message[pos++] = ':';1548message[pos++] = ' ';1549}1550# ifdef PNG_WARNINGS_SUPPORTED1551else1552{1553char number[PNG_NUMBER_BUFFER_SIZE]; /* +24 = 114 */15541555pos = png_safecat(message, (sizeof message), pos,1556png_format_number(number, number+(sizeof number),1557PNG_NUMBER_FORMAT_x, value));1558pos = png_safecat(message, (sizeof message), pos, "h: "); /* +2 = 116 */1559}1560# endif1561/* The 'reason' is an arbitrary message, allow +79 maximum 195 */1562pos = png_safecat(message, (sizeof message), pos, reason);1563PNG_UNUSED(pos)15641565png_chunk_benign_error(png_ptr, message);15661567return 0;1568}15691570/* Encoded value of D50 as an ICC XYZNumber. From the ICC 2010 spec the value1571* is XYZ(0.9642,1.0,0.8249), which scales to:1572*1573* (63189.8112, 65536, 54060.6464)1574*/1575static const png_byte D50_nCIEXYZ[12] =1576{ 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d };15771578static int /* bool */1579icc_check_length(png_const_structrp png_ptr, png_const_charp name,1580png_uint_32 profile_length)1581{1582if (profile_length < 132)1583return png_icc_profile_error(png_ptr, name, profile_length, "too short");1584return 1;1585}15861587int /* PRIVATE */1588png_icc_check_length(png_const_structrp png_ptr, png_const_charp name,1589png_uint_32 profile_length)1590{1591if (!icc_check_length(png_ptr, name, profile_length))1592return 0;15931594/* This needs to be here because the 'normal' check is in1595* png_decompress_chunk, yet this happens after the attempt to1596* png_malloc_base the required data. We only need this on read; on write1597* the caller supplies the profile buffer so libpng doesn't allocate it. See1598* the call to icc_check_length below (the write case).1599*/1600if (profile_length > png_chunk_max(png_ptr))1601return png_icc_profile_error(png_ptr, name, profile_length,1602"profile too long");16031604return 1;1605}16061607int /* PRIVATE */1608png_icc_check_header(png_const_structrp png_ptr, png_const_charp name,1609png_uint_32 profile_length,1610png_const_bytep profile/* first 132 bytes only */, int color_type)1611{1612png_uint_32 temp;16131614/* Length check; this cannot be ignored in this code because profile_length1615* is used later to check the tag table, so even if the profile seems over1616* long profile_length from the caller must be correct. The caller can fix1617* this up on read or write by just passing in the profile header length.1618*/1619temp = png_get_uint_32(profile);1620if (temp != profile_length)1621return png_icc_profile_error(png_ptr, name, temp,1622"length does not match profile");16231624temp = (png_uint_32) (*(profile+8));1625if (temp > 3 && (profile_length & 3))1626return png_icc_profile_error(png_ptr, name, profile_length,1627"invalid length");16281629temp = png_get_uint_32(profile+128); /* tag count: 12 bytes/tag */1630if (temp > 357913930 || /* (2^32-4-132)/12: maximum possible tag count */1631profile_length < 132+12*temp) /* truncated tag table */1632return png_icc_profile_error(png_ptr, name, temp,1633"tag count too large");16341635/* The 'intent' must be valid or we can't store it, ICC limits the intent to1636* 16 bits.1637*/1638temp = png_get_uint_32(profile+64);1639if (temp >= 0xffff) /* The ICC limit */1640return png_icc_profile_error(png_ptr, name, temp,1641"invalid rendering intent");16421643/* This is just a warning because the profile may be valid in future1644* versions.1645*/1646if (temp >= PNG_sRGB_INTENT_LAST)1647(void)png_icc_profile_error(png_ptr, name, temp,1648"intent outside defined range");16491650/* At this point the tag table can't be checked because it hasn't necessarily1651* been loaded; however, various header fields can be checked. These checks1652* are for values permitted by the PNG spec in an ICC profile; the PNG spec1653* restricts the profiles that can be passed in an iCCP chunk (they must be1654* appropriate to processing PNG data!)1655*/16561657/* Data checks (could be skipped). These checks must be independent of the1658* version number; however, the version number doesn't accommodate changes in1659* the header fields (just the known tags and the interpretation of the1660* data.)1661*/1662temp = png_get_uint_32(profile+36); /* signature 'ascp' */1663if (temp != 0x61637370)1664return png_icc_profile_error(png_ptr, name, temp,1665"invalid signature");16661667/* Currently the PCS illuminant/adopted white point (the computational1668* white point) are required to be D50,1669* however the profile contains a record of the illuminant so perhaps ICC1670* expects to be able to change this in the future (despite the rationale in1671* the introduction for using a fixed PCS adopted white.) Consequently the1672* following is just a warning.1673*/1674if (memcmp(profile+68, D50_nCIEXYZ, 12) != 0)1675(void)png_icc_profile_error(png_ptr, name, 0/*no tag value*/,1676"PCS illuminant is not D50");16771678/* The PNG spec requires this:1679* "If the iCCP chunk is present, the image samples conform to the colour1680* space represented by the embedded ICC profile as defined by the1681* International Color Consortium [ICC]. The colour space of the ICC profile1682* shall be an RGB colour space for colour images (PNG colour types 2, 3, and1683* 6), or a greyscale colour space for greyscale images (PNG colour types 01684* and 4)."1685*1686* This checking code ensures the embedded profile (on either read or write)1687* conforms to the specification requirements. Notice that an ICC 'gray'1688* color-space profile contains the information to transform the monochrome1689* data to XYZ or L*a*b (according to which PCS the profile uses) and this1690* should be used in preference to the standard libpng K channel replication1691* into R, G and B channels.1692*1693* Previously it was suggested that an RGB profile on grayscale data could be1694* handled. However it it is clear that using an RGB profile in this context1695* must be an error - there is no specification of what it means. Thus it is1696* almost certainly more correct to ignore the profile.1697*/1698temp = png_get_uint_32(profile+16); /* data colour space field */1699switch (temp)1700{1701case 0x52474220: /* 'RGB ' */1702if ((color_type & PNG_COLOR_MASK_COLOR) == 0)1703return png_icc_profile_error(png_ptr, name, temp,1704"RGB color space not permitted on grayscale PNG");1705break;17061707case 0x47524159: /* 'GRAY' */1708if ((color_type & PNG_COLOR_MASK_COLOR) != 0)1709return png_icc_profile_error(png_ptr, name, temp,1710"Gray color space not permitted on RGB PNG");1711break;17121713default:1714return png_icc_profile_error(png_ptr, name, temp,1715"invalid ICC profile color space");1716}17171718/* It is up to the application to check that the profile class matches the1719* application requirements; the spec provides no guidance, but it's pretty1720* weird if the profile is not scanner ('scnr'), monitor ('mntr'), printer1721* ('prtr') or 'spac' (for generic color spaces). Issue a warning in these1722* cases. Issue an error for device link or abstract profiles - these don't1723* contain the records necessary to transform the color-space to anything1724* other than the target device (and not even that for an abstract profile).1725* Profiles of these classes may not be embedded in images.1726*/1727temp = png_get_uint_32(profile+12); /* profile/device class */1728switch (temp)1729{1730case 0x73636e72: /* 'scnr' */1731case 0x6d6e7472: /* 'mntr' */1732case 0x70727472: /* 'prtr' */1733case 0x73706163: /* 'spac' */1734/* All supported */1735break;17361737case 0x61627374: /* 'abst' */1738/* May not be embedded in an image */1739return png_icc_profile_error(png_ptr, name, temp,1740"invalid embedded Abstract ICC profile");17411742case 0x6c696e6b: /* 'link' */1743/* DeviceLink profiles cannot be interpreted in a non-device specific1744* fashion, if an app uses the AToB0Tag in the profile the results are1745* undefined unless the result is sent to the intended device,1746* therefore a DeviceLink profile should not be found embedded in a1747* PNG.1748*/1749return png_icc_profile_error(png_ptr, name, temp,1750"unexpected DeviceLink ICC profile class");17511752case 0x6e6d636c: /* 'nmcl' */1753/* A NamedColor profile is also device specific, however it doesn't1754* contain an AToB0 tag that is open to misinterpretation. Almost1755* certainly it will fail the tests below.1756*/1757(void)png_icc_profile_error(png_ptr, name, temp,1758"unexpected NamedColor ICC profile class");1759break;17601761default:1762/* To allow for future enhancements to the profile accept unrecognized1763* profile classes with a warning, these then hit the test below on the1764* tag content to ensure they are backward compatible with one of the1765* understood profiles.1766*/1767(void)png_icc_profile_error(png_ptr, name, temp,1768"unrecognized ICC profile class");1769break;1770}17711772/* For any profile other than a device link one the PCS must be encoded1773* either in XYZ or Lab.1774*/1775temp = png_get_uint_32(profile+20);1776switch (temp)1777{1778case 0x58595a20: /* 'XYZ ' */1779case 0x4c616220: /* 'Lab ' */1780break;17811782default:1783return png_icc_profile_error(png_ptr, name, temp,1784"unexpected ICC PCS encoding");1785}17861787return 1;1788}17891790int /* PRIVATE */1791png_icc_check_tag_table(png_const_structrp png_ptr, png_const_charp name,1792png_uint_32 profile_length,1793png_const_bytep profile /* header plus whole tag table */)1794{1795png_uint_32 tag_count = png_get_uint_32(profile+128);1796png_uint_32 itag;1797png_const_bytep tag = profile+132; /* The first tag */17981799/* First scan all the tags in the table and add bits to the icc_info value1800* (temporarily in 'tags').1801*/1802for (itag=0; itag < tag_count; ++itag, tag += 12)1803{1804png_uint_32 tag_id = png_get_uint_32(tag+0);1805png_uint_32 tag_start = png_get_uint_32(tag+4); /* must be aligned */1806png_uint_32 tag_length = png_get_uint_32(tag+8);/* not padded */18071808/* The ICC specification does not exclude zero length tags, therefore the1809* start might actually be anywhere if there is no data, but this would be1810* a clear abuse of the intent of the standard so the start is checked for1811* being in range. All defined tag types have an 8 byte header - a 4 byte1812* type signature then 0.1813*/18141815/* This is a hard error; potentially it can cause read outside the1816* profile.1817*/1818if (tag_start > profile_length || tag_length > profile_length - tag_start)1819return png_icc_profile_error(png_ptr, name, tag_id,1820"ICC profile tag outside profile");18211822if ((tag_start & 3) != 0)1823{1824/* CNHP730S.icc shipped with Microsoft Windows 64 violates this; it is1825* only a warning here because libpng does not care about the1826* alignment.1827*/1828(void)png_icc_profile_error(png_ptr, name, tag_id,1829"ICC profile tag start not a multiple of 4");1830}1831}18321833return 1; /* success, maybe with warnings */1834}1835#endif /* READ_iCCP */18361837#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED1838#if (defined PNG_READ_mDCV_SUPPORTED) || (defined PNG_READ_cHRM_SUPPORTED)1839static int1840have_chromaticities(png_const_structrp png_ptr)1841{1842/* Handle new PNGv3 chunks and the precedence rules to determine whether1843* png_struct::chromaticities must be processed. Only required for RGB to1844* gray.1845*1846* mDCV: this is the mastering colour space and it is independent of the1847* encoding so it needs to be used regardless of the encoded space.1848*1849* cICP: first in priority but not yet implemented - the chromaticities come1850* from the 'primaries'.1851*1852* iCCP: not supported by libpng (so ignored)1853*1854* sRGB: the defaults match sRGB1855*1856* cHRM: calculate the coefficients1857*/1858# ifdef PNG_READ_mDCV_SUPPORTED1859if (png_has_chunk(png_ptr, mDCV))1860return 1;1861# define check_chromaticities 11862# endif /*mDCV*/18631864# ifdef PNG_READ_sRGB_SUPPORTED1865if (png_has_chunk(png_ptr, sRGB))1866return 0;1867# endif /*sRGB*/18681869# ifdef PNG_READ_cHRM_SUPPORTED1870if (png_has_chunk(png_ptr, cHRM))1871return 1;1872# define check_chromaticities 11873# endif /*cHRM*/18741875return 0; /* sRGB defaults */1876}1877#endif /* READ_mDCV || READ_cHRM */18781879void /* PRIVATE */1880png_set_rgb_coefficients(png_structrp png_ptr)1881{1882/* Set the rgb_to_gray coefficients from the colorspace if available. Note1883* that '_set' means that png_rgb_to_gray was called **and** it successfully1884* set up the coefficients.1885*/1886if (png_ptr->rgb_to_gray_coefficients_set == 0)1887{1888# if check_chromaticities1889png_XYZ xyz;18901891if (have_chromaticities(png_ptr) &&1892png_XYZ_from_xy(&xyz, &png_ptr->chromaticities) == 0)1893{1894/* png_set_rgb_to_gray has not set the coefficients, get them from the1895* Y * values of the colorspace colorants.1896*/1897png_fixed_point r = xyz.red_Y;1898png_fixed_point g = xyz.green_Y;1899png_fixed_point b = xyz.blue_Y;1900png_fixed_point total = r+g+b;19011902if (total > 0 &&1903r >= 0 && png_muldiv(&r, r, 32768, total) && r >= 0 && r <= 32768 &&1904g >= 0 && png_muldiv(&g, g, 32768, total) && g >= 0 && g <= 32768 &&1905b >= 0 && png_muldiv(&b, b, 32768, total) && b >= 0 && b <= 32768 &&1906r+g+b <= 32769)1907{1908/* We allow 0 coefficients here. r+g+b may be 32769 if two or1909* all of the coefficients were rounded up. Handle this by1910* reducing the *largest* coefficient by 1; this matches the1911* approach used for the default coefficients in pngrtran.c1912*/1913int add = 0;19141915if (r+g+b > 32768)1916add = -1;1917else if (r+g+b < 32768)1918add = 1;19191920if (add != 0)1921{1922if (g >= r && g >= b)1923g += add;1924else if (r >= g && r >= b)1925r += add;1926else1927b += add;1928}19291930/* Check for an internal error. */1931if (r+g+b != 32768)1932png_error(png_ptr,1933"internal error handling cHRM coefficients");19341935else1936{1937png_ptr->rgb_to_gray_red_coeff = (png_uint_16)r;1938png_ptr->rgb_to_gray_green_coeff = (png_uint_16)g;1939}1940}1941}1942else1943# endif /* check_chromaticities */1944{1945/* Use the historical REC 709 (etc) values: */1946png_ptr->rgb_to_gray_red_coeff = 6968;1947png_ptr->rgb_to_gray_green_coeff = 23434;1948/* png_ptr->rgb_to_gray_blue_coeff = 2366; */1949}1950}1951}1952#endif /* READ_RGB_TO_GRAY */19531954void /* PRIVATE */1955png_check_IHDR(png_const_structrp png_ptr,1956png_uint_32 width, png_uint_32 height, int bit_depth,1957int color_type, int interlace_type, int compression_type,1958int filter_type)1959{1960int error = 0;19611962/* Check for width and height valid values */1963if (width == 0)1964{1965png_warning(png_ptr, "Image width is zero in IHDR");1966error = 1;1967}19681969if (width > PNG_UINT_31_MAX)1970{1971png_warning(png_ptr, "Invalid image width in IHDR");1972error = 1;1973}19741975/* The bit mask on the first line below must be at least as big as a1976* png_uint_32. "~7U" is not adequate on 16-bit systems because it will1977* be an unsigned 16-bit value. Casting to (png_alloc_size_t) makes the1978* type of the result at least as bit (in bits) as the RHS of the > operator1979* which also avoids a common warning on 64-bit systems that the comparison1980* of (png_uint_32) against the constant value on the RHS will always be1981* false.1982*/1983if (((width + 7) & ~(png_alloc_size_t)7) >1984(((PNG_SIZE_MAX1985- 48 /* big_row_buf hack */1986- 1) /* filter byte */1987/ 8) /* 8-byte RGBA pixels */1988- 1)) /* extra max_pixel_depth pad */1989{1990/* The size of the row must be within the limits of this architecture.1991* Because the read code can perform arbitrary transformations the1992* maximum size is checked here. Because the code in png_read_start_row1993* adds extra space "for safety's sake" in several places a conservative1994* limit is used here.1995*1996* NOTE: it would be far better to check the size that is actually used,1997* but the effect in the real world is minor and the changes are more1998* extensive, therefore much more dangerous and much more difficult to1999* write in a way that avoids compiler warnings.2000*/2001png_warning(png_ptr, "Image width is too large for this architecture");2002error = 1;2003}20042005#ifdef PNG_SET_USER_LIMITS_SUPPORTED2006if (width > png_ptr->user_width_max)2007#else2008if (width > PNG_USER_WIDTH_MAX)2009#endif2010{2011png_warning(png_ptr, "Image width exceeds user limit in IHDR");2012error = 1;2013}20142015if (height == 0)2016{2017png_warning(png_ptr, "Image height is zero in IHDR");2018error = 1;2019}20202021if (height > PNG_UINT_31_MAX)2022{2023png_warning(png_ptr, "Invalid image height in IHDR");2024error = 1;2025}20262027#ifdef PNG_SET_USER_LIMITS_SUPPORTED2028if (height > png_ptr->user_height_max)2029#else2030if (height > PNG_USER_HEIGHT_MAX)2031#endif2032{2033png_warning(png_ptr, "Image height exceeds user limit in IHDR");2034error = 1;2035}20362037/* Check other values */2038if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&2039bit_depth != 8 && bit_depth != 16)2040{2041png_warning(png_ptr, "Invalid bit depth in IHDR");2042error = 1;2043}20442045if (color_type < 0 || color_type == 1 ||2046color_type == 5 || color_type > 6)2047{2048png_warning(png_ptr, "Invalid color type in IHDR");2049error = 1;2050}20512052if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||2053((color_type == PNG_COLOR_TYPE_RGB ||2054color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||2055color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))2056{2057png_warning(png_ptr, "Invalid color type/bit depth combination in IHDR");2058error = 1;2059}20602061if (interlace_type >= PNG_INTERLACE_LAST)2062{2063png_warning(png_ptr, "Unknown interlace method in IHDR");2064error = 1;2065}20662067if (compression_type != PNG_COMPRESSION_TYPE_BASE)2068{2069png_warning(png_ptr, "Unknown compression method in IHDR");2070error = 1;2071}20722073#ifdef PNG_MNG_FEATURES_SUPPORTED2074/* Accept filter_method 64 (intrapixel differencing) only if2075* 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and2076* 2. Libpng did not read a PNG signature (this filter_method is only2077* used in PNG datastreams that are embedded in MNG datastreams) and2078* 3. The application called png_permit_mng_features with a mask that2079* included PNG_FLAG_MNG_FILTER_64 and2080* 4. The filter_method is 64 and2081* 5. The color_type is RGB or RGBA2082*/2083if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 &&2084png_ptr->mng_features_permitted != 0)2085png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");20862087if (filter_type != PNG_FILTER_TYPE_BASE)2088{2089if (!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&2090(filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&2091((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) == 0) &&2092(color_type == PNG_COLOR_TYPE_RGB ||2093color_type == PNG_COLOR_TYPE_RGB_ALPHA)))2094{2095png_warning(png_ptr, "Unknown filter method in IHDR");2096error = 1;2097}20982099if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0)2100{2101png_warning(png_ptr, "Invalid filter method in IHDR");2102error = 1;2103}2104}21052106#else2107if (filter_type != PNG_FILTER_TYPE_BASE)2108{2109png_warning(png_ptr, "Unknown filter method in IHDR");2110error = 1;2111}2112#endif21132114if (error == 1)2115png_error(png_ptr, "Invalid IHDR data");2116}21172118#if defined(PNG_sCAL_SUPPORTED) || defined(PNG_pCAL_SUPPORTED)2119/* ASCII to fp functions */2120/* Check an ASCII formatted floating point value, see the more detailed2121* comments in pngpriv.h2122*/2123/* The following is used internally to preserve the sticky flags */2124#define png_fp_add(state, flags) ((state) |= (flags))2125#define png_fp_set(state, value) ((state) = (value) | ((state) & PNG_FP_STICKY))21262127int /* PRIVATE */2128png_check_fp_number(png_const_charp string, size_t size, int *statep,2129size_t *whereami)2130{2131int state = *statep;2132size_t i = *whereami;21332134while (i < size)2135{2136int type;2137/* First find the type of the next character */2138switch (string[i])2139{2140case 43: type = PNG_FP_SAW_SIGN; break;2141case 45: type = PNG_FP_SAW_SIGN + PNG_FP_NEGATIVE; break;2142case 46: type = PNG_FP_SAW_DOT; break;2143case 48: type = PNG_FP_SAW_DIGIT; break;2144case 49: case 50: case 51: case 52:2145case 53: case 54: case 55: case 56:2146case 57: type = PNG_FP_SAW_DIGIT + PNG_FP_NONZERO; break;2147case 69:2148case 101: type = PNG_FP_SAW_E; break;2149default: goto PNG_FP_End;2150}21512152/* Now deal with this type according to the current2153* state, the type is arranged to not overlap the2154* bits of the PNG_FP_STATE.2155*/2156switch ((state & PNG_FP_STATE) + (type & PNG_FP_SAW_ANY))2157{2158case PNG_FP_INTEGER + PNG_FP_SAW_SIGN:2159if ((state & PNG_FP_SAW_ANY) != 0)2160goto PNG_FP_End; /* not a part of the number */21612162png_fp_add(state, type);2163break;21642165case PNG_FP_INTEGER + PNG_FP_SAW_DOT:2166/* Ok as trailer, ok as lead of fraction. */2167if ((state & PNG_FP_SAW_DOT) != 0) /* two dots */2168goto PNG_FP_End;21692170else if ((state & PNG_FP_SAW_DIGIT) != 0) /* trailing dot? */2171png_fp_add(state, type);21722173else2174png_fp_set(state, PNG_FP_FRACTION | type);21752176break;21772178case PNG_FP_INTEGER + PNG_FP_SAW_DIGIT:2179if ((state & PNG_FP_SAW_DOT) != 0) /* delayed fraction */2180png_fp_set(state, PNG_FP_FRACTION | PNG_FP_SAW_DOT);21812182png_fp_add(state, type | PNG_FP_WAS_VALID);21832184break;21852186case PNG_FP_INTEGER + PNG_FP_SAW_E:2187if ((state & PNG_FP_SAW_DIGIT) == 0)2188goto PNG_FP_End;21892190png_fp_set(state, PNG_FP_EXPONENT);21912192break;21932194/* case PNG_FP_FRACTION + PNG_FP_SAW_SIGN:2195goto PNG_FP_End; ** no sign in fraction */21962197/* case PNG_FP_FRACTION + PNG_FP_SAW_DOT:2198goto PNG_FP_End; ** Because SAW_DOT is always set */21992200case PNG_FP_FRACTION + PNG_FP_SAW_DIGIT:2201png_fp_add(state, type | PNG_FP_WAS_VALID);2202break;22032204case PNG_FP_FRACTION + PNG_FP_SAW_E:2205/* This is correct because the trailing '.' on an2206* integer is handled above - so we can only get here2207* with the sequence ".E" (with no preceding digits).2208*/2209if ((state & PNG_FP_SAW_DIGIT) == 0)2210goto PNG_FP_End;22112212png_fp_set(state, PNG_FP_EXPONENT);22132214break;22152216case PNG_FP_EXPONENT + PNG_FP_SAW_SIGN:2217if ((state & PNG_FP_SAW_ANY) != 0)2218goto PNG_FP_End; /* not a part of the number */22192220png_fp_add(state, PNG_FP_SAW_SIGN);22212222break;22232224/* case PNG_FP_EXPONENT + PNG_FP_SAW_DOT:2225goto PNG_FP_End; */22262227case PNG_FP_EXPONENT + PNG_FP_SAW_DIGIT:2228png_fp_add(state, PNG_FP_SAW_DIGIT | PNG_FP_WAS_VALID);22292230break;22312232/* case PNG_FP_EXPONEXT + PNG_FP_SAW_E:2233goto PNG_FP_End; */22342235default: goto PNG_FP_End; /* I.e. break 2 */2236}22372238/* The character seems ok, continue. */2239++i;2240}22412242PNG_FP_End:2243/* Here at the end, update the state and return the correct2244* return code.2245*/2246*statep = state;2247*whereami = i;22482249return (state & PNG_FP_SAW_DIGIT) != 0;2250}225122522253/* The same but for a complete string. */2254int2255png_check_fp_string(png_const_charp string, size_t size)2256{2257int state=0;2258size_t char_index=0;22592260if (png_check_fp_number(string, size, &state, &char_index) != 0 &&2261(char_index == size || string[char_index] == 0))2262return state /* must be non-zero - see above */;22632264return 0; /* i.e. fail */2265}2266#endif /* pCAL || sCAL */22672268#ifdef PNG_sCAL_SUPPORTED2269# ifdef PNG_FLOATING_POINT_SUPPORTED2270/* Utility used below - a simple accurate power of ten from an integral2271* exponent.2272*/2273static double2274png_pow10(int power)2275{2276int recip = 0;2277double d = 1;22782279/* Handle negative exponent with a reciprocal at the end because2280* 10 is exact whereas .1 is inexact in base 22281*/2282if (power < 0)2283{2284if (power < DBL_MIN_10_EXP) return 0;2285recip = 1; power = -power;2286}22872288if (power > 0)2289{2290/* Decompose power bitwise. */2291double mult = 10;2292do2293{2294if (power & 1) d *= mult;2295mult *= mult;2296power >>= 1;2297}2298while (power > 0);22992300if (recip != 0) d = 1/d;2301}2302/* else power is 0 and d is 1 */23032304return d;2305}23062307/* Function to format a floating point value in ASCII with a given2308* precision.2309*/2310void /* PRIVATE */2311png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, size_t size,2312double fp, unsigned int precision)2313{2314/* We use standard functions from math.h, but not printf because2315* that would require stdio. The caller must supply a buffer of2316* sufficient size or we will png_error. The tests on size and2317* the space in ascii[] consumed are indicated below.2318*/2319if (precision < 1)2320precision = DBL_DIG;23212322/* Enforce the limit of the implementation precision too. */2323if (precision > DBL_DIG+1)2324precision = DBL_DIG+1;23252326/* Basic sanity checks */2327if (size >= precision+5) /* See the requirements below. */2328{2329if (fp < 0)2330{2331fp = -fp;2332*ascii++ = 45; /* '-' PLUS 1 TOTAL 1 */2333--size;2334}23352336if (fp >= DBL_MIN && fp <= DBL_MAX)2337{2338int exp_b10; /* A base 10 exponent */2339double base; /* 10^exp_b10 */23402341/* First extract a base 10 exponent of the number,2342* the calculation below rounds down when converting2343* from base 2 to base 10 (multiply by log10(2) -2344* 0.3010, but 77/256 is 0.3008, so exp_b10 needs to2345* be increased. Note that the arithmetic shift2346* performs a floor() unlike C arithmetic - using a2347* C multiply would break the following for negative2348* exponents.2349*/2350(void)frexp(fp, &exp_b10); /* exponent to base 2 */23512352exp_b10 = (exp_b10 * 77) >> 8; /* <= exponent to base 10 */23532354/* Avoid underflow here. */2355base = png_pow10(exp_b10); /* May underflow */23562357while (base < DBL_MIN || base < fp)2358{2359/* And this may overflow. */2360double test = png_pow10(exp_b10+1);23612362if (test <= DBL_MAX)2363{2364++exp_b10; base = test;2365}23662367else2368break;2369}23702371/* Normalize fp and correct exp_b10, after this fp is in the2372* range [.1,1) and exp_b10 is both the exponent and the digit2373* *before* which the decimal point should be inserted2374* (starting with 0 for the first digit). Note that this2375* works even if 10^exp_b10 is out of range because of the2376* test on DBL_MAX above.2377*/2378fp /= base;2379while (fp >= 1)2380{2381fp /= 10; ++exp_b10;2382}23832384/* Because of the code above fp may, at this point, be2385* less than .1, this is ok because the code below can2386* handle the leading zeros this generates, so no attempt2387* is made to correct that here.2388*/23892390{2391unsigned int czero, clead, cdigits;2392char exponent[10];23932394/* Allow up to two leading zeros - this will not lengthen2395* the number compared to using E-n.2396*/2397if (exp_b10 < 0 && exp_b10 > -3) /* PLUS 3 TOTAL 4 */2398{2399czero = 0U-exp_b10; /* PLUS 2 digits: TOTAL 3 */2400exp_b10 = 0; /* Dot added below before first output. */2401}2402else2403czero = 0; /* No zeros to add */24042405/* Generate the digit list, stripping trailing zeros and2406* inserting a '.' before a digit if the exponent is 0.2407*/2408clead = czero; /* Count of leading zeros */2409cdigits = 0; /* Count of digits in list. */24102411do2412{2413double d;24142415fp *= 10;2416/* Use modf here, not floor and subtract, so that2417* the separation is done in one step. At the end2418* of the loop don't break the number into parts so2419* that the final digit is rounded.2420*/2421if (cdigits+czero+1 < precision+clead)2422fp = modf(fp, &d);24232424else2425{2426d = floor(fp + .5);24272428if (d > 9)2429{2430/* Rounding up to 10, handle that here. */2431if (czero > 0)2432{2433--czero; d = 1;2434if (cdigits == 0) --clead;2435}2436else2437{2438while (cdigits > 0 && d > 9)2439{2440int ch = *--ascii;24412442if (exp_b10 != (-1))2443++exp_b10;24442445else if (ch == 46)2446{2447ch = *--ascii; ++size;2448/* Advance exp_b10 to '1', so that the2449* decimal point happens after the2450* previous digit.2451*/2452exp_b10 = 1;2453}24542455--cdigits;2456d = ch - 47; /* I.e. 1+(ch-48) */2457}24582459/* Did we reach the beginning? If so adjust the2460* exponent but take into account the leading2461* decimal point.2462*/2463if (d > 9) /* cdigits == 0 */2464{2465if (exp_b10 == (-1))2466{2467/* Leading decimal point (plus zeros?), if2468* we lose the decimal point here it must2469* be reentered below.2470*/2471int ch = *--ascii;24722473if (ch == 46)2474{2475++size; exp_b10 = 1;2476}24772478/* Else lost a leading zero, so 'exp_b10' is2479* still ok at (-1)2480*/2481}2482else2483++exp_b10;24842485/* In all cases we output a '1' */2486d = 1;2487}2488}2489}2490fp = 0; /* Guarantees termination below. */2491}24922493if (d == 0)2494{2495++czero;2496if (cdigits == 0) ++clead;2497}2498else2499{2500/* Included embedded zeros in the digit count. */2501cdigits += czero - clead;2502clead = 0;25032504while (czero > 0)2505{2506/* exp_b10 == (-1) means we just output the decimal2507* place - after the DP don't adjust 'exp_b10' any2508* more!2509*/2510if (exp_b10 != (-1))2511{2512if (exp_b10 == 0)2513{2514*ascii++ = 46; --size;2515}2516/* PLUS 1: TOTAL 4 */2517--exp_b10;2518}2519*ascii++ = 48; --czero;2520}25212522if (exp_b10 != (-1))2523{2524if (exp_b10 == 0)2525{2526*ascii++ = 46; --size; /* counted above */2527}25282529--exp_b10;2530}2531*ascii++ = (char)(48 + (int)d); ++cdigits;2532}2533}2534while (cdigits+czero < precision+clead && fp > DBL_MIN);25352536/* The total output count (max) is now 4+precision */25372538/* Check for an exponent, if we don't need one we are2539* done and just need to terminate the string. At this2540* point, exp_b10==(-1) is effectively a flag: it got2541* to '-1' because of the decrement, after outputting2542* the decimal point above. (The exponent required is2543* *not* -1.)2544*/2545if (exp_b10 >= (-1) && exp_b10 <= 2)2546{2547/* The following only happens if we didn't output the2548* leading zeros above for negative exponent, so this2549* doesn't add to the digit requirement. Note that the2550* two zeros here can only be output if the two leading2551* zeros were *not* output, so this doesn't increase2552* the output count.2553*/2554while (exp_b10-- > 0) *ascii++ = 48;25552556*ascii = 0;25572558/* Total buffer requirement (including the '\0') is2559* 5+precision - see check at the start.2560*/2561return;2562}25632564/* Here if an exponent is required, adjust size for2565* the digits we output but did not count. The total2566* digit output here so far is at most 1+precision - no2567* decimal point and no leading or trailing zeros have2568* been output.2569*/2570size -= cdigits;25712572*ascii++ = 69; --size; /* 'E': PLUS 1 TOTAL 2+precision */25732574/* The following use of an unsigned temporary avoids ambiguities in2575* the signed arithmetic on exp_b10 and permits GCC at least to do2576* better optimization.2577*/2578{2579unsigned int uexp_b10;25802581if (exp_b10 < 0)2582{2583*ascii++ = 45; --size; /* '-': PLUS 1 TOTAL 3+precision */2584uexp_b10 = 0U-exp_b10;2585}25862587else2588uexp_b10 = 0U+exp_b10;25892590cdigits = 0;25912592while (uexp_b10 > 0)2593{2594exponent[cdigits++] = (char)(48 + uexp_b10 % 10);2595uexp_b10 /= 10;2596}2597}25982599/* Need another size check here for the exponent digits, so2600* this need not be considered above.2601*/2602if (size > cdigits)2603{2604while (cdigits > 0) *ascii++ = exponent[--cdigits];26052606*ascii = 0;26072608return;2609}2610}2611}2612else if (!(fp >= DBL_MIN))2613{2614*ascii++ = 48; /* '0' */2615*ascii = 0;2616return;2617}2618else2619{2620*ascii++ = 105; /* 'i' */2621*ascii++ = 110; /* 'n' */2622*ascii++ = 102; /* 'f' */2623*ascii = 0;2624return;2625}2626}26272628/* Here on buffer too small. */2629png_error(png_ptr, "ASCII conversion buffer too small");2630}2631# endif /* FLOATING_POINT */26322633# ifdef PNG_FIXED_POINT_SUPPORTED2634/* Function to format a fixed point value in ASCII.2635*/2636void /* PRIVATE */2637png_ascii_from_fixed(png_const_structrp png_ptr, png_charp ascii,2638size_t size, png_fixed_point fp)2639{2640/* Require space for 10 decimal digits, a decimal point, a minus sign and a2641* trailing \0, 13 characters:2642*/2643if (size > 12)2644{2645png_uint_32 num;26462647/* Avoid overflow here on the minimum integer. */2648if (fp < 0)2649{2650*ascii++ = 45; num = (png_uint_32)(-fp);2651}2652else2653num = (png_uint_32)fp;26542655if (num <= 0x80000000) /* else overflowed */2656{2657unsigned int ndigits = 0, first = 16 /* flag value */;2658char digits[10] = {0};26592660while (num)2661{2662/* Split the low digit off num: */2663unsigned int tmp = num/10;2664num -= tmp*10;2665digits[ndigits++] = (char)(48 + num);2666/* Record the first non-zero digit, note that this is a number2667* starting at 1, it's not actually the array index.2668*/2669if (first == 16 && num > 0)2670first = ndigits;2671num = tmp;2672}26732674if (ndigits > 0)2675{2676while (ndigits > 5) *ascii++ = digits[--ndigits];2677/* The remaining digits are fractional digits, ndigits is '5' or2678* smaller at this point. It is certainly not zero. Check for a2679* non-zero fractional digit:2680*/2681if (first <= 5)2682{2683unsigned int i;2684*ascii++ = 46; /* decimal point */2685/* ndigits may be <5 for small numbers, output leading zeros2686* then ndigits digits to first:2687*/2688i = 5;2689while (ndigits < i)2690{2691*ascii++ = 48; --i;2692}2693while (ndigits >= first) *ascii++ = digits[--ndigits];2694/* Don't output the trailing zeros! */2695}2696}2697else2698*ascii++ = 48;26992700/* And null terminate the string: */2701*ascii = 0;2702return;2703}2704}27052706/* Here on buffer too small. */2707png_error(png_ptr, "ASCII conversion buffer too small");2708}2709# endif /* FIXED_POINT */2710#endif /* SCAL */27112712#if defined(PNG_FLOATING_POINT_SUPPORTED) && \2713!defined(PNG_FIXED_POINT_MACRO_SUPPORTED) && \2714(defined(PNG_gAMA_SUPPORTED) || defined(PNG_cHRM_SUPPORTED) || \2715defined(PNG_sCAL_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) || \2716defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)) || \2717(defined(PNG_sCAL_SUPPORTED) && \2718defined(PNG_FLOATING_ARITHMETIC_SUPPORTED))2719png_fixed_point2720png_fixed(png_const_structrp png_ptr, double fp, png_const_charp text)2721{2722double r = floor(100000 * fp + .5);27232724if (r > 2147483647. || r < -2147483648.)2725png_fixed_error(png_ptr, text);27262727# ifndef PNG_ERROR_TEXT_SUPPORTED2728PNG_UNUSED(text)2729# endif27302731return (png_fixed_point)r;2732}2733#endif27342735#if defined(PNG_FLOATING_POINT_SUPPORTED) && \2736!defined(PNG_FIXED_POINT_MACRO_SUPPORTED) && \2737(defined(PNG_cLLI_SUPPORTED) || defined(PNG_mDCV_SUPPORTED))2738png_uint_322739png_fixed_ITU(png_const_structrp png_ptr, double fp, png_const_charp text)2740{2741double r = floor(10000 * fp + .5);27422743if (r > 2147483647. || r < 0)2744png_fixed_error(png_ptr, text);27452746# ifndef PNG_ERROR_TEXT_SUPPORTED2747PNG_UNUSED(text)2748# endif27492750return (png_uint_32)r;2751}2752#endif275327542755#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_COLORSPACE_SUPPORTED) ||\2756defined(PNG_INCH_CONVERSIONS_SUPPORTED) || defined(PNG_READ_pHYs_SUPPORTED)2757/* muldiv functions */2758/* This API takes signed arguments and rounds the result to the nearest2759* integer (or, for a fixed point number - the standard argument - to2760* the nearest .00001). Overflow and divide by zero are signalled in2761* the result, a boolean - true on success, false on overflow.2762*/2763int /* PRIVATE */2764png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times,2765png_int_32 divisor)2766{2767/* Return a * times / divisor, rounded. */2768if (divisor != 0)2769{2770if (a == 0 || times == 0)2771{2772*res = 0;2773return 1;2774}2775else2776{2777#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED2778double r = a;2779r *= times;2780r /= divisor;2781r = floor(r+.5);27822783/* A png_fixed_point is a 32-bit integer. */2784if (r <= 2147483647. && r >= -2147483648.)2785{2786*res = (png_fixed_point)r;2787return 1;2788}2789#else2790int negative = 0;2791png_uint_32 A, T, D;2792png_uint_32 s16, s32, s00;27932794if (a < 0)2795negative = 1, A = -a;2796else2797A = a;27982799if (times < 0)2800negative = !negative, T = -times;2801else2802T = times;28032804if (divisor < 0)2805negative = !negative, D = -divisor;2806else2807D = divisor;28082809/* Following can't overflow because the arguments only2810* have 31 bits each, however the result may be 32 bits.2811*/2812s16 = (A >> 16) * (T & 0xffff) +2813(A & 0xffff) * (T >> 16);2814/* Can't overflow because the a*times bit is only 302815* bits at most.2816*/2817s32 = (A >> 16) * (T >> 16) + (s16 >> 16);2818s00 = (A & 0xffff) * (T & 0xffff);28192820s16 = (s16 & 0xffff) << 16;2821s00 += s16;28222823if (s00 < s16)2824++s32; /* carry */28252826if (s32 < D) /* else overflow */2827{2828/* s32.s00 is now the 64-bit product, do a standard2829* division, we know that s32 < D, so the maximum2830* required shift is 31.2831*/2832int bitshift = 32;2833png_fixed_point result = 0; /* NOTE: signed */28342835while (--bitshift >= 0)2836{2837png_uint_32 d32, d00;28382839if (bitshift > 0)2840d32 = D >> (32-bitshift), d00 = D << bitshift;28412842else2843d32 = 0, d00 = D;28442845if (s32 > d32)2846{2847if (s00 < d00) --s32; /* carry */2848s32 -= d32, s00 -= d00, result += 1<<bitshift;2849}28502851else2852if (s32 == d32 && s00 >= d00)2853s32 = 0, s00 -= d00, result += 1<<bitshift;2854}28552856/* Handle the rounding. */2857if (s00 >= (D >> 1))2858++result;28592860if (negative != 0)2861result = -result;28622863/* Check for overflow. */2864if ((negative != 0 && result <= 0) ||2865(negative == 0 && result >= 0))2866{2867*res = result;2868return 1;2869}2870}2871#endif2872}2873}28742875return 0;2876}28772878/* Calculate a reciprocal, return 0 on div-by-zero or overflow. */2879png_fixed_point2880png_reciprocal(png_fixed_point a)2881{2882#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED2883double r = floor(1E10/a+.5);28842885if (r <= 2147483647. && r >= -2147483648.)2886return (png_fixed_point)r;2887#else2888png_fixed_point res;28892890if (png_muldiv(&res, 100000, 100000, a) != 0)2891return res;2892#endif28932894return 0; /* error/overflow */2895}2896#endif /* READ_GAMMA || COLORSPACE || INCH_CONVERSIONS || READ_pHYS */28972898#ifdef PNG_READ_GAMMA_SUPPORTED2899/* This is the shared test on whether a gamma value is 'significant' - whether2900* it is worth doing gamma correction.2901*/2902int /* PRIVATE */2903png_gamma_significant(png_fixed_point gamma_val)2904{2905/* sRGB: 1/2.2 == 0.4545(45)2906* AdobeRGB: 1/(2+51/256) ~= 0.45471 5dp2907*2908* So the correction from AdobeRGB to sRGB (output) is:2909*2910* 2.2/(2+51/256) == 1.000355242911*2912* I.e. vanishly small (<4E-4) but still detectable in 16-bit linear (+/-2913* 23). Note that the Adobe choice seems to be something intended to give an2914* exact number with 8 binary fractional digits - it is the closest to 2.22915* that is possible a base 2 .8p representation.2916*/2917return gamma_val < PNG_FP_1 - PNG_GAMMA_THRESHOLD_FIXED ||2918gamma_val > PNG_FP_1 + PNG_GAMMA_THRESHOLD_FIXED;2919}29202921#ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED2922/* A local convenience routine. */2923static png_fixed_point2924png_product2(png_fixed_point a, png_fixed_point b)2925{2926/* The required result is a * b; the following preserves accuracy. */2927#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED /* Should now be unused */2928double r = a * 1E-5;2929r *= b;2930r = floor(r+.5);29312932if (r <= 2147483647. && r >= -2147483648.)2933return (png_fixed_point)r;2934#else2935png_fixed_point res;29362937if (png_muldiv(&res, a, b, 100000) != 0)2938return res;2939#endif29402941return 0; /* overflow */2942}2943#endif /* FLOATING_ARITHMETIC */29442945png_fixed_point2946png_reciprocal2(png_fixed_point a, png_fixed_point b)2947{2948/* The required result is 1/a * 1/b; the following preserves accuracy. */2949#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED2950if (a != 0 && b != 0)2951{2952double r = 1E15/a;2953r /= b;2954r = floor(r+.5);29552956if (r <= 2147483647. && r >= -2147483648.)2957return (png_fixed_point)r;2958}2959#else2960/* This may overflow because the range of png_fixed_point isn't symmetric,2961* but this API is only used for the product of file and screen gamma so it2962* doesn't matter that the smallest number it can produce is 1/21474, not2963* 1/1000002964*/2965png_fixed_point res = png_product2(a, b);29662967if (res != 0)2968return png_reciprocal(res);2969#endif29702971return 0; /* overflow */2972}2973#endif /* READ_GAMMA */29742975#ifdef PNG_READ_GAMMA_SUPPORTED /* gamma table code */2976#ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED2977/* Fixed point gamma.2978*2979* The code to calculate the tables used below can be found in the shell script2980* contrib/tools/intgamma.sh2981*2982* To calculate gamma this code implements fast log() and exp() calls using only2983* fixed point arithmetic. This code has sufficient precision for either 8-bit2984* or 16-bit sample values.2985*2986* The tables used here were calculated using simple 'bc' programs, but C double2987* precision floating point arithmetic would work fine.2988*2989* 8-bit log table2990* This is a table of -log(value/255)/log(2) for 'value' in the range 128 to2991* 255, so it's the base 2 logarithm of a normalized 8-bit floating point2992* mantissa. The numbers are 32-bit fractions.2993*/2994static const png_uint_322995png_8bit_l2[128] =2996{29974270715492U, 4222494797U, 4174646467U, 4127164793U, 4080044201U, 4033279239U,29983986864580U, 3940795015U, 3895065449U, 3849670902U, 3804606499U, 3759867474U,29993715449162U, 3671346997U, 3627556511U, 3584073329U, 3540893168U, 3498011834U,30003455425220U, 3413129301U, 3371120137U, 3329393864U, 3287946700U, 3246774933U,30013205874930U, 3165243125U, 3124876025U, 3084770202U, 3044922296U, 3005329011U,30022965987113U, 2926893432U, 2888044853U, 2849438323U, 2811070844U, 2772939474U,30032735041326U, 2697373562U, 2659933400U, 2622718104U, 2585724991U, 2548951424U,30042512394810U, 2476052606U, 2439922311U, 2404001468U, 2368287663U, 2332778523U,30052297471715U, 2262364947U, 2227455964U, 2192742551U, 2158222529U, 2123893754U,30062089754119U, 2055801552U, 2022034013U, 1988449497U, 1955046031U, 1921821672U,30071888774511U, 1855902668U, 1823204291U, 1790677560U, 1758320682U, 1726131893U,30081694109454U, 1662251657U, 1630556815U, 1599023271U, 1567649391U, 1536433567U,30091505374214U, 1474469770U, 1443718700U, 1413119487U, 1382670639U, 1352370686U,30101322218179U, 1292211689U, 1262349810U, 1232631153U, 1203054352U, 1173618059U,30111144320946U, 1115161701U, 1086139034U, 1057251672U, 1028498358U, 999877854U,3012971388940U, 943030410U, 914801076U, 886699767U, 858725327U, 830876614U,3013803152505U, 775551890U, 748073672U, 720716771U, 693480120U, 666362667U,3014639363374U, 612481215U, 585715177U, 559064263U, 532527486U, 506103872U,3015479792461U, 453592303U, 427502463U, 401522014U, 375650043U, 349885648U,3016324227938U, 298676034U, 273229066U, 247886176U, 222646516U, 197509248U,3017172473545U, 147538590U, 122703574U, 97967701U, 73330182U, 48790236U,301824347096U, 0U30193020#if 03021/* The following are the values for 16-bit tables - these work fine for the3022* 8-bit conversions but produce very slightly larger errors in the 16-bit3023* log (about 1.2 as opposed to 0.7 absolute error in the final value). To3024* use these all the shifts below must be adjusted appropriately.3025*/302665166, 64430, 63700, 62976, 62257, 61543, 60835, 60132, 59434, 58741, 58054,302757371, 56693, 56020, 55352, 54689, 54030, 53375, 52726, 52080, 51439, 50803,302850170, 49542, 48918, 48298, 47682, 47070, 46462, 45858, 45257, 44661, 44068,302943479, 42894, 42312, 41733, 41159, 40587, 40020, 39455, 38894, 38336, 37782,303037230, 36682, 36137, 35595, 35057, 34521, 33988, 33459, 32932, 32408, 31887,303131369, 30854, 30341, 29832, 29325, 28820, 28319, 27820, 27324, 26830, 26339,303225850, 25364, 24880, 24399, 23920, 23444, 22970, 22499, 22029, 21562, 21098,303320636, 20175, 19718, 19262, 18808, 18357, 17908, 17461, 17016, 16573, 16132,303415694, 15257, 14822, 14390, 13959, 13530, 13103, 12678, 12255, 11834, 11415,303510997, 10582, 10168, 9756, 9346, 8937, 8531, 8126, 7723, 7321, 6921, 6523,30366127, 5732, 5339, 4947, 4557, 4169, 3782, 3397, 3014, 2632, 2251, 1872, 1495,30371119, 744, 3723038#endif3039};30403041static png_int_323042png_log8bit(unsigned int x)3043{3044unsigned int lg2 = 0;3045/* Each time 'x' is multiplied by 2, 1 must be subtracted off the final log,3046* because the log is actually negate that means adding 1. The final3047* returned value thus has the range 0 (for 255 input) to 7.994 (for 13048* input), return -1 for the overflow (log 0) case, - so the result is3049* always at most 19 bits.3050*/3051if ((x &= 0xff) == 0)3052return -1;30533054if ((x & 0xf0) == 0)3055lg2 = 4, x <<= 4;30563057if ((x & 0xc0) == 0)3058lg2 += 2, x <<= 2;30593060if ((x & 0x80) == 0)3061lg2 += 1, x <<= 1;30623063/* result is at most 19 bits, so this cast is safe: */3064return (png_int_32)((lg2 << 16) + ((png_8bit_l2[x-128]+32768)>>16));3065}30663067/* The above gives exact (to 16 binary places) log2 values for 8-bit images,3068* for 16-bit images we use the most significant 8 bits of the 16-bit value to3069* get an approximation then multiply the approximation by a correction factor3070* determined by the remaining up to 8 bits. This requires an additional step3071* in the 16-bit case.3072*3073* We want log2(value/65535), we have log2(v'/255), where:3074*3075* value = v' * 256 + v''3076* = v' * f3077*3078* So f is value/v', which is equal to (256+v''/v') since v' is in the range 1283079* to 255 and v'' is in the range 0 to 255 f will be in the range 256 to less3080* than 258. The final factor also needs to correct for the fact that our 8-bit3081* value is scaled by 255, whereas the 16-bit values must be scaled by 65535.3082*3083* This gives a final formula using a calculated value 'x' which is value/v' and3084* scaling by 65536 to match the above table:3085*3086* log2(x/257) * 655363087*3088* Since these numbers are so close to '1' we can use simple linear3089* interpolation between the two end values 256/257 (result -368.61) and 258/2573090* (result 367.179). The values used below are scaled by a further 64 to give3091* 16-bit precision in the interpolation:3092*3093* Start (256): -235913094* Zero (257): 03095* End (258): 234993096*/3097#ifdef PNG_16BIT_SUPPORTED3098static png_int_323099png_log16bit(png_uint_32 x)3100{3101unsigned int lg2 = 0;31023103/* As above, but now the input has 16 bits. */3104if ((x &= 0xffff) == 0)3105return -1;31063107if ((x & 0xff00) == 0)3108lg2 = 8, x <<= 8;31093110if ((x & 0xf000) == 0)3111lg2 += 4, x <<= 4;31123113if ((x & 0xc000) == 0)3114lg2 += 2, x <<= 2;31153116if ((x & 0x8000) == 0)3117lg2 += 1, x <<= 1;31183119/* Calculate the base logarithm from the top 8 bits as a 28-bit fractional3120* value.3121*/3122lg2 <<= 28;3123lg2 += (png_8bit_l2[(x>>8)-128]+8) >> 4;31243125/* Now we need to interpolate the factor, this requires a division by the top3126* 8 bits. Do this with maximum precision.3127*/3128x = ((x << 16) + (x >> 9)) / (x >> 8);31293130/* Since we divided by the top 8 bits of 'x' there will be a '1' at 1<<24,3131* the value at 1<<16 (ignoring this) will be 0 or 1; this gives us exactly3132* 16 bits to interpolate to get the low bits of the result. Round the3133* answer. Note that the end point values are scaled by 64 to retain overall3134* precision and that 'lg2' is current scaled by an extra 12 bits, so adjust3135* the overall scaling by 6-12. Round at every step.3136*/3137x -= 1U << 24;31383139if (x <= 65536U) /* <= '257' */3140lg2 += ((23591U * (65536U-x)) + (1U << (16+6-12-1))) >> (16+6-12);31413142else3143lg2 -= ((23499U * (x-65536U)) + (1U << (16+6-12-1))) >> (16+6-12);31443145/* Safe, because the result can't have more than 20 bits: */3146return (png_int_32)((lg2 + 2048) >> 12);3147}3148#endif /* 16BIT */31493150/* The 'exp()' case must invert the above, taking a 20-bit fixed point3151* logarithmic value and returning a 16 or 8-bit number as appropriate. In3152* each case only the low 16 bits are relevant - the fraction - since the3153* integer bits (the top 4) simply determine a shift.3154*3155* The worst case is the 16-bit distinction between 65535 and 65534. This3156* requires perhaps spurious accuracy in the decoding of the logarithm to3157* distinguish log2(65535/65534.5) - 10^-5 or 17 bits. There is little chance3158* of getting this accuracy in practice.3159*3160* To deal with this the following exp() function works out the exponent of the3161* fractional part of the logarithm by using an accurate 32-bit value from the3162* top four fractional bits then multiplying in the remaining bits.3163*/3164static const png_uint_323165png_32bit_exp[16] =3166{3167/* NOTE: the first entry is deliberately set to the maximum 32-bit value. */31684294967295U, 4112874773U, 3938502376U, 3771522796U, 3611622603U, 3458501653U,31693311872529U, 3171459999U, 3037000500U, 2908241642U, 2784941738U, 2666869345U,31702553802834U, 2445529972U, 2341847524U, 2242560872U3171};31723173/* Adjustment table; provided to explain the numbers in the code below. */3174#if 03175for (i=11;i>=0;--i){ print i, " ", (1 - e(-(2^i)/65536*l(2))) * 2^(32-i), "\n"}317611 44937.64284865548751208448317710 45180.9873484558510116044831789 45303.3193698068735931187231798 45364.6511059532301887078431807 45395.3585036178962461491231816 45410.7225971510203750809631825 45418.4072441322072231116831834 45422.2502178689817300172831843 45424.1718673229841904435231852 45425.1327326994081146470431861 45425.6131755503555864166431870 45425.853399516549438504963188#endif31893190static png_uint_323191png_exp(png_fixed_point x)3192{3193if (x > 0 && x <= 0xfffff) /* Else overflow or zero (underflow) */3194{3195/* Obtain a 4-bit approximation */3196png_uint_32 e = png_32bit_exp[(x >> 12) & 0x0f];31973198/* Incorporate the low 12 bits - these decrease the returned value by3199* multiplying by a number less than 1 if the bit is set. The multiplier3200* is determined by the above table and the shift. Notice that the values3201* converge on 45426 and this is used to allow linear interpolation of the3202* low bits.3203*/3204if (x & 0x800)3205e -= (((e >> 16) * 44938U) + 16U) >> 5;32063207if (x & 0x400)3208e -= (((e >> 16) * 45181U) + 32U) >> 6;32093210if (x & 0x200)3211e -= (((e >> 16) * 45303U) + 64U) >> 7;32123213if (x & 0x100)3214e -= (((e >> 16) * 45365U) + 128U) >> 8;32153216if (x & 0x080)3217e -= (((e >> 16) * 45395U) + 256U) >> 9;32183219if (x & 0x040)3220e -= (((e >> 16) * 45410U) + 512U) >> 10;32213222/* And handle the low 6 bits in a single block. */3223e -= (((e >> 16) * 355U * (x & 0x3fU)) + 256U) >> 9;32243225/* Handle the upper bits of x. */3226e >>= x >> 16;3227return e;3228}32293230/* Check for overflow */3231if (x <= 0)3232return png_32bit_exp[0];32333234/* Else underflow */3235return 0;3236}32373238static png_byte3239png_exp8bit(png_fixed_point lg2)3240{3241/* Get a 32-bit value: */3242png_uint_32 x = png_exp(lg2);32433244/* Convert the 32-bit value to 0..255 by multiplying by 256-1. Note that the3245* second, rounding, step can't overflow because of the first, subtraction,3246* step.3247*/3248x -= x >> 8;3249return (png_byte)(((x + 0x7fffffU) >> 24) & 0xff);3250}32513252#ifdef PNG_16BIT_SUPPORTED3253static png_uint_163254png_exp16bit(png_fixed_point lg2)3255{3256/* Get a 32-bit value: */3257png_uint_32 x = png_exp(lg2);32583259/* Convert the 32-bit value to 0..65535 by multiplying by 65536-1: */3260x -= x >> 16;3261return (png_uint_16)((x + 32767U) >> 16);3262}3263#endif /* 16BIT */3264#endif /* FLOATING_ARITHMETIC */32653266png_byte3267png_gamma_8bit_correct(unsigned int value, png_fixed_point gamma_val)3268{3269if (value > 0 && value < 255)3270{3271# ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3272/* 'value' is unsigned, ANSI-C90 requires the compiler to correctly3273* convert this to a floating point value. This includes values that3274* would overflow if 'value' were to be converted to 'int'.3275*3276* Apparently GCC, however, does an intermediate conversion to (int)3277* on some (ARM) but not all (x86) platforms, possibly because of3278* hardware FP limitations. (E.g. if the hardware conversion always3279* assumes the integer register contains a signed value.) This results3280* in ANSI-C undefined behavior for large values.3281*3282* Other implementations on the same machine might actually be ANSI-C903283* conformant and therefore compile spurious extra code for the large3284* values.3285*3286* We can be reasonably sure that an unsigned to float conversion3287* won't be faster than an int to float one. Therefore this code3288* assumes responsibility for the undefined behavior, which it knows3289* can't happen because of the check above.3290*3291* Note the argument to this routine is an (unsigned int) because, on3292* 16-bit platforms, it is assigned a value which might be out of3293* range for an (int); that would result in undefined behavior in the3294* caller if the *argument* ('value') were to be declared (int).3295*/3296double r = floor(255*pow((int)/*SAFE*/value/255.,gamma_val*.00001)+.5);3297return (png_byte)r;3298# else3299png_int_32 lg2 = png_log8bit(value);3300png_fixed_point res;33013302if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1) != 0)3303return png_exp8bit(res);33043305/* Overflow. */3306value = 0;3307# endif3308}33093310return (png_byte)(value & 0xff);3311}33123313#ifdef PNG_16BIT_SUPPORTED3314png_uint_163315png_gamma_16bit_correct(unsigned int value, png_fixed_point gamma_val)3316{3317if (value > 0 && value < 65535)3318{3319# ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3320/* The same (unsigned int)->(double) constraints apply here as above,3321* however in this case the (unsigned int) to (int) conversion can3322* overflow on an ANSI-C90 compliant system so the cast needs to ensure3323* that this is not possible.3324*/3325double r = floor(65535*pow((png_int_32)value/65535.,3326gamma_val*.00001)+.5);3327return (png_uint_16)r;3328# else3329png_int_32 lg2 = png_log16bit(value);3330png_fixed_point res;33313332if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1) != 0)3333return png_exp16bit(res);33343335/* Overflow. */3336value = 0;3337# endif3338}33393340return (png_uint_16)value;3341}3342#endif /* 16BIT */33433344/* This does the right thing based on the bit_depth field of the3345* png_struct, interpreting values as 8-bit or 16-bit. While the result3346* is nominally a 16-bit value if bit depth is 8 then the result is3347* 8-bit (as are the arguments.)3348*/3349png_uint_16 /* PRIVATE */3350png_gamma_correct(png_structrp png_ptr, unsigned int value,3351png_fixed_point gamma_val)3352{3353if (png_ptr->bit_depth == 8)3354return png_gamma_8bit_correct(value, gamma_val);33553356#ifdef PNG_16BIT_SUPPORTED3357else3358return png_gamma_16bit_correct(value, gamma_val);3359#else3360/* should not reach this */3361return 0;3362#endif /* 16BIT */3363}33643365#ifdef PNG_16BIT_SUPPORTED3366/* Internal function to build a single 16-bit table - the table consists of3367* 'num' 256 entry subtables, where 'num' is determined by 'shift' - the amount3368* to shift the input values right (or 16-number_of_signifiant_bits).3369*3370* The caller is responsible for ensuring that the table gets cleaned up on3371* png_error (i.e. if one of the mallocs below fails) - i.e. the *table argument3372* should be somewhere that will be cleaned.3373*/3374static void3375png_build_16bit_table(png_structrp png_ptr, png_uint_16pp *ptable,3376unsigned int shift, png_fixed_point gamma_val)3377{3378/* Various values derived from 'shift': */3379unsigned int num = 1U << (8U - shift);3380#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3381/* CSE the division and work round wacky GCC warnings (see the comments3382* in png_gamma_8bit_correct for where these come from.)3383*/3384double fmax = 1.0 / (((png_int_32)1 << (16U - shift)) - 1);3385#endif3386unsigned int max = (1U << (16U - shift)) - 1U;3387unsigned int max_by_2 = 1U << (15U - shift);3388unsigned int i;33893390png_uint_16pp table = *ptable =3391(png_uint_16pp)png_calloc(png_ptr, num * (sizeof (png_uint_16p)));33923393for (i = 0; i < num; i++)3394{3395png_uint_16p sub_table = table[i] =3396(png_uint_16p)png_malloc(png_ptr, 256 * (sizeof (png_uint_16)));33973398/* The 'threshold' test is repeated here because it can arise for one of3399* the 16-bit tables even if the others don't hit it.3400*/3401if (png_gamma_significant(gamma_val) != 0)3402{3403/* The old code would overflow at the end and this would cause the3404* 'pow' function to return a result >1, resulting in an3405* arithmetic error. This code follows the spec exactly; ig is3406* the recovered input sample, it always has 8-16 bits.3407*3408* We want input * 65535/max, rounded, the arithmetic fits in 323409* bits (unsigned) so long as max <= 32767.3410*/3411unsigned int j;3412for (j = 0; j < 256; j++)3413{3414png_uint_32 ig = (j << (8-shift)) + i;3415# ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3416/* Inline the 'max' scaling operation: */3417/* See png_gamma_8bit_correct for why the cast to (int) is3418* required here.3419*/3420double d = floor(65535.*pow(ig*fmax, gamma_val*.00001)+.5);3421sub_table[j] = (png_uint_16)d;3422# else3423if (shift != 0)3424ig = (ig * 65535U + max_by_2)/max;34253426sub_table[j] = png_gamma_16bit_correct(ig, gamma_val);3427# endif3428}3429}3430else3431{3432/* We must still build a table, but do it the fast way. */3433unsigned int j;34343435for (j = 0; j < 256; j++)3436{3437png_uint_32 ig = (j << (8-shift)) + i;34383439if (shift != 0)3440ig = (ig * 65535U + max_by_2)/max;34413442sub_table[j] = (png_uint_16)ig;3443}3444}3445}3446}34473448/* NOTE: this function expects the *inverse* of the overall gamma transformation3449* required.3450*/3451static void3452png_build_16to8_table(png_structrp png_ptr, png_uint_16pp *ptable,3453unsigned int shift, png_fixed_point gamma_val)3454{3455unsigned int num = 1U << (8U - shift);3456unsigned int max = (1U << (16U - shift))-1U;3457unsigned int i;3458png_uint_32 last;34593460png_uint_16pp table = *ptable =3461(png_uint_16pp)png_calloc(png_ptr, num * (sizeof (png_uint_16p)));34623463/* 'num' is the number of tables and also the number of low bits of low3464* bits of the input 16-bit value used to select a table. Each table is3465* itself indexed by the high 8 bits of the value.3466*/3467for (i = 0; i < num; i++)3468table[i] = (png_uint_16p)png_malloc(png_ptr,3469256 * (sizeof (png_uint_16)));34703471/* 'gamma_val' is set to the reciprocal of the value calculated above, so3472* pow(out,g) is an *input* value. 'last' is the last input value set.3473*3474* In the loop 'i' is used to find output values. Since the output is3475* 8-bit there are only 256 possible values. The tables are set up to3476* select the closest possible output value for each input by finding3477* the input value at the boundary between each pair of output values3478* and filling the table up to that boundary with the lower output3479* value.3480*3481* The boundary values are 0.5,1.5..253.5,254.5. Since these are 9-bit3482* values the code below uses a 16-bit value in i; the values start at3483* 128.5 (for 0.5) and step by 257, for a total of 254 values (the last3484* entries are filled with 255). Start i at 128 and fill all 'last'3485* table entries <= 'max'3486*/3487last = 0;3488for (i = 0; i < 255; ++i) /* 8-bit output value */3489{3490/* Find the corresponding maximum input value */3491png_uint_16 out = (png_uint_16)(i * 257U); /* 16-bit output value */34923493/* Find the boundary value in 16 bits: */3494png_uint_32 bound = png_gamma_16bit_correct(out+128U, gamma_val);34953496/* Adjust (round) to (16-shift) bits: */3497bound = (bound * max + 32768U)/65535U + 1U;34983499while (last < bound)3500{3501table[last & (0xffU >> shift)][last >> (8U - shift)] = out;3502last++;3503}3504}35053506/* And fill in the final entries. */3507while (last < (num << 8))3508{3509table[last & (0xff >> shift)][last >> (8U - shift)] = 65535U;3510last++;3511}3512}3513#endif /* 16BIT */35143515/* Build a single 8-bit table: same as the 16-bit case but much simpler (and3516* typically much faster). Note that libpng currently does no sBIT processing3517* (apparently contrary to the spec) so a 256-entry table is always generated.3518*/3519static void3520png_build_8bit_table(png_structrp png_ptr, png_bytepp ptable,3521png_fixed_point gamma_val)3522{3523unsigned int i;3524png_bytep table = *ptable = (png_bytep)png_malloc(png_ptr, 256);35253526if (png_gamma_significant(gamma_val) != 0)3527for (i=0; i<256; i++)3528table[i] = png_gamma_8bit_correct(i, gamma_val);35293530else3531for (i=0; i<256; ++i)3532table[i] = (png_byte)(i & 0xff);3533}35343535/* Used from png_read_destroy and below to release the memory used by the gamma3536* tables.3537*/3538void /* PRIVATE */3539png_destroy_gamma_table(png_structrp png_ptr)3540{3541png_free(png_ptr, png_ptr->gamma_table);3542png_ptr->gamma_table = NULL;35433544#ifdef PNG_16BIT_SUPPORTED3545if (png_ptr->gamma_16_table != NULL)3546{3547int i;3548int istop = (1 << (8 - png_ptr->gamma_shift));3549for (i = 0; i < istop; i++)3550{3551png_free(png_ptr, png_ptr->gamma_16_table[i]);3552}3553png_free(png_ptr, png_ptr->gamma_16_table);3554png_ptr->gamma_16_table = NULL;3555}3556#endif /* 16BIT */35573558#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \3559defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \3560defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)3561png_free(png_ptr, png_ptr->gamma_from_1);3562png_ptr->gamma_from_1 = NULL;3563png_free(png_ptr, png_ptr->gamma_to_1);3564png_ptr->gamma_to_1 = NULL;35653566#ifdef PNG_16BIT_SUPPORTED3567if (png_ptr->gamma_16_from_1 != NULL)3568{3569int i;3570int istop = (1 << (8 - png_ptr->gamma_shift));3571for (i = 0; i < istop; i++)3572{3573png_free(png_ptr, png_ptr->gamma_16_from_1[i]);3574}3575png_free(png_ptr, png_ptr->gamma_16_from_1);3576png_ptr->gamma_16_from_1 = NULL;3577}3578if (png_ptr->gamma_16_to_1 != NULL)3579{3580int i;3581int istop = (1 << (8 - png_ptr->gamma_shift));3582for (i = 0; i < istop; i++)3583{3584png_free(png_ptr, png_ptr->gamma_16_to_1[i]);3585}3586png_free(png_ptr, png_ptr->gamma_16_to_1);3587png_ptr->gamma_16_to_1 = NULL;3588}3589#endif /* 16BIT */3590#endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */3591}35923593/* We build the 8- or 16-bit gamma tables here. Note that for 16-bit3594* tables, we don't make a full table if we are reducing to 8-bit in3595* the future. Note also how the gamma_16 tables are segmented so that3596* we don't need to allocate > 64K chunks for a full 16-bit table.3597*3598* TODO: move this to pngrtran.c and make it static. Better yet create3599* pngcolor.c and put all the PNG_COLORSPACE stuff in there.3600*/3601#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \3602defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \3603defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)3604# define GAMMA_TRANSFORMS 1 /* #ifdef CSE */3605#else3606# define GAMMA_TRANSFORMS 03607#endif36083609void /* PRIVATE */3610png_build_gamma_table(png_structrp png_ptr, int bit_depth)3611{3612png_fixed_point file_gamma, screen_gamma;3613png_fixed_point correction;3614# if GAMMA_TRANSFORMS3615png_fixed_point file_to_linear, linear_to_screen;3616# endif36173618png_debug(1, "in png_build_gamma_table");36193620/* Remove any existing table; this copes with multiple calls to3621* png_read_update_info. The warning is because building the gamma tables3622* multiple times is a performance hit - it's harmless but the ability to3623* call png_read_update_info() multiple times is new in 1.5.6 so it seems3624* sensible to warn if the app introduces such a hit.3625*/3626if (png_ptr->gamma_table != NULL || png_ptr->gamma_16_table != NULL)3627{3628png_warning(png_ptr, "gamma table being rebuilt");3629png_destroy_gamma_table(png_ptr);3630}36313632/* The following fields are set, finally, in png_init_read_transformations.3633* If file_gamma is 0 (unset) nothing can be done otherwise if screen_gamma3634* is 0 (unset) there is no gamma correction but to/from linear is possible.3635*/3636file_gamma = png_ptr->file_gamma;3637screen_gamma = png_ptr->screen_gamma;3638# if GAMMA_TRANSFORMS3639file_to_linear = png_reciprocal(file_gamma);3640# endif36413642if (screen_gamma > 0)3643{3644# if GAMMA_TRANSFORMS3645linear_to_screen = png_reciprocal(screen_gamma);3646# endif3647correction = png_reciprocal2(screen_gamma, file_gamma);3648}3649else /* screen gamma unknown */3650{3651# if GAMMA_TRANSFORMS3652linear_to_screen = file_gamma;3653# endif3654correction = PNG_FP_1;3655}36563657if (bit_depth <= 8)3658{3659png_build_8bit_table(png_ptr, &png_ptr->gamma_table, correction);36603661#if GAMMA_TRANSFORMS3662if ((png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY)) != 0)3663{3664png_build_8bit_table(png_ptr, &png_ptr->gamma_to_1, file_to_linear);36653666png_build_8bit_table(png_ptr, &png_ptr->gamma_from_1,3667linear_to_screen);3668}3669#endif /* GAMMA_TRANSFORMS */3670}3671#ifdef PNG_16BIT_SUPPORTED3672else3673{3674png_byte shift, sig_bit;36753676if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)3677{3678sig_bit = png_ptr->sig_bit.red;36793680if (png_ptr->sig_bit.green > sig_bit)3681sig_bit = png_ptr->sig_bit.green;36823683if (png_ptr->sig_bit.blue > sig_bit)3684sig_bit = png_ptr->sig_bit.blue;3685}3686else3687sig_bit = png_ptr->sig_bit.gray;36883689/* 16-bit gamma code uses this equation:3690*3691* ov = table[(iv & 0xff) >> gamma_shift][iv >> 8]3692*3693* Where 'iv' is the input color value and 'ov' is the output value -3694* pow(iv, gamma).3695*3696* Thus the gamma table consists of up to 256 256-entry tables. The table3697* is selected by the (8-gamma_shift) most significant of the low 8 bits3698* of the color value then indexed by the upper 8 bits:3699*3700* table[low bits][high 8 bits]3701*3702* So the table 'n' corresponds to all those 'iv' of:3703*3704* <all high 8-bit values><n << gamma_shift>..<(n+1 << gamma_shift)-1>3705*3706*/3707if (sig_bit > 0 && sig_bit < 16U)3708/* shift == insignificant bits */3709shift = (png_byte)((16U - sig_bit) & 0xff);37103711else3712shift = 0; /* keep all 16 bits */37133714if ((png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8)) != 0)3715{3716/* PNG_MAX_GAMMA_8 is the number of bits to keep - effectively3717* the significant bits in the *input* when the output will3718* eventually be 8 bits. By default it is 11.3719*/3720if (shift < (16U - PNG_MAX_GAMMA_8))3721shift = (16U - PNG_MAX_GAMMA_8);3722}37233724if (shift > 8U)3725shift = 8U; /* Guarantees at least one table! */37263727png_ptr->gamma_shift = shift;37283729/* NOTE: prior to 1.5.4 this test used to include PNG_BACKGROUND (now3730* PNG_COMPOSE). This effectively smashed the background calculation for3731* 16-bit output because the 8-bit table assumes the result will be3732* reduced to 8 bits.3733*/3734if ((png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8)) != 0)3735png_build_16to8_table(png_ptr, &png_ptr->gamma_16_table, shift,3736png_reciprocal(correction));3737else3738png_build_16bit_table(png_ptr, &png_ptr->gamma_16_table, shift,3739correction);37403741# if GAMMA_TRANSFORMS3742if ((png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY)) != 0)3743{3744png_build_16bit_table(png_ptr, &png_ptr->gamma_16_to_1, shift,3745file_to_linear);37463747/* Notice that the '16 from 1' table should be full precision, however3748* the lookup on this table still uses gamma_shift, so it can't be.3749* TODO: fix this.3750*/3751png_build_16bit_table(png_ptr, &png_ptr->gamma_16_from_1, shift,3752linear_to_screen);3753}3754#endif /* GAMMA_TRANSFORMS */3755}3756#endif /* 16BIT */3757}3758#endif /* READ_GAMMA */37593760/* HARDWARE OR SOFTWARE OPTION SUPPORT */3761#ifdef PNG_SET_OPTION_SUPPORTED3762int PNGAPI3763png_set_option(png_structrp png_ptr, int option, int onoff)3764{3765if (png_ptr != NULL && option >= 0 && option < PNG_OPTION_NEXT &&3766(option & 1) == 0)3767{3768png_uint_32 mask = 3U << option;3769png_uint_32 setting = (2U + (onoff != 0)) << option;3770png_uint_32 current = png_ptr->options;37713772png_ptr->options = (png_uint_32)((current & ~mask) | setting);37733774return (int)(current & mask) >> option;3775}37763777return PNG_OPTION_INVALID;3778}3779#endif37803781/* sRGB support */3782#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\3783defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)3784/* sRGB conversion tables; these are machine generated with the code in3785* contrib/tools/makesRGB.c. The actual sRGB transfer curve defined in the3786* specification (see the article at https://en.wikipedia.org/wiki/SRGB)3787* is used, not the gamma=1/2.2 approximation use elsewhere in libpng.3788* The sRGB to linear table is exact (to the nearest 16-bit linear fraction).3789* The inverse (linear to sRGB) table has accuracies as follows:3790*3791* For all possible (255*65535+1) input values:3792*3793* error: -0.515566 - 0.625971, 79441 (0.475369%) of readings inexact3794*3795* For the input values corresponding to the 65536 16-bit values:3796*3797* error: -0.513727 - 0.607759, 308 (0.469978%) of readings inexact3798*3799* In all cases the inexact readings are only off by one.3800*/38013802#ifdef PNG_SIMPLIFIED_READ_SUPPORTED3803/* The convert-to-sRGB table is only currently required for read. */3804const png_uint_16 png_sRGB_table[256] =3805{38060,20,40,60,80,99,119,139,3807159,179,199,219,241,264,288,313,3808340,367,396,427,458,491,526,562,3809599,637,677,718,761,805,851,898,3810947,997,1048,1101,1156,1212,1270,1330,38111391,1453,1517,1583,1651,1720,1790,1863,38121937,2013,2090,2170,2250,2333,2418,2504,38132592,2681,2773,2866,2961,3058,3157,3258,38143360,3464,3570,3678,3788,3900,4014,4129,38154247,4366,4488,4611,4736,4864,4993,5124,38165257,5392,5530,5669,5810,5953,6099,6246,38176395,6547,6700,6856,7014,7174,7335,7500,38187666,7834,8004,8177,8352,8528,8708,8889,38199072,9258,9445,9635,9828,10022,10219,10417,382010619,10822,11028,11235,11446,11658,11873,12090,382112309,12530,12754,12980,13209,13440,13673,13909,382214146,14387,14629,14874,15122,15371,15623,15878,382316135,16394,16656,16920,17187,17456,17727,18001,382418277,18556,18837,19121,19407,19696,19987,20281,382520577,20876,21177,21481,21787,22096,22407,22721,382623038,23357,23678,24002,24329,24658,24990,25325,382725662,26001,26344,26688,27036,27386,27739,28094,382828452,28813,29176,29542,29911,30282,30656,31033,382931412,31794,32179,32567,32957,33350,33745,34143,383034544,34948,35355,35764,36176,36591,37008,37429,383137852,38278,38706,39138,39572,40009,40449,40891,383241337,41785,42236,42690,43147,43606,44069,44534,383345002,45473,45947,46423,46903,47385,47871,48359,383448850,49344,49841,50341,50844,51349,51858,52369,383552884,53401,53921,54445,54971,55500,56032,56567,383657105,57646,58190,58737,59287,59840,60396,60955,383761517,62082,62650,63221,63795,64372,64952,655353838};3839#endif /* SIMPLIFIED_READ */38403841/* The base/delta tables are required for both read and write (but currently3842* only the simplified versions.)3843*/3844const png_uint_16 png_sRGB_base[512] =3845{3846128,1782,3383,4644,5675,6564,7357,8074,38478732,9346,9921,10463,10977,11466,11935,12384,384812816,13233,13634,14024,14402,14769,15125,15473,384915812,16142,16466,16781,17090,17393,17690,17981,385018266,18546,18822,19093,19359,19621,19879,20133,385120383,20630,20873,21113,21349,21583,21813,22041,385222265,22487,22707,22923,23138,23350,23559,23767,385323972,24175,24376,24575,24772,24967,25160,25352,385425542,25730,25916,26101,26284,26465,26645,26823,385527000,27176,27350,27523,27695,27865,28034,28201,385628368,28533,28697,28860,29021,29182,29341,29500,385729657,29813,29969,30123,30276,30429,30580,30730,385830880,31028,31176,31323,31469,31614,31758,31902,385932045,32186,32327,32468,32607,32746,32884,33021,386033158,33294,33429,33564,33697,33831,33963,34095,386134226,34357,34486,34616,34744,34873,35000,35127,386235253,35379,35504,35629,35753,35876,35999,36122,386336244,36365,36486,36606,36726,36845,36964,37083,386437201,37318,37435,37551,37668,37783,37898,38013,386538127,38241,38354,38467,38580,38692,38803,38915,386639026,39136,39246,39356,39465,39574,39682,39790,386739898,40005,40112,40219,40325,40431,40537,40642,386840747,40851,40955,41059,41163,41266,41369,41471,386941573,41675,41777,41878,41979,42079,42179,42279,387042379,42478,42577,42676,42775,42873,42971,43068,387143165,43262,43359,43456,43552,43648,43743,43839,387243934,44028,44123,44217,44311,44405,44499,44592,387344685,44778,44870,44962,45054,45146,45238,45329,387445420,45511,45601,45692,45782,45872,45961,46051,387546140,46229,46318,46406,46494,46583,46670,46758,387646846,46933,47020,47107,47193,47280,47366,47452,387747538,47623,47709,47794,47879,47964,48048,48133,387848217,48301,48385,48468,48552,48635,48718,48801,387948884,48966,49048,49131,49213,49294,49376,49458,388049539,49620,49701,49782,49862,49943,50023,50103,388150183,50263,50342,50422,50501,50580,50659,50738,388250816,50895,50973,51051,51129,51207,51285,51362,388351439,51517,51594,51671,51747,51824,51900,51977,388452053,52129,52205,52280,52356,52432,52507,52582,388552657,52732,52807,52881,52956,53030,53104,53178,388653252,53326,53400,53473,53546,53620,53693,53766,388753839,53911,53984,54056,54129,54201,54273,54345,388854417,54489,54560,54632,54703,54774,54845,54916,388954987,55058,55129,55199,55269,55340,55410,55480,389055550,55620,55689,55759,55828,55898,55967,56036,389156105,56174,56243,56311,56380,56448,56517,56585,389256653,56721,56789,56857,56924,56992,57059,57127,389357194,57261,57328,57395,57462,57529,57595,57662,389457728,57795,57861,57927,57993,58059,58125,58191,389558256,58322,58387,58453,58518,58583,58648,58713,389658778,58843,58908,58972,59037,59101,59165,59230,389759294,59358,59422,59486,59549,59613,59677,59740,389859804,59867,59930,59993,60056,60119,60182,60245,389960308,60370,60433,60495,60558,60620,60682,60744,390060806,60868,60930,60992,61054,61115,61177,61238,390161300,61361,61422,61483,61544,61605,61666,61727,390261788,61848,61909,61969,62030,62090,62150,62211,390362271,62331,62391,62450,62510,62570,62630,62689,390462749,62808,62867,62927,62986,63045,63104,63163,390563222,63281,63340,63398,63457,63515,63574,63632,390663691,63749,63807,63865,63923,63981,64039,64097,390764155,64212,64270,64328,64385,64443,64500,64557,390864614,64672,64729,64786,64843,64900,64956,65013,390965070,65126,65183,65239,65296,65352,65409,654653910};39113912const png_byte png_sRGB_delta[512] =3913{3914207,201,158,129,113,100,90,82,77,72,68,64,61,59,56,54,391552,50,49,47,46,45,43,42,41,40,39,39,38,37,36,36,391635,34,34,33,33,32,32,31,31,30,30,30,29,29,28,28,391728,27,27,27,27,26,26,26,25,25,25,25,24,24,24,24,391823,23,23,23,23,22,22,22,22,22,22,21,21,21,21,21,391921,20,20,20,20,20,20,20,20,19,19,19,19,19,19,19,392019,18,18,18,18,18,18,18,18,18,18,17,17,17,17,17,392117,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,392216,16,16,16,15,15,15,15,15,15,15,15,15,15,15,15,392315,15,15,15,14,14,14,14,14,14,14,14,14,14,14,14,392414,14,14,14,14,14,14,13,13,13,13,13,13,13,13,13,392513,13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,392612,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,392712,12,12,12,12,12,12,12,12,12,12,12,11,11,11,11,392811,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,392911,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,393011,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,393110,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,393210,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,393310,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,39349,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,39359,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,39369,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,39379,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,39388,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,39398,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,39408,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,39418,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,39428,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,39437,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,39447,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,39457,7,7,7,7,7,7,7,7,7,7,7,7,7,7,73946};3947#endif /* SIMPLIFIED READ/WRITE sRGB support */39483949/* SIMPLIFIED READ/WRITE SUPPORT */3950#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\3951defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)3952static int3953png_image_free_function(png_voidp argument)3954{3955png_imagep image = png_voidcast(png_imagep, argument);3956png_controlp cp = image->opaque;3957png_control c;39583959/* Double check that we have a png_ptr - it should be impossible to get here3960* without one.3961*/3962if (cp->png_ptr == NULL)3963return 0;39643965/* First free any data held in the control structure. */3966# ifdef PNG_STDIO_SUPPORTED3967if (cp->owned_file != 0)3968{3969FILE *fp = png_voidcast(FILE *, cp->png_ptr->io_ptr);3970cp->owned_file = 0;39713972/* Ignore errors here. */3973if (fp != NULL)3974{3975cp->png_ptr->io_ptr = NULL;3976(void)fclose(fp);3977}3978}3979# endif39803981/* Copy the control structure so that the original, allocated, version can be3982* safely freed. Notice that a png_error here stops the remainder of the3983* cleanup, but this is probably fine because that would indicate bad memory3984* problems anyway.3985*/3986c = *cp;3987image->opaque = &c;3988png_free(c.png_ptr, cp);39893990/* Then the structures, calling the correct API. */3991if (c.for_write != 0)3992{3993# ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED3994png_destroy_write_struct(&c.png_ptr, &c.info_ptr);3995# else3996png_error(c.png_ptr, "simplified write not supported");3997# endif3998}3999else4000{4001# ifdef PNG_SIMPLIFIED_READ_SUPPORTED4002png_destroy_read_struct(&c.png_ptr, &c.info_ptr, NULL);4003# else4004png_error(c.png_ptr, "simplified read not supported");4005# endif4006}40074008/* Success. */4009return 1;4010}40114012void PNGAPI4013png_image_free(png_imagep image)4014{4015/* Safely call the real function, but only if doing so is safe at this point4016* (if not inside an error handling context). Otherwise assume4017* png_safe_execute will call this API after the return.4018*/4019if (image != NULL && image->opaque != NULL &&4020image->opaque->error_buf == NULL)4021{4022png_image_free_function(image);4023image->opaque = NULL;4024}4025}40264027int /* PRIVATE */4028png_image_error(png_imagep image, png_const_charp error_message)4029{4030/* Utility to log an error. */4031png_safecat(image->message, (sizeof image->message), 0, error_message);4032image->warning_or_error |= PNG_IMAGE_ERROR;4033png_image_free(image);4034return 0;4035}40364037#endif /* SIMPLIFIED READ/WRITE */4038#endif /* READ || WRITE */403940404041