/* png.c - location for general purpose libpng functions1*2* Copyright (c) 2018-2026 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_54 Your_png_h_is_not_version_1_6_54;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),104PNG_ALLOCATED)105{106png_alloc_size_t num_bytes = size;107108if (png_ptr == NULL)109return NULL;110111/* This check against overflow is vestigial, dating back from112* the old times when png_zalloc used to be an exported function.113* We're still keeping it here for now, as an extra-cautious114* prevention against programming errors inside zlib, although it115* should rather be a debug-time assertion instead.116*/117if (size != 0 && items >= (~(png_alloc_size_t)0) / size)118{119png_warning(png_voidcast(png_structrp, png_ptr),120"Potential overflow in png_zalloc()");121return NULL;122}123124num_bytes *= items;125return png_malloc_warn(png_voidcast(png_structrp, png_ptr), num_bytes);126}127128/* Function to free memory for zlib */129void /* PRIVATE */130png_zfree(voidpf png_ptr, voidpf ptr)131{132png_free(png_voidcast(png_const_structrp,png_ptr), ptr);133}134135/* Reset the CRC variable to 32 bits of 1's. Care must be taken136* in case CRC is > 32 bits to leave the top bits 0.137*/138void /* PRIVATE */139png_reset_crc(png_structrp png_ptr)140{141/* The cast is safe because the crc is a 32-bit value. */142png_ptr->crc = (png_uint_32)crc32(0, Z_NULL, 0);143}144145/* Calculate the CRC over a section of data. We can only pass as146* much data to this routine as the largest single buffer size. We147* also check that this data will actually be used before going to the148* trouble of calculating it.149*/150void /* PRIVATE */151png_calculate_crc(png_structrp png_ptr, png_const_bytep ptr, size_t length)152{153int need_crc = 1;154155if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0)156{157if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==158(PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))159need_crc = 0;160}161162else /* critical */163{164if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0)165need_crc = 0;166}167168/* 'uLong' is defined in zlib.h as unsigned long; this means that on some169* systems it is a 64-bit value. crc32, however, returns 32 bits so the170* following cast is safe. 'uInt' may be no more than 16 bits, so it is171* necessary to perform a loop here.172*/173if (need_crc != 0 && length > 0)174{175uLong crc = png_ptr->crc; /* Should never issue a warning */176177do178{179uInt safe_length = (uInt)length;180#ifndef __COVERITY__181if (safe_length == 0)182safe_length = (uInt)-1; /* evil, but safe */183#endif184185crc = crc32(crc, ptr, safe_length);186187/* The following should never issue compiler warnings; if they do the188* target system has characteristics that will probably violate other189* assumptions within the libpng code.190*/191ptr += safe_length;192length -= safe_length;193}194while (length > 0);195196/* And the following is always safe because the crc is only 32 bits. */197png_ptr->crc = (png_uint_32)crc;198}199}200201/* Check a user supplied version number, called from both read and write202* functions that create a png_struct.203*/204int205png_user_version_check(png_structrp png_ptr, png_const_charp user_png_ver)206{207/* Libpng versions 1.0.0 and later are binary compatible if the version208* string matches through the second '.'; we must recompile any209* applications that use any older library version.210*/211212if (user_png_ver != NULL)213{214int i = -1;215int found_dots = 0;216217do218{219i++;220if (user_png_ver[i] != PNG_LIBPNG_VER_STRING[i])221png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;222if (user_png_ver[i] == '.')223found_dots++;224} while (found_dots < 2 && user_png_ver[i] != 0 &&225PNG_LIBPNG_VER_STRING[i] != 0);226}227228else229png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;230231if ((png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH) != 0)232{233#ifdef PNG_WARNINGS_SUPPORTED234size_t pos = 0;235char m[128];236237pos = png_safecat(m, (sizeof m), pos,238"Application built with libpng-");239pos = png_safecat(m, (sizeof m), pos, user_png_ver);240pos = png_safecat(m, (sizeof m), pos, " but running with ");241pos = png_safecat(m, (sizeof m), pos, PNG_LIBPNG_VER_STRING);242PNG_UNUSED(pos)243244png_warning(png_ptr, m);245#endif246247return 0;248}249250/* Success return. */251return 1;252}253254/* Generic function to create a png_struct for either read or write - this255* contains the common initialization.256*/257PNG_FUNCTION(png_structp /* PRIVATE */,258png_create_png_struct,(png_const_charp user_png_ver, png_voidp error_ptr,259png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,260png_malloc_ptr malloc_fn, png_free_ptr free_fn),261PNG_ALLOCATED)262{263png_struct create_struct;264# ifdef PNG_SETJMP_SUPPORTED265jmp_buf create_jmp_buf;266# endif267268/* This temporary stack-allocated structure is used to provide a place to269* build enough context to allow the user provided memory allocator (if any)270* to be called.271*/272memset(&create_struct, 0, (sizeof create_struct));273274# ifdef PNG_USER_LIMITS_SUPPORTED275create_struct.user_width_max = PNG_USER_WIDTH_MAX;276create_struct.user_height_max = PNG_USER_HEIGHT_MAX;277278# ifdef PNG_USER_CHUNK_CACHE_MAX279create_struct.user_chunk_cache_max = PNG_USER_CHUNK_CACHE_MAX;280# endif281282# if PNG_USER_CHUNK_MALLOC_MAX > 0 /* default to compile-time limit */283create_struct.user_chunk_malloc_max = PNG_USER_CHUNK_MALLOC_MAX;284285/* No compile-time limit, so initialize to the system limit: */286# elif defined PNG_MAX_MALLOC_64K /* legacy system limit */287create_struct.user_chunk_malloc_max = 65536U;288289# else /* modern system limit SIZE_MAX (C99) */290create_struct.user_chunk_malloc_max = PNG_SIZE_MAX;291# endif292# endif293294/* The following two API calls simply set fields in png_struct, so it is safe295* to do them now even though error handling is not yet set up.296*/297# ifdef PNG_USER_MEM_SUPPORTED298png_set_mem_fn(&create_struct, mem_ptr, malloc_fn, free_fn);299# else300PNG_UNUSED(mem_ptr)301PNG_UNUSED(malloc_fn)302PNG_UNUSED(free_fn)303# endif304305/* (*error_fn) can return control to the caller after the error_ptr is set,306* this will result in a memory leak unless the error_fn does something307* extremely sophisticated. The design lacks merit but is implicit in the308* API.309*/310png_set_error_fn(&create_struct, error_ptr, error_fn, warn_fn);311312# ifdef PNG_SETJMP_SUPPORTED313if (!setjmp(create_jmp_buf))314# endif315{316# ifdef PNG_SETJMP_SUPPORTED317/* Temporarily fake out the longjmp information until we have318* successfully completed this function. This only works if we have319* setjmp() support compiled in, but it is safe - this stuff should320* never happen.321*/322create_struct.jmp_buf_ptr = &create_jmp_buf;323create_struct.jmp_buf_size = 0; /*stack allocation*/324create_struct.longjmp_fn = longjmp;325# endif326/* Call the general version checker (shared with read and write code):327*/328if (png_user_version_check(&create_struct, user_png_ver) != 0)329{330png_structrp png_ptr = png_voidcast(png_structrp,331png_malloc_warn(&create_struct, (sizeof *png_ptr)));332333if (png_ptr != NULL)334{335/* png_ptr->zstream holds a back-pointer to the png_struct, so336* this can only be done now:337*/338create_struct.zstream.zalloc = png_zalloc;339create_struct.zstream.zfree = png_zfree;340create_struct.zstream.opaque = png_ptr;341342# ifdef PNG_SETJMP_SUPPORTED343/* Eliminate the local error handling: */344create_struct.jmp_buf_ptr = NULL;345create_struct.jmp_buf_size = 0;346create_struct.longjmp_fn = 0;347# endif348349*png_ptr = create_struct;350351/* This is the successful return point */352return png_ptr;353}354}355}356357/* A longjmp because of a bug in the application storage allocator or a358* simple failure to allocate the png_struct.359*/360return NULL;361}362363/* Allocate the memory for an info_struct for the application. */364PNG_FUNCTION(png_infop,PNGAPI365png_create_info_struct,(png_const_structrp png_ptr),366PNG_ALLOCATED)367{368png_inforp info_ptr;369370png_debug(1, "in png_create_info_struct");371372if (png_ptr == NULL)373return NULL;374375/* Use the internal API that does not (or at least should not) error out, so376* that this call always returns ok. The application typically sets up the377* error handling *after* creating the info_struct because this is the way it378* has always been done in 'example.c'.379*/380info_ptr = png_voidcast(png_inforp, png_malloc_base(png_ptr,381(sizeof *info_ptr)));382383if (info_ptr != NULL)384memset(info_ptr, 0, (sizeof *info_ptr));385386return info_ptr;387}388389/* This function frees the memory associated with a single info struct.390* Normally, one would use either png_destroy_read_struct() or391* png_destroy_write_struct() to free an info struct, but this may be392* useful for some applications. From libpng 1.6.0 this function is also used393* internally to implement the png_info release part of the 'struct' destroy394* APIs. This ensures that all possible approaches free the same data (all of395* it).396*/397void PNGAPI398png_destroy_info_struct(png_const_structrp png_ptr, png_infopp info_ptr_ptr)399{400png_inforp info_ptr = NULL;401402png_debug(1, "in png_destroy_info_struct");403404if (png_ptr == NULL)405return;406407if (info_ptr_ptr != NULL)408info_ptr = *info_ptr_ptr;409410if (info_ptr != NULL)411{412/* Do this first in case of an error below; if the app implements its own413* memory management this can lead to png_free calling png_error, which414* will abort this routine and return control to the app error handler.415* An infinite loop may result if it then tries to free the same info416* ptr.417*/418*info_ptr_ptr = NULL;419420png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);421memset(info_ptr, 0, (sizeof *info_ptr));422png_free(png_ptr, info_ptr);423}424}425426/* Initialize the info structure. This is now an internal function (0.89)427* and applications using it are urged to use png_create_info_struct()428* instead. Use deprecated in 1.6.0, internal use removed (used internally it429* is just a memset).430*431* NOTE: it is almost inconceivable that this API is used because it bypasses432* the user-memory mechanism and the user error handling/warning mechanisms in433* those cases where it does anything other than a memset.434*/435PNG_FUNCTION(void,PNGAPI436png_info_init_3,(png_infopp ptr_ptr, size_t png_info_struct_size),437PNG_DEPRECATED)438{439png_inforp info_ptr = *ptr_ptr;440441png_debug(1, "in png_info_init_3");442443if (info_ptr == NULL)444return;445446if ((sizeof (png_info)) > png_info_struct_size)447{448*ptr_ptr = NULL;449/* The following line is why this API should not be used: */450free(info_ptr);451info_ptr = png_voidcast(png_inforp, png_malloc_base(NULL,452(sizeof *info_ptr)));453if (info_ptr == NULL)454return;455*ptr_ptr = info_ptr;456}457458/* Set everything to 0 */459memset(info_ptr, 0, (sizeof *info_ptr));460}461462void PNGAPI463png_data_freer(png_const_structrp png_ptr, png_inforp info_ptr,464int freer, png_uint_32 mask)465{466png_debug(1, "in png_data_freer");467468if (png_ptr == NULL || info_ptr == NULL)469return;470471if (freer == PNG_DESTROY_WILL_FREE_DATA)472info_ptr->free_me |= mask;473474else if (freer == PNG_USER_WILL_FREE_DATA)475info_ptr->free_me &= ~mask;476477else478png_error(png_ptr, "Unknown freer parameter in png_data_freer");479}480481void PNGAPI482png_free_data(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 mask,483int num)484{485png_debug(1, "in png_free_data");486487if (png_ptr == NULL || info_ptr == NULL)488return;489490#ifdef PNG_TEXT_SUPPORTED491/* Free text item num or (if num == -1) all text items */492if (info_ptr->text != NULL &&493((mask & PNG_FREE_TEXT) & info_ptr->free_me) != 0)494{495if (num != -1)496{497png_free(png_ptr, info_ptr->text[num].key);498info_ptr->text[num].key = NULL;499}500501else502{503int i;504505for (i = 0; i < info_ptr->num_text; i++)506png_free(png_ptr, info_ptr->text[i].key);507508png_free(png_ptr, info_ptr->text);509info_ptr->text = NULL;510info_ptr->num_text = 0;511info_ptr->max_text = 0;512}513}514#endif515516#ifdef PNG_tRNS_SUPPORTED517/* Free any tRNS entry */518if (((mask & PNG_FREE_TRNS) & info_ptr->free_me) != 0)519{520info_ptr->valid &= ~PNG_INFO_tRNS;521png_free(png_ptr, info_ptr->trans_alpha);522info_ptr->trans_alpha = NULL;523info_ptr->num_trans = 0;524}525#endif526527#ifdef PNG_sCAL_SUPPORTED528/* Free any sCAL entry */529if (((mask & PNG_FREE_SCAL) & info_ptr->free_me) != 0)530{531png_free(png_ptr, info_ptr->scal_s_width);532png_free(png_ptr, info_ptr->scal_s_height);533info_ptr->scal_s_width = NULL;534info_ptr->scal_s_height = NULL;535info_ptr->valid &= ~PNG_INFO_sCAL;536}537#endif538539#ifdef PNG_pCAL_SUPPORTED540/* Free any pCAL entry */541if (((mask & PNG_FREE_PCAL) & info_ptr->free_me) != 0)542{543png_free(png_ptr, info_ptr->pcal_purpose);544png_free(png_ptr, info_ptr->pcal_units);545info_ptr->pcal_purpose = NULL;546info_ptr->pcal_units = NULL;547548if (info_ptr->pcal_params != NULL)549{550int i;551552for (i = 0; i < info_ptr->pcal_nparams; i++)553png_free(png_ptr, info_ptr->pcal_params[i]);554555png_free(png_ptr, info_ptr->pcal_params);556info_ptr->pcal_params = NULL;557}558info_ptr->valid &= ~PNG_INFO_pCAL;559}560#endif561562#ifdef PNG_iCCP_SUPPORTED563/* Free any profile entry */564if (((mask & PNG_FREE_ICCP) & info_ptr->free_me) != 0)565{566png_free(png_ptr, info_ptr->iccp_name);567png_free(png_ptr, info_ptr->iccp_profile);568info_ptr->iccp_name = NULL;569info_ptr->iccp_profile = NULL;570info_ptr->valid &= ~PNG_INFO_iCCP;571}572#endif573574#ifdef PNG_sPLT_SUPPORTED575/* Free a given sPLT entry, or (if num == -1) all sPLT entries */576if (info_ptr->splt_palettes != NULL &&577((mask & PNG_FREE_SPLT) & info_ptr->free_me) != 0)578{579if (num != -1)580{581png_free(png_ptr, info_ptr->splt_palettes[num].name);582png_free(png_ptr, info_ptr->splt_palettes[num].entries);583info_ptr->splt_palettes[num].name = NULL;584info_ptr->splt_palettes[num].entries = NULL;585}586587else588{589int i;590591for (i = 0; i < info_ptr->splt_palettes_num; i++)592{593png_free(png_ptr, info_ptr->splt_palettes[i].name);594png_free(png_ptr, info_ptr->splt_palettes[i].entries);595}596597png_free(png_ptr, info_ptr->splt_palettes);598info_ptr->splt_palettes = NULL;599info_ptr->splt_palettes_num = 0;600info_ptr->valid &= ~PNG_INFO_sPLT;601}602}603#endif604605#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED606if (info_ptr->unknown_chunks != NULL &&607((mask & PNG_FREE_UNKN) & info_ptr->free_me) != 0)608{609if (num != -1)610{611png_free(png_ptr, info_ptr->unknown_chunks[num].data);612info_ptr->unknown_chunks[num].data = NULL;613}614615else616{617int i;618619for (i = 0; i < info_ptr->unknown_chunks_num; i++)620png_free(png_ptr, info_ptr->unknown_chunks[i].data);621622png_free(png_ptr, info_ptr->unknown_chunks);623info_ptr->unknown_chunks = NULL;624info_ptr->unknown_chunks_num = 0;625}626}627#endif628629#ifdef PNG_eXIf_SUPPORTED630/* Free any eXIf entry */631if (((mask & PNG_FREE_EXIF) & info_ptr->free_me) != 0)632{633if (info_ptr->exif)634{635png_free(png_ptr, info_ptr->exif);636info_ptr->exif = NULL;637}638info_ptr->valid &= ~PNG_INFO_eXIf;639}640#endif641642#ifdef PNG_hIST_SUPPORTED643/* Free any hIST entry */644if (((mask & PNG_FREE_HIST) & info_ptr->free_me) != 0)645{646png_free(png_ptr, info_ptr->hist);647info_ptr->hist = NULL;648info_ptr->valid &= ~PNG_INFO_hIST;649}650#endif651652/* Free any PLTE entry that was internally allocated */653if (((mask & PNG_FREE_PLTE) & info_ptr->free_me) != 0)654{655png_free(png_ptr, info_ptr->palette);656info_ptr->palette = NULL;657info_ptr->valid &= ~PNG_INFO_PLTE;658info_ptr->num_palette = 0;659}660661#ifdef PNG_INFO_IMAGE_SUPPORTED662/* Free any image bits attached to the info structure */663if (((mask & PNG_FREE_ROWS) & info_ptr->free_me) != 0)664{665if (info_ptr->row_pointers != NULL)666{667png_uint_32 row;668for (row = 0; row < info_ptr->height; row++)669png_free(png_ptr, info_ptr->row_pointers[row]);670671png_free(png_ptr, info_ptr->row_pointers);672info_ptr->row_pointers = NULL;673}674info_ptr->valid &= ~PNG_INFO_IDAT;675}676#endif677678if (num != -1)679mask &= ~PNG_FREE_MUL;680681info_ptr->free_me &= ~mask;682}683#endif /* READ || WRITE */684685/* This function returns a pointer to the io_ptr associated with the user686* functions. The application should free any memory associated with this687* pointer before png_write_destroy() or png_read_destroy() are called.688*/689png_voidp PNGAPI690png_get_io_ptr(png_const_structrp png_ptr)691{692if (png_ptr == NULL)693return NULL;694695return png_ptr->io_ptr;696}697698#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)699# ifdef PNG_STDIO_SUPPORTED700/* Initialize the default input/output functions for the PNG file. If you701* use your own read or write routines, you can call either png_set_read_fn()702* or png_set_write_fn() instead of png_init_io(). If you have defined703* PNG_NO_STDIO or otherwise disabled PNG_STDIO_SUPPORTED, you must use a704* function of your own because "FILE *" isn't necessarily available.705*/706void PNGAPI707png_init_io(png_structrp png_ptr, FILE *fp)708{709png_debug(1, "in png_init_io");710711if (png_ptr == NULL)712return;713714png_ptr->io_ptr = (png_voidp)fp;715}716# endif717718# ifdef PNG_SAVE_INT_32_SUPPORTED719/* PNG signed integers are saved in 32-bit 2's complement format. ANSI C-90720* defines a cast of a signed integer to an unsigned integer either to preserve721* the value, if it is positive, or to calculate:722*723* (UNSIGNED_MAX+1) + integer724*725* Where UNSIGNED_MAX is the appropriate maximum unsigned value, so when the726* negative integral value is added the result will be an unsigned value727* corresponding to the 2's complement representation.728*/729void PNGAPI730png_save_int_32(png_bytep buf, png_int_32 i)731{732png_save_uint_32(buf, (png_uint_32)i);733}734# endif735736# ifdef PNG_TIME_RFC1123_SUPPORTED737/* Convert the supplied time into an RFC 1123 string suitable for use in738* a "Creation Time" or other text-based time string.739*/740int PNGAPI741png_convert_to_rfc1123_buffer(char out[29], png_const_timep ptime)742{743static const char short_months[12][4] =744{"Jan", "Feb", "Mar", "Apr", "May", "Jun",745"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};746747if (out == NULL)748return 0;749750if (ptime->year > 9999 /* RFC1123 limitation */ ||751ptime->month == 0 || ptime->month > 12 ||752ptime->day == 0 || ptime->day > 31 ||753ptime->hour > 23 || ptime->minute > 59 ||754ptime->second > 60)755return 0;756757{758size_t pos = 0;759char number_buf[5] = {0, 0, 0, 0, 0}; /* enough for a four-digit year */760761# define APPEND_STRING(string) pos = png_safecat(out, 29, pos, (string))762# define APPEND_NUMBER(format, value)\763APPEND_STRING(PNG_FORMAT_NUMBER(number_buf, format, (value)))764# define APPEND(ch) if (pos < 28) out[pos++] = (ch)765766APPEND_NUMBER(PNG_NUMBER_FORMAT_u, (unsigned)ptime->day);767APPEND(' ');768APPEND_STRING(short_months[(ptime->month - 1)]);769APPEND(' ');770APPEND_NUMBER(PNG_NUMBER_FORMAT_u, ptime->year);771APPEND(' ');772APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->hour);773APPEND(':');774APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->minute);775APPEND(':');776APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->second);777APPEND_STRING(" +0000"); /* This reliably terminates the buffer */778PNG_UNUSED (pos)779780# undef APPEND781# undef APPEND_NUMBER782# undef APPEND_STRING783}784785return 1;786}787788# if PNG_LIBPNG_VER < 10700789/* To do: remove the following from libpng-1.7 */790/* Original API that uses a private buffer in png_struct.791* Deprecated because it causes png_struct to carry a spurious temporary792* buffer (png_struct::time_buffer), better to have the caller pass this in.793*/794png_const_charp PNGAPI795png_convert_to_rfc1123(png_structrp png_ptr, png_const_timep ptime)796{797if (png_ptr != NULL)798{799/* The only failure above if png_ptr != NULL is from an invalid ptime */800if (png_convert_to_rfc1123_buffer(png_ptr->time_buffer, ptime) == 0)801png_warning(png_ptr, "Ignoring invalid time value");802803else804return png_ptr->time_buffer;805}806807return NULL;808}809# endif /* LIBPNG_VER < 10700 */810# endif /* TIME_RFC1123 */811812#endif /* READ || WRITE */813814png_const_charp PNGAPI815png_get_copyright(png_const_structrp png_ptr)816{817PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */818#ifdef PNG_STRING_COPYRIGHT819return PNG_STRING_COPYRIGHT820#else821return PNG_STRING_NEWLINE \822"libpng version 1.6.54" PNG_STRING_NEWLINE \823"Copyright (c) 2018-2026 Cosmin Truta" PNG_STRING_NEWLINE \824"Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson" \825PNG_STRING_NEWLINE \826"Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \827"Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \828PNG_STRING_NEWLINE;829#endif830}831832/* The following return the library version as a short string in the833* format 1.0.0 through 99.99.99zz. To get the version of *.h files834* used with your application, print out PNG_LIBPNG_VER_STRING, which835* is defined in png.h.836* Note: now there is no difference between png_get_libpng_ver() and837* png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,838* it is guaranteed that png.c uses the correct version of png.h.839*/840png_const_charp PNGAPI841png_get_libpng_ver(png_const_structrp png_ptr)842{843/* Version of *.c files used when building libpng */844return png_get_header_ver(png_ptr);845}846847png_const_charp PNGAPI848png_get_header_ver(png_const_structrp png_ptr)849{850/* Version of *.h files used when building libpng */851PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */852return PNG_LIBPNG_VER_STRING;853}854855png_const_charp PNGAPI856png_get_header_version(png_const_structrp png_ptr)857{858/* Returns longer string containing both version and date */859PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */860#ifdef __STDC__861return PNG_HEADER_VERSION_STRING862# ifndef PNG_READ_SUPPORTED863" (NO READ SUPPORT)"864# endif865PNG_STRING_NEWLINE;866#else867return PNG_HEADER_VERSION_STRING;868#endif869}870871#ifdef PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED872/* NOTE: this routine is not used internally! */873/* Build a grayscale palette. Palette is assumed to be 1 << bit_depth874* large of png_color. This lets grayscale images be treated as875* paletted. Most useful for gamma correction and simplification876* of code. This API is not used internally.877*/878void PNGAPI879png_build_grayscale_palette(int bit_depth, png_colorp palette)880{881int num_palette;882int color_inc;883int i;884int v;885886png_debug(1, "in png_do_build_grayscale_palette");887888if (palette == NULL)889return;890891switch (bit_depth)892{893case 1:894num_palette = 2;895color_inc = 0xff;896break;897898case 2:899num_palette = 4;900color_inc = 0x55;901break;902903case 4:904num_palette = 16;905color_inc = 0x11;906break;907908case 8:909num_palette = 256;910color_inc = 1;911break;912913default:914num_palette = 0;915color_inc = 0;916break;917}918919for (i = 0, v = 0; i < num_palette; i++, v += color_inc)920{921palette[i].red = (png_byte)(v & 0xff);922palette[i].green = (png_byte)(v & 0xff);923palette[i].blue = (png_byte)(v & 0xff);924}925}926#endif927928#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED929int PNGAPI930png_handle_as_unknown(png_const_structrp png_ptr, png_const_bytep chunk_name)931{932/* Check chunk_name and return "keep" value if it's on the list, else 0 */933png_const_bytep p, p_end;934935if (png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list == 0)936return PNG_HANDLE_CHUNK_AS_DEFAULT;937938p_end = png_ptr->chunk_list;939p = p_end + png_ptr->num_chunk_list*5; /* beyond end */940941/* The code is the fifth byte after each four byte string. Historically this942* code was always searched from the end of the list, this is no longer943* necessary because the 'set' routine handles duplicate entries correctly.944*/945do /* num_chunk_list > 0, so at least one */946{947p -= 5;948949if (memcmp(chunk_name, p, 4) == 0)950return p[4];951}952while (p > p_end);953954/* This means that known chunks should be processed and unknown chunks should955* be handled according to the value of png_ptr->unknown_default; this can be956* confusing because, as a result, there are two levels of defaulting for957* unknown chunks.958*/959return PNG_HANDLE_CHUNK_AS_DEFAULT;960}961962#if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) ||\963defined(PNG_HANDLE_AS_UNKNOWN_SUPPORTED)964int /* PRIVATE */965png_chunk_unknown_handling(png_const_structrp png_ptr, png_uint_32 chunk_name)966{967png_byte chunk_string[5];968969PNG_CSTRING_FROM_CHUNK(chunk_string, chunk_name);970return png_handle_as_unknown(png_ptr, chunk_string);971}972#endif /* READ_UNKNOWN_CHUNKS || HANDLE_AS_UNKNOWN */973#endif /* SET_UNKNOWN_CHUNKS */974975#ifdef PNG_READ_SUPPORTED976/* This function, added to libpng-1.0.6g, is untested. */977int PNGAPI978png_reset_zstream(png_structrp png_ptr)979{980if (png_ptr == NULL)981return Z_STREAM_ERROR;982983/* WARNING: this resets the window bits to the maximum! */984return inflateReset(&png_ptr->zstream);985}986#endif /* READ */987988/* This function was added to libpng-1.0.7 */989png_uint_32 PNGAPI990png_access_version_number(void)991{992/* Version of *.c files used when building libpng */993return (png_uint_32)PNG_LIBPNG_VER;994}995996#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)997/* Ensure that png_ptr->zstream.msg holds some appropriate error message string.998* If it doesn't 'ret' is used to set it to something appropriate, even in cases999* like Z_OK or Z_STREAM_END where the error code is apparently a success code.1000*/1001void /* PRIVATE */1002png_zstream_error(png_structrp png_ptr, int ret)1003{1004/* Translate 'ret' into an appropriate error string, priority is given to the1005* one in zstream if set. This always returns a string, even in cases like1006* Z_OK or Z_STREAM_END where the error code is a success code.1007*/1008if (png_ptr->zstream.msg == NULL) switch (ret)1009{1010default:1011case Z_OK:1012png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected zlib return code");1013break;10141015case Z_STREAM_END:1016/* Normal exit */1017png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected end of LZ stream");1018break;10191020case Z_NEED_DICT:1021/* This means the deflate stream did not have a dictionary; this1022* indicates a bogus PNG.1023*/1024png_ptr->zstream.msg = PNGZ_MSG_CAST("missing LZ dictionary");1025break;10261027case Z_ERRNO:1028/* gz APIs only: should not happen */1029png_ptr->zstream.msg = PNGZ_MSG_CAST("zlib IO error");1030break;10311032case Z_STREAM_ERROR:1033/* internal libpng error */1034png_ptr->zstream.msg = PNGZ_MSG_CAST("bad parameters to zlib");1035break;10361037case Z_DATA_ERROR:1038png_ptr->zstream.msg = PNGZ_MSG_CAST("damaged LZ stream");1039break;10401041case Z_MEM_ERROR:1042png_ptr->zstream.msg = PNGZ_MSG_CAST("insufficient memory");1043break;10441045case Z_BUF_ERROR:1046/* End of input or output; not a problem if the caller is doing1047* incremental read or write.1048*/1049png_ptr->zstream.msg = PNGZ_MSG_CAST("truncated");1050break;10511052case Z_VERSION_ERROR:1053png_ptr->zstream.msg = PNGZ_MSG_CAST("unsupported zlib version");1054break;10551056case PNG_UNEXPECTED_ZLIB_RETURN:1057/* Compile errors here mean that zlib now uses the value co-opted in1058* pngpriv.h for PNG_UNEXPECTED_ZLIB_RETURN; update the switch above1059* and change pngpriv.h. Note that this message is "... return",1060* whereas the default/Z_OK one is "... return code".1061*/1062png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected zlib return");1063break;1064}1065}10661067#ifdef PNG_COLORSPACE_SUPPORTED1068static png_int_321069png_fp_add(png_int_32 addend0, png_int_32 addend1, int *error)1070{1071/* Safely add two fixed point values setting an error flag and returning 0.51072* on overflow.1073* IMPLEMENTATION NOTE: ANSI requires signed overflow not to occur, therefore1074* relying on addition of two positive values producing a negative one is not1075* safe.1076*/1077if (addend0 > 0)1078{1079if (0x7fffffff - addend0 >= addend1)1080return addend0+addend1;1081}1082else if (addend0 < 0)1083{1084if (-0x7fffffff - addend0 <= addend1)1085return addend0+addend1;1086}1087else1088return addend1;10891090*error = 1;1091return PNG_FP_1/2;1092}10931094static png_int_321095png_fp_sub(png_int_32 addend0, png_int_32 addend1, int *error)1096{1097/* As above but calculate addend0-addend1. */1098if (addend1 > 0)1099{1100if (-0x7fffffff + addend1 <= addend0)1101return addend0-addend1;1102}1103else if (addend1 < 0)1104{1105if (0x7fffffff + addend1 >= addend0)1106return addend0-addend1;1107}1108else1109return addend0;11101111*error = 1;1112return PNG_FP_1/2;1113}11141115static int1116png_safe_add(png_int_32 *addend0_and_result, png_int_32 addend1,1117png_int_32 addend2)1118{1119/* Safely add three integers. Returns 0 on success, 1 on overflow. Does not1120* set the result on overflow.1121*/1122int error = 0;1123int result = png_fp_add(*addend0_and_result,1124png_fp_add(addend1, addend2, &error),1125&error);1126if (!error) *addend0_and_result = result;1127return error;1128}11291130/* Added at libpng-1.5.5 to support read and write of true CIEXYZ values for1131* cHRM, as opposed to using chromaticities. These internal APIs return1132* non-zero on a parameter error. The X, Y and Z values are required to be1133* positive and less than 1.0.1134*/1135int /* PRIVATE */1136png_xy_from_XYZ(png_xy *xy, const png_XYZ *XYZ)1137{1138/* NOTE: returns 0 on success, 1 means error. */1139png_int_32 d, dred, dgreen, dblue, dwhite, whiteX, whiteY;11401141/* 'd' in each of the blocks below is just X+Y+Z for each component,1142* x, y and z are X,Y,Z/(X+Y+Z).1143*/1144d = XYZ->red_X;1145if (png_safe_add(&d, XYZ->red_Y, XYZ->red_Z))1146return 1;1147dred = d;1148if (png_muldiv(&xy->redx, XYZ->red_X, PNG_FP_1, dred) == 0)1149return 1;1150if (png_muldiv(&xy->redy, XYZ->red_Y, PNG_FP_1, dred) == 0)1151return 1;11521153d = XYZ->green_X;1154if (png_safe_add(&d, XYZ->green_Y, XYZ->green_Z))1155return 1;1156dgreen = d;1157if (png_muldiv(&xy->greenx, XYZ->green_X, PNG_FP_1, dgreen) == 0)1158return 1;1159if (png_muldiv(&xy->greeny, XYZ->green_Y, PNG_FP_1, dgreen) == 0)1160return 1;11611162d = XYZ->blue_X;1163if (png_safe_add(&d, XYZ->blue_Y, XYZ->blue_Z))1164return 1;1165dblue = d;1166if (png_muldiv(&xy->bluex, XYZ->blue_X, PNG_FP_1, dblue) == 0)1167return 1;1168if (png_muldiv(&xy->bluey, XYZ->blue_Y, PNG_FP_1, dblue) == 0)1169return 1;11701171/* The reference white is simply the sum of the end-point (X,Y,Z) vectors so1172* the fillowing calculates (X+Y+Z) of the reference white (media white,1173* encoding white) itself:1174*/1175d = dblue;1176if (png_safe_add(&d, dred, dgreen))1177return 1;1178dwhite = d;11791180/* Find the white X,Y values from the sum of the red, green and blue X,Y1181* values.1182*/1183d = XYZ->red_X;1184if (png_safe_add(&d, XYZ->green_X, XYZ->blue_X))1185return 1;1186whiteX = d;11871188d = XYZ->red_Y;1189if (png_safe_add(&d, XYZ->green_Y, XYZ->blue_Y))1190return 1;1191whiteY = d;11921193if (png_muldiv(&xy->whitex, whiteX, PNG_FP_1, dwhite) == 0)1194return 1;1195if (png_muldiv(&xy->whitey, whiteY, PNG_FP_1, dwhite) == 0)1196return 1;11971198return 0;1199}12001201int /* PRIVATE */1202png_XYZ_from_xy(png_XYZ *XYZ, const png_xy *xy)1203{1204/* NOTE: returns 0 on success, 1 means error. */1205png_fixed_point red_inverse, green_inverse, blue_scale;1206png_fixed_point left, right, denominator;12071208/* Check xy and, implicitly, z. Note that wide gamut color spaces typically1209* have end points with 0 tristimulus values (these are impossible end1210* points, but they are used to cover the possible colors). We check1211* xy->whitey against 5, not 0, to avoid a possible integer overflow.1212*1213* The limits here will *not* accept ACES AP0, where bluey is -77001214* (-0.0770) because the PNG spec itself requires the xy values to be1215* unsigned. whitey is also required to be 5 or more to avoid overflow.1216*1217* Instead the upper limits have been relaxed to accomodate ACES AP1 where1218* redz ends up as -600 (-0.006). ProPhotoRGB was already "in range."1219* The new limit accomodates the AP0 and AP1 ranges for z but not AP0 redy.1220*/1221const png_fixed_point fpLimit = PNG_FP_1+(PNG_FP_1/10);1222if (xy->redx < 0 || xy->redx > fpLimit) return 1;1223if (xy->redy < 0 || xy->redy > fpLimit-xy->redx) return 1;1224if (xy->greenx < 0 || xy->greenx > fpLimit) return 1;1225if (xy->greeny < 0 || xy->greeny > fpLimit-xy->greenx) return 1;1226if (xy->bluex < 0 || xy->bluex > fpLimit) return 1;1227if (xy->bluey < 0 || xy->bluey > fpLimit-xy->bluex) return 1;1228if (xy->whitex < 0 || xy->whitex > fpLimit) return 1;1229if (xy->whitey < 5 || xy->whitey > fpLimit-xy->whitex) return 1;12301231/* The reverse calculation is more difficult because the original tristimulus1232* value had 9 independent values (red,green,blue)x(X,Y,Z) however only 81233* derived values were recorded in the cHRM chunk;1234* (red,green,blue,white)x(x,y). This loses one degree of freedom and1235* therefore an arbitrary ninth value has to be introduced to undo the1236* original transformations.1237*1238* Think of the original end-points as points in (X,Y,Z) space. The1239* chromaticity values (c) have the property:1240*1241* C1242* c = ---------1243* X + Y + Z1244*1245* For each c (x,y,z) from the corresponding original C (X,Y,Z). Thus the1246* three chromaticity values (x,y,z) for each end-point obey the1247* relationship:1248*1249* x + y + z = 11250*1251* This describes the plane in (X,Y,Z) space that intersects each axis at the1252* value 1.0; call this the chromaticity plane. Thus the chromaticity1253* calculation has scaled each end-point so that it is on the x+y+z=1 plane1254* and chromaticity is the intersection of the vector from the origin to the1255* (X,Y,Z) value with the chromaticity plane.1256*1257* To fully invert the chromaticity calculation we would need the three1258* end-point scale factors, (red-scale, green-scale, blue-scale), but these1259* were not recorded. Instead we calculated the reference white (X,Y,Z) and1260* recorded the chromaticity of this. The reference white (X,Y,Z) would have1261* given all three of the scale factors since:1262*1263* color-C = color-c * color-scale1264* white-C = red-C + green-C + blue-C1265* = red-c*red-scale + green-c*green-scale + blue-c*blue-scale1266*1267* But cHRM records only white-x and white-y, so we have lost the white scale1268* factor:1269*1270* white-C = white-c*white-scale1271*1272* To handle this the inverse transformation makes an arbitrary assumption1273* about white-scale:1274*1275* Assume: white-Y = 1.01276* Hence: white-scale = 1/white-y1277* Or: red-Y + green-Y + blue-Y = 1.01278*1279* Notice the last statement of the assumption gives an equation in three of1280* the nine values we want to calculate. 8 more equations come from the1281* above routine as summarised at the top above (the chromaticity1282* calculation):1283*1284* Given: color-x = color-X / (color-X + color-Y + color-Z)1285* Hence: (color-x - 1)*color-X + color.x*color-Y + color.x*color-Z = 01286*1287* This is 9 simultaneous equations in the 9 variables "color-C" and can be1288* solved by Cramer's rule. Cramer's rule requires calculating 10 9x9 matrix1289* determinants, however this is not as bad as it seems because only 28 of1290* the total of 90 terms in the various matrices are non-zero. Nevertheless1291* Cramer's rule is notoriously numerically unstable because the determinant1292* calculation involves the difference of large, but similar, numbers. It is1293* difficult to be sure that the calculation is stable for real world values1294* and it is certain that it becomes unstable where the end points are close1295* together.1296*1297* So this code uses the perhaps slightly less optimal but more1298* understandable and totally obvious approach of calculating color-scale.1299*1300* This algorithm depends on the precision in white-scale and that is1301* (1/white-y), so we can immediately see that as white-y approaches 0 the1302* accuracy inherent in the cHRM chunk drops off substantially.1303*1304* libpng arithmetic: a simple inversion of the above equations1305* ------------------------------------------------------------1306*1307* white_scale = 1/white-y1308* white-X = white-x * white-scale1309* white-Y = 1.01310* white-Z = (1 - white-x - white-y) * white_scale1311*1312* white-C = red-C + green-C + blue-C1313* = red-c*red-scale + green-c*green-scale + blue-c*blue-scale1314*1315* This gives us three equations in (red-scale,green-scale,blue-scale) where1316* all the coefficients are now known:1317*1318* red-x*red-scale + green-x*green-scale + blue-x*blue-scale1319* = white-x/white-y1320* red-y*red-scale + green-y*green-scale + blue-y*blue-scale = 11321* red-z*red-scale + green-z*green-scale + blue-z*blue-scale1322* = (1 - white-x - white-y)/white-y1323*1324* In the last equation color-z is (1 - color-x - color-y) so we can add all1325* three equations together to get an alternative third:1326*1327* red-scale + green-scale + blue-scale = 1/white-y = white-scale1328*1329* So now we have a Cramer's rule solution where the determinants are just1330* 3x3 - far more tractible. Unfortunately 3x3 determinants still involve1331* multiplication of three coefficients so we can't guarantee to avoid1332* overflow in the libpng fixed point representation. Using Cramer's rule in1333* floating point is probably a good choice here, but it's not an option for1334* fixed point. Instead proceed to simplify the first two equations by1335* eliminating what is likely to be the largest value, blue-scale:1336*1337* blue-scale = white-scale - red-scale - green-scale1338*1339* Hence:1340*1341* (red-x - blue-x)*red-scale + (green-x - blue-x)*green-scale =1342* (white-x - blue-x)*white-scale1343*1344* (red-y - blue-y)*red-scale + (green-y - blue-y)*green-scale =1345* 1 - blue-y*white-scale1346*1347* And now we can trivially solve for (red-scale,green-scale):1348*1349* green-scale =1350* (white-x - blue-x)*white-scale - (red-x - blue-x)*red-scale1351* -----------------------------------------------------------1352* green-x - blue-x1353*1354* red-scale =1355* 1 - blue-y*white-scale - (green-y - blue-y) * green-scale1356* ---------------------------------------------------------1357* red-y - blue-y1358*1359* Hence:1360*1361* red-scale =1362* ( (green-x - blue-x) * (white-y - blue-y) -1363* (green-y - blue-y) * (white-x - blue-x) ) / white-y1364* -------------------------------------------------------------------------1365* (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)1366*1367* green-scale =1368* ( (red-y - blue-y) * (white-x - blue-x) -1369* (red-x - blue-x) * (white-y - blue-y) ) / white-y1370* -------------------------------------------------------------------------1371* (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)1372*1373* Accuracy:1374* The input values have 5 decimal digits of accuracy.1375*1376* In the previous implementation the values were all in the range 0 < value1377* < 1, so simple products are in the same range but may need up to 101378* decimal digits to preserve the original precision and avoid underflow.1379* Because we are using a 32-bit signed representation we cannot match this;1380* the best is a little over 9 decimal digits, less than 10.1381*1382* This range has now been extended to allow values up to 1.1, or 110,000 in1383* fixed point.1384*1385* The approach used here is to preserve the maximum precision within the1386* signed representation. Because the red-scale calculation above uses the1387* difference between two products of values that must be in the range1388* -1.1..+1.1 it is sufficient to divide the product by 8;1389* ceil(121,000/32767*2). The factor is irrelevant in the calculation1390* because it is applied to both numerator and denominator.1391*1392* Note that the values of the differences of the products of the1393* chromaticities in the above equations tend to be small, for example for1394* the sRGB chromaticities they are:1395*1396* red numerator: -0.047511397* green numerator: -0.087881398* denominator: -0.2241 (without white-y multiplication)1399*1400* The resultant Y coefficients from the chromaticities of some widely used1401* color space definitions are (to 15 decimal places):1402*1403* sRGB1404* 0.212639005871510 0.715168678767756 0.0721923153607341405* Kodak ProPhoto1406* 0.288071128229293 0.711843217810102 0.0000856539606051407* Adobe RGB1408* 0.297344975250536 0.627363566255466 0.0752914584939981409* Adobe Wide Gamut RGB1410* 0.258728243040113 0.724682314948566 0.0165894420113211411*/1412{1413int error = 0;14141415/* By the argument above overflow should be impossible here, however the1416* code now simply returns a failure code. The xy subtracts in the1417* arguments to png_muldiv are *not* checked for overflow because the1418* checks at the start guarantee they are in the range 0..110000 and1419* png_fixed_point is a 32-bit signed number.1420*/1421if (png_muldiv(&left, xy->greenx-xy->bluex, xy->redy - xy->bluey, 8) == 0)1422return 1;1423if (png_muldiv(&right, xy->greeny-xy->bluey, xy->redx - xy->bluex, 8) ==14240)1425return 1;1426denominator = png_fp_sub(left, right, &error);1427if (error) return 1;14281429/* Now find the red numerator. */1430if (png_muldiv(&left, xy->greenx-xy->bluex, xy->whitey-xy->bluey, 8) == 0)1431return 1;1432if (png_muldiv(&right, xy->greeny-xy->bluey, xy->whitex-xy->bluex, 8) ==14330)1434return 1;14351436/* Overflow is possible here and it indicates an extreme set of PNG cHRM1437* chunk values. This calculation actually returns the reciprocal of the1438* scale value because this allows us to delay the multiplication of1439* white-y into the denominator, which tends to produce a small number.1440*/1441if (png_muldiv(&red_inverse, xy->whitey, denominator,1442png_fp_sub(left, right, &error)) == 0 || error ||1443red_inverse <= xy->whitey /* r+g+b scales = white scale */)1444return 1;14451446/* Similarly for green_inverse: */1447if (png_muldiv(&left, xy->redy-xy->bluey, xy->whitex-xy->bluex, 8) == 0)1448return 1;1449if (png_muldiv(&right, xy->redx-xy->bluex, xy->whitey-xy->bluey, 8) == 0)1450return 1;1451if (png_muldiv(&green_inverse, xy->whitey, denominator,1452png_fp_sub(left, right, &error)) == 0 || error ||1453green_inverse <= xy->whitey)1454return 1;14551456/* And the blue scale, the checks above guarantee this can't overflow but1457* it can still produce 0 for extreme cHRM values.1458*/1459blue_scale = png_fp_sub(png_fp_sub(png_reciprocal(xy->whitey),1460png_reciprocal(red_inverse), &error),1461png_reciprocal(green_inverse), &error);1462if (error || blue_scale <= 0)1463return 1;1464}14651466/* And fill in the png_XYZ. Again the subtracts are safe because of the1467* checks on the xy values at the start (the subtracts just calculate the1468* corresponding z values.)1469*/1470if (png_muldiv(&XYZ->red_X, xy->redx, PNG_FP_1, red_inverse) == 0)1471return 1;1472if (png_muldiv(&XYZ->red_Y, xy->redy, PNG_FP_1, red_inverse) == 0)1473return 1;1474if (png_muldiv(&XYZ->red_Z, PNG_FP_1 - xy->redx - xy->redy, PNG_FP_1,1475red_inverse) == 0)1476return 1;14771478if (png_muldiv(&XYZ->green_X, xy->greenx, PNG_FP_1, green_inverse) == 0)1479return 1;1480if (png_muldiv(&XYZ->green_Y, xy->greeny, PNG_FP_1, green_inverse) == 0)1481return 1;1482if (png_muldiv(&XYZ->green_Z, PNG_FP_1 - xy->greenx - xy->greeny, PNG_FP_1,1483green_inverse) == 0)1484return 1;14851486if (png_muldiv(&XYZ->blue_X, xy->bluex, blue_scale, PNG_FP_1) == 0)1487return 1;1488if (png_muldiv(&XYZ->blue_Y, xy->bluey, blue_scale, PNG_FP_1) == 0)1489return 1;1490if (png_muldiv(&XYZ->blue_Z, PNG_FP_1 - xy->bluex - xy->bluey, blue_scale,1491PNG_FP_1) == 0)1492return 1;14931494return 0; /*success*/1495}1496#endif /* COLORSPACE */14971498#ifdef PNG_READ_iCCP_SUPPORTED1499/* Error message generation */1500static char1501png_icc_tag_char(png_uint_32 byte)1502{1503byte &= 0xff;1504if (byte >= 32 && byte <= 126)1505return (char)byte;1506else1507return '?';1508}15091510static void1511png_icc_tag_name(char *name, png_uint_32 tag)1512{1513name[0] = '\'';1514name[1] = png_icc_tag_char(tag >> 24);1515name[2] = png_icc_tag_char(tag >> 16);1516name[3] = png_icc_tag_char(tag >> 8);1517name[4] = png_icc_tag_char(tag );1518name[5] = '\'';1519}15201521static int1522is_ICC_signature_char(png_alloc_size_t it)1523{1524return it == 32 || (it >= 48 && it <= 57) || (it >= 65 && it <= 90) ||1525(it >= 97 && it <= 122);1526}15271528static int1529is_ICC_signature(png_alloc_size_t it)1530{1531return is_ICC_signature_char(it >> 24) /* checks all the top bits */ &&1532is_ICC_signature_char((it >> 16) & 0xff) &&1533is_ICC_signature_char((it >> 8) & 0xff) &&1534is_ICC_signature_char(it & 0xff);1535}15361537static int1538png_icc_profile_error(png_const_structrp png_ptr, png_const_charp name,1539png_alloc_size_t value, png_const_charp reason)1540{1541size_t pos;1542char message[196]; /* see below for calculation */15431544pos = png_safecat(message, (sizeof message), 0, "profile '"); /* 9 chars */1545pos = png_safecat(message, pos+79, pos, name); /* Truncate to 79 chars */1546pos = png_safecat(message, (sizeof message), pos, "': "); /* +2 = 90 */1547if (is_ICC_signature(value) != 0)1548{1549/* So 'value' is at most 4 bytes and the following cast is safe */1550png_icc_tag_name(message+pos, (png_uint_32)value);1551pos += 6; /* total +8; less than the else clause */1552message[pos++] = ':';1553message[pos++] = ' ';1554}1555# ifdef PNG_WARNINGS_SUPPORTED1556else1557{1558char number[PNG_NUMBER_BUFFER_SIZE]; /* +24 = 114 */15591560pos = png_safecat(message, (sizeof message), pos,1561png_format_number(number, number+(sizeof number),1562PNG_NUMBER_FORMAT_x, value));1563pos = png_safecat(message, (sizeof message), pos, "h: "); /* +2 = 116 */1564}1565# endif1566/* The 'reason' is an arbitrary message, allow +79 maximum 195 */1567pos = png_safecat(message, (sizeof message), pos, reason);1568PNG_UNUSED(pos)15691570png_chunk_benign_error(png_ptr, message);15711572return 0;1573}15741575/* Encoded value of D50 as an ICC XYZNumber. From the ICC 2010 spec the value1576* is XYZ(0.9642,1.0,0.8249), which scales to:1577*1578* (63189.8112, 65536, 54060.6464)1579*/1580static const png_byte D50_nCIEXYZ[12] =1581{ 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d };15821583static int /* bool */1584icc_check_length(png_const_structrp png_ptr, png_const_charp name,1585png_uint_32 profile_length)1586{1587if (profile_length < 132)1588return png_icc_profile_error(png_ptr, name, profile_length, "too short");1589return 1;1590}15911592int /* PRIVATE */1593png_icc_check_length(png_const_structrp png_ptr, png_const_charp name,1594png_uint_32 profile_length)1595{1596if (!icc_check_length(png_ptr, name, profile_length))1597return 0;15981599/* This needs to be here because the 'normal' check is in1600* png_decompress_chunk, yet this happens after the attempt to1601* png_malloc_base the required data. We only need this on read; on write1602* the caller supplies the profile buffer so libpng doesn't allocate it. See1603* the call to icc_check_length below (the write case).1604*/1605if (profile_length > png_chunk_max(png_ptr))1606return png_icc_profile_error(png_ptr, name, profile_length,1607"profile too long");16081609return 1;1610}16111612int /* PRIVATE */1613png_icc_check_header(png_const_structrp png_ptr, png_const_charp name,1614png_uint_32 profile_length,1615png_const_bytep profile/* first 132 bytes only */, int color_type)1616{1617png_uint_32 temp;16181619/* Length check; this cannot be ignored in this code because profile_length1620* is used later to check the tag table, so even if the profile seems over1621* long profile_length from the caller must be correct. The caller can fix1622* this up on read or write by just passing in the profile header length.1623*/1624temp = png_get_uint_32(profile);1625if (temp != profile_length)1626return png_icc_profile_error(png_ptr, name, temp,1627"length does not match profile");16281629temp = (png_uint_32) (*(profile+8));1630if (temp > 3 && (profile_length & 3))1631return png_icc_profile_error(png_ptr, name, profile_length,1632"invalid length");16331634temp = png_get_uint_32(profile+128); /* tag count: 12 bytes/tag */1635if (temp > 357913930 || /* (2^32-4-132)/12: maximum possible tag count */1636profile_length < 132+12*temp) /* truncated tag table */1637return png_icc_profile_error(png_ptr, name, temp,1638"tag count too large");16391640/* The 'intent' must be valid or we can't store it, ICC limits the intent to1641* 16 bits.1642*/1643temp = png_get_uint_32(profile+64);1644if (temp >= 0xffff) /* The ICC limit */1645return png_icc_profile_error(png_ptr, name, temp,1646"invalid rendering intent");16471648/* This is just a warning because the profile may be valid in future1649* versions.1650*/1651if (temp >= PNG_sRGB_INTENT_LAST)1652(void)png_icc_profile_error(png_ptr, name, temp,1653"intent outside defined range");16541655/* At this point the tag table can't be checked because it hasn't necessarily1656* been loaded; however, various header fields can be checked. These checks1657* are for values permitted by the PNG spec in an ICC profile; the PNG spec1658* restricts the profiles that can be passed in an iCCP chunk (they must be1659* appropriate to processing PNG data!)1660*/16611662/* Data checks (could be skipped). These checks must be independent of the1663* version number; however, the version number doesn't accommodate changes in1664* the header fields (just the known tags and the interpretation of the1665* data.)1666*/1667temp = png_get_uint_32(profile+36); /* signature 'ascp' */1668if (temp != 0x61637370)1669return png_icc_profile_error(png_ptr, name, temp,1670"invalid signature");16711672/* Currently the PCS illuminant/adopted white point (the computational1673* white point) are required to be D50,1674* however the profile contains a record of the illuminant so perhaps ICC1675* expects to be able to change this in the future (despite the rationale in1676* the introduction for using a fixed PCS adopted white.) Consequently the1677* following is just a warning.1678*/1679if (memcmp(profile+68, D50_nCIEXYZ, 12) != 0)1680(void)png_icc_profile_error(png_ptr, name, 0/*no tag value*/,1681"PCS illuminant is not D50");16821683/* The PNG spec requires this:1684* "If the iCCP chunk is present, the image samples conform to the colour1685* space represented by the embedded ICC profile as defined by the1686* International Color Consortium [ICC]. The colour space of the ICC profile1687* shall be an RGB colour space for colour images (PNG colour types 2, 3, and1688* 6), or a greyscale colour space for greyscale images (PNG colour types 01689* and 4)."1690*1691* This checking code ensures the embedded profile (on either read or write)1692* conforms to the specification requirements. Notice that an ICC 'gray'1693* color-space profile contains the information to transform the monochrome1694* data to XYZ or L*a*b (according to which PCS the profile uses) and this1695* should be used in preference to the standard libpng K channel replication1696* into R, G and B channels.1697*1698* Previously it was suggested that an RGB profile on grayscale data could be1699* handled. However it it is clear that using an RGB profile in this context1700* must be an error - there is no specification of what it means. Thus it is1701* almost certainly more correct to ignore the profile.1702*/1703temp = png_get_uint_32(profile+16); /* data colour space field */1704switch (temp)1705{1706case 0x52474220: /* 'RGB ' */1707if ((color_type & PNG_COLOR_MASK_COLOR) == 0)1708return png_icc_profile_error(png_ptr, name, temp,1709"RGB color space not permitted on grayscale PNG");1710break;17111712case 0x47524159: /* 'GRAY' */1713if ((color_type & PNG_COLOR_MASK_COLOR) != 0)1714return png_icc_profile_error(png_ptr, name, temp,1715"Gray color space not permitted on RGB PNG");1716break;17171718default:1719return png_icc_profile_error(png_ptr, name, temp,1720"invalid ICC profile color space");1721}17221723/* It is up to the application to check that the profile class matches the1724* application requirements; the spec provides no guidance, but it's pretty1725* weird if the profile is not scanner ('scnr'), monitor ('mntr'), printer1726* ('prtr') or 'spac' (for generic color spaces). Issue a warning in these1727* cases. Issue an error for device link or abstract profiles - these don't1728* contain the records necessary to transform the color-space to anything1729* other than the target device (and not even that for an abstract profile).1730* Profiles of these classes may not be embedded in images.1731*/1732temp = png_get_uint_32(profile+12); /* profile/device class */1733switch (temp)1734{1735case 0x73636e72: /* 'scnr' */1736case 0x6d6e7472: /* 'mntr' */1737case 0x70727472: /* 'prtr' */1738case 0x73706163: /* 'spac' */1739/* All supported */1740break;17411742case 0x61627374: /* 'abst' */1743/* May not be embedded in an image */1744return png_icc_profile_error(png_ptr, name, temp,1745"invalid embedded Abstract ICC profile");17461747case 0x6c696e6b: /* 'link' */1748/* DeviceLink profiles cannot be interpreted in a non-device specific1749* fashion, if an app uses the AToB0Tag in the profile the results are1750* undefined unless the result is sent to the intended device,1751* therefore a DeviceLink profile should not be found embedded in a1752* PNG.1753*/1754return png_icc_profile_error(png_ptr, name, temp,1755"unexpected DeviceLink ICC profile class");17561757case 0x6e6d636c: /* 'nmcl' */1758/* A NamedColor profile is also device specific, however it doesn't1759* contain an AToB0 tag that is open to misinterpretation. Almost1760* certainly it will fail the tests below.1761*/1762(void)png_icc_profile_error(png_ptr, name, temp,1763"unexpected NamedColor ICC profile class");1764break;17651766default:1767/* To allow for future enhancements to the profile accept unrecognized1768* profile classes with a warning, these then hit the test below on the1769* tag content to ensure they are backward compatible with one of the1770* understood profiles.1771*/1772(void)png_icc_profile_error(png_ptr, name, temp,1773"unrecognized ICC profile class");1774break;1775}17761777/* For any profile other than a device link one the PCS must be encoded1778* either in XYZ or Lab.1779*/1780temp = png_get_uint_32(profile+20);1781switch (temp)1782{1783case 0x58595a20: /* 'XYZ ' */1784case 0x4c616220: /* 'Lab ' */1785break;17861787default:1788return png_icc_profile_error(png_ptr, name, temp,1789"unexpected ICC PCS encoding");1790}17911792return 1;1793}17941795int /* PRIVATE */1796png_icc_check_tag_table(png_const_structrp png_ptr, png_const_charp name,1797png_uint_32 profile_length,1798png_const_bytep profile /* header plus whole tag table */)1799{1800png_uint_32 tag_count = png_get_uint_32(profile+128);1801png_uint_32 itag;1802png_const_bytep tag = profile+132; /* The first tag */18031804/* First scan all the tags in the table and add bits to the icc_info value1805* (temporarily in 'tags').1806*/1807for (itag=0; itag < tag_count; ++itag, tag += 12)1808{1809png_uint_32 tag_id = png_get_uint_32(tag+0);1810png_uint_32 tag_start = png_get_uint_32(tag+4); /* must be aligned */1811png_uint_32 tag_length = png_get_uint_32(tag+8);/* not padded */18121813/* The ICC specification does not exclude zero length tags, therefore the1814* start might actually be anywhere if there is no data, but this would be1815* a clear abuse of the intent of the standard so the start is checked for1816* being in range. All defined tag types have an 8 byte header - a 4 byte1817* type signature then 0.1818*/18191820/* This is a hard error; potentially it can cause read outside the1821* profile.1822*/1823if (tag_start > profile_length || tag_length > profile_length - tag_start)1824return png_icc_profile_error(png_ptr, name, tag_id,1825"ICC profile tag outside profile");18261827if ((tag_start & 3) != 0)1828{1829/* CNHP730S.icc shipped with Microsoft Windows 64 violates this; it is1830* only a warning here because libpng does not care about the1831* alignment.1832*/1833(void)png_icc_profile_error(png_ptr, name, tag_id,1834"ICC profile tag start not a multiple of 4");1835}1836}18371838return 1; /* success, maybe with warnings */1839}1840#endif /* READ_iCCP */18411842#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED1843#if (defined PNG_READ_mDCV_SUPPORTED) || (defined PNG_READ_cHRM_SUPPORTED)1844static int1845have_chromaticities(png_const_structrp png_ptr)1846{1847/* Handle new PNGv3 chunks and the precedence rules to determine whether1848* png_struct::chromaticities must be processed. Only required for RGB to1849* gray.1850*1851* mDCV: this is the mastering colour space and it is independent of the1852* encoding so it needs to be used regardless of the encoded space.1853*1854* cICP: first in priority but not yet implemented - the chromaticities come1855* from the 'primaries'.1856*1857* iCCP: not supported by libpng (so ignored)1858*1859* sRGB: the defaults match sRGB1860*1861* cHRM: calculate the coefficients1862*/1863# ifdef PNG_READ_mDCV_SUPPORTED1864if (png_has_chunk(png_ptr, mDCV))1865return 1;1866# define check_chromaticities 11867# endif /*mDCV*/18681869# ifdef PNG_READ_sRGB_SUPPORTED1870if (png_has_chunk(png_ptr, sRGB))1871return 0;1872# endif /*sRGB*/18731874# ifdef PNG_READ_cHRM_SUPPORTED1875if (png_has_chunk(png_ptr, cHRM))1876return 1;1877# define check_chromaticities 11878# endif /*cHRM*/18791880return 0; /* sRGB defaults */1881}1882#endif /* READ_mDCV || READ_cHRM */18831884void /* PRIVATE */1885png_set_rgb_coefficients(png_structrp png_ptr)1886{1887/* Set the rgb_to_gray coefficients from the colorspace if available. Note1888* that '_set' means that png_rgb_to_gray was called **and** it successfully1889* set up the coefficients.1890*/1891if (png_ptr->rgb_to_gray_coefficients_set == 0)1892{1893# if check_chromaticities1894png_XYZ xyz;18951896if (have_chromaticities(png_ptr) &&1897png_XYZ_from_xy(&xyz, &png_ptr->chromaticities) == 0)1898{1899/* png_set_rgb_to_gray has not set the coefficients, get them from the1900* Y * values of the colorspace colorants.1901*/1902png_fixed_point r = xyz.red_Y;1903png_fixed_point g = xyz.green_Y;1904png_fixed_point b = xyz.blue_Y;1905png_fixed_point total = r+g+b;19061907if (total > 0 &&1908r >= 0 && png_muldiv(&r, r, 32768, total) && r >= 0 && r <= 32768 &&1909g >= 0 && png_muldiv(&g, g, 32768, total) && g >= 0 && g <= 32768 &&1910b >= 0 && png_muldiv(&b, b, 32768, total) && b >= 0 && b <= 32768 &&1911r+g+b <= 32769)1912{1913/* We allow 0 coefficients here. r+g+b may be 32769 if two or1914* all of the coefficients were rounded up. Handle this by1915* reducing the *largest* coefficient by 1; this matches the1916* approach used for the default coefficients in pngrtran.c1917*/1918int add = 0;19191920if (r+g+b > 32768)1921add = -1;1922else if (r+g+b < 32768)1923add = 1;19241925if (add != 0)1926{1927if (g >= r && g >= b)1928g += add;1929else if (r >= g && r >= b)1930r += add;1931else1932b += add;1933}19341935/* Check for an internal error. */1936if (r+g+b != 32768)1937png_error(png_ptr,1938"internal error handling cHRM coefficients");19391940else1941{1942png_ptr->rgb_to_gray_red_coeff = (png_uint_16)r;1943png_ptr->rgb_to_gray_green_coeff = (png_uint_16)g;1944}1945}1946}1947else1948# endif /* check_chromaticities */1949{1950/* Use the historical REC 709 (etc) values: */1951png_ptr->rgb_to_gray_red_coeff = 6968;1952png_ptr->rgb_to_gray_green_coeff = 23434;1953/* png_ptr->rgb_to_gray_blue_coeff = 2366; */1954}1955}1956}1957#endif /* READ_RGB_TO_GRAY */19581959void /* PRIVATE */1960png_check_IHDR(png_const_structrp png_ptr,1961png_uint_32 width, png_uint_32 height, int bit_depth,1962int color_type, int interlace_type, int compression_type,1963int filter_type)1964{1965int error = 0;19661967/* Check for width and height valid values */1968if (width == 0)1969{1970png_warning(png_ptr, "Image width is zero in IHDR");1971error = 1;1972}19731974if (width > PNG_UINT_31_MAX)1975{1976png_warning(png_ptr, "Invalid image width in IHDR");1977error = 1;1978}19791980/* The bit mask on the first line below must be at least as big as a1981* png_uint_32. "~7U" is not adequate on 16-bit systems because it will1982* be an unsigned 16-bit value. Casting to (png_alloc_size_t) makes the1983* type of the result at least as bit (in bits) as the RHS of the > operator1984* which also avoids a common warning on 64-bit systems that the comparison1985* of (png_uint_32) against the constant value on the RHS will always be1986* false.1987*/1988if (((width + 7) & ~(png_alloc_size_t)7) >1989(((PNG_SIZE_MAX1990- 48 /* big_row_buf hack */1991- 1) /* filter byte */1992/ 8) /* 8-byte RGBA pixels */1993- 1)) /* extra max_pixel_depth pad */1994{1995/* The size of the row must be within the limits of this architecture.1996* Because the read code can perform arbitrary transformations the1997* maximum size is checked here. Because the code in png_read_start_row1998* adds extra space "for safety's sake" in several places a conservative1999* limit is used here.2000*2001* NOTE: it would be far better to check the size that is actually used,2002* but the effect in the real world is minor and the changes are more2003* extensive, therefore much more dangerous and much more difficult to2004* write in a way that avoids compiler warnings.2005*/2006png_warning(png_ptr, "Image width is too large for this architecture");2007error = 1;2008}20092010#ifdef PNG_SET_USER_LIMITS_SUPPORTED2011if (width > png_ptr->user_width_max)2012#else2013if (width > PNG_USER_WIDTH_MAX)2014#endif2015{2016png_warning(png_ptr, "Image width exceeds user limit in IHDR");2017error = 1;2018}20192020if (height == 0)2021{2022png_warning(png_ptr, "Image height is zero in IHDR");2023error = 1;2024}20252026if (height > PNG_UINT_31_MAX)2027{2028png_warning(png_ptr, "Invalid image height in IHDR");2029error = 1;2030}20312032#ifdef PNG_SET_USER_LIMITS_SUPPORTED2033if (height > png_ptr->user_height_max)2034#else2035if (height > PNG_USER_HEIGHT_MAX)2036#endif2037{2038png_warning(png_ptr, "Image height exceeds user limit in IHDR");2039error = 1;2040}20412042/* Check other values */2043if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&2044bit_depth != 8 && bit_depth != 16)2045{2046png_warning(png_ptr, "Invalid bit depth in IHDR");2047error = 1;2048}20492050if (color_type < 0 || color_type == 1 ||2051color_type == 5 || color_type > 6)2052{2053png_warning(png_ptr, "Invalid color type in IHDR");2054error = 1;2055}20562057if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||2058((color_type == PNG_COLOR_TYPE_RGB ||2059color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||2060color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))2061{2062png_warning(png_ptr, "Invalid color type/bit depth combination in IHDR");2063error = 1;2064}20652066if (interlace_type >= PNG_INTERLACE_LAST)2067{2068png_warning(png_ptr, "Unknown interlace method in IHDR");2069error = 1;2070}20712072if (compression_type != PNG_COMPRESSION_TYPE_BASE)2073{2074png_warning(png_ptr, "Unknown compression method in IHDR");2075error = 1;2076}20772078#ifdef PNG_MNG_FEATURES_SUPPORTED2079/* Accept filter_method 64 (intrapixel differencing) only if2080* 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and2081* 2. Libpng did not read a PNG signature (this filter_method is only2082* used in PNG datastreams that are embedded in MNG datastreams) and2083* 3. The application called png_permit_mng_features with a mask that2084* included PNG_FLAG_MNG_FILTER_64 and2085* 4. The filter_method is 64 and2086* 5. The color_type is RGB or RGBA2087*/2088if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 &&2089png_ptr->mng_features_permitted != 0)2090png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");20912092if (filter_type != PNG_FILTER_TYPE_BASE)2093{2094if (!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&2095(filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&2096((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) == 0) &&2097(color_type == PNG_COLOR_TYPE_RGB ||2098color_type == PNG_COLOR_TYPE_RGB_ALPHA)))2099{2100png_warning(png_ptr, "Unknown filter method in IHDR");2101error = 1;2102}21032104if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0)2105{2106png_warning(png_ptr, "Invalid filter method in IHDR");2107error = 1;2108}2109}21102111#else2112if (filter_type != PNG_FILTER_TYPE_BASE)2113{2114png_warning(png_ptr, "Unknown filter method in IHDR");2115error = 1;2116}2117#endif21182119if (error == 1)2120png_error(png_ptr, "Invalid IHDR data");2121}21222123#if defined(PNG_sCAL_SUPPORTED) || defined(PNG_pCAL_SUPPORTED)2124/* ASCII to fp functions */2125/* Check an ASCII formatted floating point value, see the more detailed2126* comments in pngpriv.h2127*/2128/* The following is used internally to preserve the sticky flags */2129#define png_fp_add(state, flags) ((state) |= (flags))2130#define png_fp_set(state, value) ((state) = (value) | ((state) & PNG_FP_STICKY))21312132int /* PRIVATE */2133png_check_fp_number(png_const_charp string, size_t size, int *statep,2134size_t *whereami)2135{2136int state = *statep;2137size_t i = *whereami;21382139while (i < size)2140{2141int type;2142/* First find the type of the next character */2143switch (string[i])2144{2145case 43: type = PNG_FP_SAW_SIGN; break;2146case 45: type = PNG_FP_SAW_SIGN + PNG_FP_NEGATIVE; break;2147case 46: type = PNG_FP_SAW_DOT; break;2148case 48: type = PNG_FP_SAW_DIGIT; break;2149case 49: case 50: case 51: case 52:2150case 53: case 54: case 55: case 56:2151case 57: type = PNG_FP_SAW_DIGIT + PNG_FP_NONZERO; break;2152case 69:2153case 101: type = PNG_FP_SAW_E; break;2154default: goto PNG_FP_End;2155}21562157/* Now deal with this type according to the current2158* state, the type is arranged to not overlap the2159* bits of the PNG_FP_STATE.2160*/2161switch ((state & PNG_FP_STATE) + (type & PNG_FP_SAW_ANY))2162{2163case PNG_FP_INTEGER + PNG_FP_SAW_SIGN:2164if ((state & PNG_FP_SAW_ANY) != 0)2165goto PNG_FP_End; /* not a part of the number */21662167png_fp_add(state, type);2168break;21692170case PNG_FP_INTEGER + PNG_FP_SAW_DOT:2171/* Ok as trailer, ok as lead of fraction. */2172if ((state & PNG_FP_SAW_DOT) != 0) /* two dots */2173goto PNG_FP_End;21742175else if ((state & PNG_FP_SAW_DIGIT) != 0) /* trailing dot? */2176png_fp_add(state, type);21772178else2179png_fp_set(state, PNG_FP_FRACTION | type);21802181break;21822183case PNG_FP_INTEGER + PNG_FP_SAW_DIGIT:2184if ((state & PNG_FP_SAW_DOT) != 0) /* delayed fraction */2185png_fp_set(state, PNG_FP_FRACTION | PNG_FP_SAW_DOT);21862187png_fp_add(state, type | PNG_FP_WAS_VALID);21882189break;21902191case PNG_FP_INTEGER + PNG_FP_SAW_E:2192if ((state & PNG_FP_SAW_DIGIT) == 0)2193goto PNG_FP_End;21942195png_fp_set(state, PNG_FP_EXPONENT);21962197break;21982199/* case PNG_FP_FRACTION + PNG_FP_SAW_SIGN:2200goto PNG_FP_End; ** no sign in fraction */22012202/* case PNG_FP_FRACTION + PNG_FP_SAW_DOT:2203goto PNG_FP_End; ** Because SAW_DOT is always set */22042205case PNG_FP_FRACTION + PNG_FP_SAW_DIGIT:2206png_fp_add(state, type | PNG_FP_WAS_VALID);2207break;22082209case PNG_FP_FRACTION + PNG_FP_SAW_E:2210/* This is correct because the trailing '.' on an2211* integer is handled above - so we can only get here2212* with the sequence ".E" (with no preceding digits).2213*/2214if ((state & PNG_FP_SAW_DIGIT) == 0)2215goto PNG_FP_End;22162217png_fp_set(state, PNG_FP_EXPONENT);22182219break;22202221case PNG_FP_EXPONENT + PNG_FP_SAW_SIGN:2222if ((state & PNG_FP_SAW_ANY) != 0)2223goto PNG_FP_End; /* not a part of the number */22242225png_fp_add(state, PNG_FP_SAW_SIGN);22262227break;22282229/* case PNG_FP_EXPONENT + PNG_FP_SAW_DOT:2230goto PNG_FP_End; */22312232case PNG_FP_EXPONENT + PNG_FP_SAW_DIGIT:2233png_fp_add(state, PNG_FP_SAW_DIGIT | PNG_FP_WAS_VALID);22342235break;22362237/* case PNG_FP_EXPONEXT + PNG_FP_SAW_E:2238goto PNG_FP_End; */22392240default: goto PNG_FP_End; /* I.e. break 2 */2241}22422243/* The character seems ok, continue. */2244++i;2245}22462247PNG_FP_End:2248/* Here at the end, update the state and return the correct2249* return code.2250*/2251*statep = state;2252*whereami = i;22532254return (state & PNG_FP_SAW_DIGIT) != 0;2255}225622572258/* The same but for a complete string. */2259int2260png_check_fp_string(png_const_charp string, size_t size)2261{2262int state = 0;2263size_t char_index = 0;22642265if (png_check_fp_number(string, size, &state, &char_index) != 0 &&2266(char_index == size || string[char_index] == 0))2267return state /* must be non-zero - see above */;22682269return 0; /* i.e. fail */2270}2271#endif /* pCAL || sCAL */22722273#ifdef PNG_sCAL_SUPPORTED2274# ifdef PNG_FLOATING_POINT_SUPPORTED2275/* Utility used below - a simple accurate power of ten from an integral2276* exponent.2277*/2278static double2279png_pow10(int power)2280{2281int recip = 0;2282double d = 1;22832284/* Handle negative exponent with a reciprocal at the end because2285* 10 is exact whereas .1 is inexact in base 22286*/2287if (power < 0)2288{2289if (power < DBL_MIN_10_EXP) return 0;2290recip = 1; power = -power;2291}22922293if (power > 0)2294{2295/* Decompose power bitwise. */2296double mult = 10;2297do2298{2299if (power & 1) d *= mult;2300mult *= mult;2301power >>= 1;2302}2303while (power > 0);23042305if (recip != 0) d = 1/d;2306}2307/* else power is 0 and d is 1 */23082309return d;2310}23112312/* Function to format a floating point value in ASCII with a given2313* precision.2314*/2315void /* PRIVATE */2316png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, size_t size,2317double fp, unsigned int precision)2318{2319/* We use standard functions from math.h, but not printf because2320* that would require stdio. The caller must supply a buffer of2321* sufficient size or we will png_error. The tests on size and2322* the space in ascii[] consumed are indicated below.2323*/2324if (precision < 1)2325precision = DBL_DIG;23262327/* Enforce the limit of the implementation precision too. */2328if (precision > DBL_DIG+1)2329precision = DBL_DIG+1;23302331/* Basic sanity checks */2332if (size >= precision+5) /* See the requirements below. */2333{2334if (fp < 0)2335{2336fp = -fp;2337*ascii++ = 45; /* '-' PLUS 1 TOTAL 1 */2338--size;2339}23402341if (fp >= DBL_MIN && fp <= DBL_MAX)2342{2343int exp_b10; /* A base 10 exponent */2344double base; /* 10^exp_b10 */23452346/* First extract a base 10 exponent of the number,2347* the calculation below rounds down when converting2348* from base 2 to base 10 (multiply by log10(2) -2349* 0.3010, but 77/256 is 0.3008, so exp_b10 needs to2350* be increased. Note that the arithmetic shift2351* performs a floor() unlike C arithmetic - using a2352* C multiply would break the following for negative2353* exponents.2354*/2355(void)frexp(fp, &exp_b10); /* exponent to base 2 */23562357exp_b10 = (exp_b10 * 77) >> 8; /* <= exponent to base 10 */23582359/* Avoid underflow here. */2360base = png_pow10(exp_b10); /* May underflow */23612362while (base < DBL_MIN || base < fp)2363{2364/* And this may overflow. */2365double test = png_pow10(exp_b10+1);23662367if (test <= DBL_MAX)2368{2369++exp_b10; base = test;2370}23712372else2373break;2374}23752376/* Normalize fp and correct exp_b10, after this fp is in the2377* range [.1,1) and exp_b10 is both the exponent and the digit2378* *before* which the decimal point should be inserted2379* (starting with 0 for the first digit). Note that this2380* works even if 10^exp_b10 is out of range because of the2381* test on DBL_MAX above.2382*/2383fp /= base;2384while (fp >= 1)2385{2386fp /= 10; ++exp_b10;2387}23882389/* Because of the code above fp may, at this point, be2390* less than .1, this is ok because the code below can2391* handle the leading zeros this generates, so no attempt2392* is made to correct that here.2393*/23942395{2396unsigned int czero, clead, cdigits;2397char exponent[10];23982399/* Allow up to two leading zeros - this will not lengthen2400* the number compared to using E-n.2401*/2402if (exp_b10 < 0 && exp_b10 > -3) /* PLUS 3 TOTAL 4 */2403{2404czero = 0U-exp_b10; /* PLUS 2 digits: TOTAL 3 */2405exp_b10 = 0; /* Dot added below before first output. */2406}2407else2408czero = 0; /* No zeros to add */24092410/* Generate the digit list, stripping trailing zeros and2411* inserting a '.' before a digit if the exponent is 0.2412*/2413clead = czero; /* Count of leading zeros */2414cdigits = 0; /* Count of digits in list. */24152416do2417{2418double d;24192420fp *= 10;2421/* Use modf here, not floor and subtract, so that2422* the separation is done in one step. At the end2423* of the loop don't break the number into parts so2424* that the final digit is rounded.2425*/2426if (cdigits+czero+1 < precision+clead)2427fp = modf(fp, &d);24282429else2430{2431d = floor(fp + .5);24322433if (d > 9)2434{2435/* Rounding up to 10, handle that here. */2436if (czero > 0)2437{2438--czero; d = 1;2439if (cdigits == 0) --clead;2440}2441else2442{2443while (cdigits > 0 && d > 9)2444{2445int ch = *--ascii;24462447if (exp_b10 != (-1))2448++exp_b10;24492450else if (ch == 46)2451{2452ch = *--ascii; ++size;2453/* Advance exp_b10 to '1', so that the2454* decimal point happens after the2455* previous digit.2456*/2457exp_b10 = 1;2458}24592460--cdigits;2461d = ch - 47; /* I.e. 1+(ch-48) */2462}24632464/* Did we reach the beginning? If so adjust the2465* exponent but take into account the leading2466* decimal point.2467*/2468if (d > 9) /* cdigits == 0 */2469{2470if (exp_b10 == (-1))2471{2472/* Leading decimal point (plus zeros?), if2473* we lose the decimal point here it must2474* be reentered below.2475*/2476int ch = *--ascii;24772478if (ch == 46)2479{2480++size; exp_b10 = 1;2481}24822483/* Else lost a leading zero, so 'exp_b10' is2484* still ok at (-1)2485*/2486}2487else2488++exp_b10;24892490/* In all cases we output a '1' */2491d = 1;2492}2493}2494}2495fp = 0; /* Guarantees termination below. */2496}24972498if (d == 0)2499{2500++czero;2501if (cdigits == 0) ++clead;2502}2503else2504{2505/* Included embedded zeros in the digit count. */2506cdigits += czero - clead;2507clead = 0;25082509while (czero > 0)2510{2511/* exp_b10 == (-1) means we just output the decimal2512* place - after the DP don't adjust 'exp_b10' any2513* more!2514*/2515if (exp_b10 != (-1))2516{2517if (exp_b10 == 0)2518{2519*ascii++ = 46; --size;2520}2521/* PLUS 1: TOTAL 4 */2522--exp_b10;2523}2524*ascii++ = 48; --czero;2525}25262527if (exp_b10 != (-1))2528{2529if (exp_b10 == 0)2530{2531*ascii++ = 46; --size; /* counted above */2532}25332534--exp_b10;2535}2536*ascii++ = (char)(48 + (int)d); ++cdigits;2537}2538}2539while (cdigits+czero < precision+clead && fp > DBL_MIN);25402541/* The total output count (max) is now 4+precision */25422543/* Check for an exponent, if we don't need one we are2544* done and just need to terminate the string. At this2545* point, exp_b10==(-1) is effectively a flag: it got2546* to '-1' because of the decrement, after outputting2547* the decimal point above. (The exponent required is2548* *not* -1.)2549*/2550if (exp_b10 >= (-1) && exp_b10 <= 2)2551{2552/* The following only happens if we didn't output the2553* leading zeros above for negative exponent, so this2554* doesn't add to the digit requirement. Note that the2555* two zeros here can only be output if the two leading2556* zeros were *not* output, so this doesn't increase2557* the output count.2558*/2559while (exp_b10-- > 0) *ascii++ = 48;25602561*ascii = 0;25622563/* Total buffer requirement (including the '\0') is2564* 5+precision - see check at the start.2565*/2566return;2567}25682569/* Here if an exponent is required, adjust size for2570* the digits we output but did not count. The total2571* digit output here so far is at most 1+precision - no2572* decimal point and no leading or trailing zeros have2573* been output.2574*/2575size -= cdigits;25762577*ascii++ = 69; --size; /* 'E': PLUS 1 TOTAL 2+precision */25782579/* The following use of an unsigned temporary avoids ambiguities in2580* the signed arithmetic on exp_b10 and permits GCC at least to do2581* better optimization.2582*/2583{2584unsigned int uexp_b10;25852586if (exp_b10 < 0)2587{2588*ascii++ = 45; --size; /* '-': PLUS 1 TOTAL 3+precision */2589uexp_b10 = 0U-exp_b10;2590}25912592else2593uexp_b10 = 0U+exp_b10;25942595cdigits = 0;25962597while (uexp_b10 > 0)2598{2599exponent[cdigits++] = (char)(48 + uexp_b10 % 10);2600uexp_b10 /= 10;2601}2602}26032604/* Need another size check here for the exponent digits, so2605* this need not be considered above.2606*/2607if (size > cdigits)2608{2609while (cdigits > 0) *ascii++ = exponent[--cdigits];26102611*ascii = 0;26122613return;2614}2615}2616}2617else if (!(fp >= DBL_MIN))2618{2619*ascii++ = 48; /* '0' */2620*ascii = 0;2621return;2622}2623else2624{2625*ascii++ = 105; /* 'i' */2626*ascii++ = 110; /* 'n' */2627*ascii++ = 102; /* 'f' */2628*ascii = 0;2629return;2630}2631}26322633/* Here on buffer too small. */2634png_error(png_ptr, "ASCII conversion buffer too small");2635}2636# endif /* FLOATING_POINT */26372638# ifdef PNG_FIXED_POINT_SUPPORTED2639/* Function to format a fixed point value in ASCII.2640*/2641void /* PRIVATE */2642png_ascii_from_fixed(png_const_structrp png_ptr, png_charp ascii,2643size_t size, png_fixed_point fp)2644{2645/* Require space for 10 decimal digits, a decimal point, a minus sign and a2646* trailing \0, 13 characters:2647*/2648if (size > 12)2649{2650png_uint_32 num;26512652/* Avoid overflow here on the minimum integer. */2653if (fp < 0)2654{2655*ascii++ = 45; num = (png_uint_32)(-fp);2656}2657else2658num = (png_uint_32)fp;26592660if (num <= 0x80000000) /* else overflowed */2661{2662unsigned int ndigits = 0, first = 16 /* flag value */;2663char digits[10] = {0};26642665while (num)2666{2667/* Split the low digit off num: */2668unsigned int tmp = num/10;2669num -= tmp*10;2670digits[ndigits++] = (char)(48 + num);2671/* Record the first non-zero digit, note that this is a number2672* starting at 1, it's not actually the array index.2673*/2674if (first == 16 && num > 0)2675first = ndigits;2676num = tmp;2677}26782679if (ndigits > 0)2680{2681while (ndigits > 5) *ascii++ = digits[--ndigits];2682/* The remaining digits are fractional digits, ndigits is '5' or2683* smaller at this point. It is certainly not zero. Check for a2684* non-zero fractional digit:2685*/2686if (first <= 5)2687{2688unsigned int i;2689*ascii++ = 46; /* decimal point */2690/* ndigits may be <5 for small numbers, output leading zeros2691* then ndigits digits to first:2692*/2693i = 5;2694while (ndigits < i)2695{2696*ascii++ = 48; --i;2697}2698while (ndigits >= first) *ascii++ = digits[--ndigits];2699/* Don't output the trailing zeros! */2700}2701}2702else2703*ascii++ = 48;27042705/* And null terminate the string: */2706*ascii = 0;2707return;2708}2709}27102711/* Here on buffer too small. */2712png_error(png_ptr, "ASCII conversion buffer too small");2713}2714# endif /* FIXED_POINT */2715#endif /* SCAL */27162717#if defined(PNG_FLOATING_POINT_SUPPORTED) && \2718!defined(PNG_FIXED_POINT_MACRO_SUPPORTED) && \2719(defined(PNG_gAMA_SUPPORTED) || defined(PNG_cHRM_SUPPORTED) || \2720defined(PNG_sCAL_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) || \2721defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)) || \2722(defined(PNG_sCAL_SUPPORTED) && \2723defined(PNG_FLOATING_ARITHMETIC_SUPPORTED))2724png_fixed_point2725png_fixed(png_const_structrp png_ptr, double fp, png_const_charp text)2726{2727double r = floor(100000 * fp + .5);27282729if (r > 2147483647. || r < -2147483648.)2730png_fixed_error(png_ptr, text);27312732# ifndef PNG_ERROR_TEXT_SUPPORTED2733PNG_UNUSED(text)2734# endif27352736return (png_fixed_point)r;2737}2738#endif27392740#if defined(PNG_FLOATING_POINT_SUPPORTED) && \2741!defined(PNG_FIXED_POINT_MACRO_SUPPORTED) && \2742(defined(PNG_cLLI_SUPPORTED) || defined(PNG_mDCV_SUPPORTED))2743png_uint_322744png_fixed_ITU(png_const_structrp png_ptr, double fp, png_const_charp text)2745{2746double r = floor(10000 * fp + .5);27472748if (r > 2147483647. || r < 0)2749png_fixed_error(png_ptr, text);27502751# ifndef PNG_ERROR_TEXT_SUPPORTED2752PNG_UNUSED(text)2753# endif27542755return (png_uint_32)r;2756}2757#endif275827592760#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_COLORSPACE_SUPPORTED) ||\2761defined(PNG_INCH_CONVERSIONS_SUPPORTED) || defined(PNG_READ_pHYs_SUPPORTED)2762/* muldiv functions */2763/* This API takes signed arguments and rounds the result to the nearest2764* integer (or, for a fixed point number - the standard argument - to2765* the nearest .00001). Overflow and divide by zero are signalled in2766* the result, a boolean - true on success, false on overflow.2767*/2768int /* PRIVATE */2769png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times,2770png_int_32 divisor)2771{2772/* Return a * times / divisor, rounded. */2773if (divisor != 0)2774{2775if (a == 0 || times == 0)2776{2777*res = 0;2778return 1;2779}2780else2781{2782#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED2783double r = a;2784r *= times;2785r /= divisor;2786r = floor(r+.5);27872788/* A png_fixed_point is a 32-bit integer. */2789if (r <= 2147483647. && r >= -2147483648.)2790{2791*res = (png_fixed_point)r;2792return 1;2793}2794#else2795int negative = 0;2796png_uint_32 A, T, D;2797png_uint_32 s16, s32, s00;27982799if (a < 0)2800negative = 1, A = -a;2801else2802A = a;28032804if (times < 0)2805negative = !negative, T = -times;2806else2807T = times;28082809if (divisor < 0)2810negative = !negative, D = -divisor;2811else2812D = divisor;28132814/* Following can't overflow because the arguments only2815* have 31 bits each, however the result may be 32 bits.2816*/2817s16 = (A >> 16) * (T & 0xffff) +2818(A & 0xffff) * (T >> 16);2819/* Can't overflow because the a*times bit is only 302820* bits at most.2821*/2822s32 = (A >> 16) * (T >> 16) + (s16 >> 16);2823s00 = (A & 0xffff) * (T & 0xffff);28242825s16 = (s16 & 0xffff) << 16;2826s00 += s16;28272828if (s00 < s16)2829++s32; /* carry */28302831if (s32 < D) /* else overflow */2832{2833/* s32.s00 is now the 64-bit product, do a standard2834* division, we know that s32 < D, so the maximum2835* required shift is 31.2836*/2837int bitshift = 32;2838png_fixed_point result = 0; /* NOTE: signed */28392840while (--bitshift >= 0)2841{2842png_uint_32 d32, d00;28432844if (bitshift > 0)2845d32 = D >> (32-bitshift), d00 = D << bitshift;28462847else2848d32 = 0, d00 = D;28492850if (s32 > d32)2851{2852if (s00 < d00) --s32; /* carry */2853s32 -= d32, s00 -= d00, result += 1<<bitshift;2854}28552856else2857if (s32 == d32 && s00 >= d00)2858s32 = 0, s00 -= d00, result += 1<<bitshift;2859}28602861/* Handle the rounding. */2862if (s00 >= (D >> 1))2863++result;28642865if (negative != 0)2866result = -result;28672868/* Check for overflow. */2869if ((negative != 0 && result <= 0) ||2870(negative == 0 && result >= 0))2871{2872*res = result;2873return 1;2874}2875}2876#endif2877}2878}28792880return 0;2881}28822883/* Calculate a reciprocal, return 0 on div-by-zero or overflow. */2884png_fixed_point2885png_reciprocal(png_fixed_point a)2886{2887#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED2888double r = floor(1E10/a+.5);28892890if (r <= 2147483647. && r >= -2147483648.)2891return (png_fixed_point)r;2892#else2893png_fixed_point res;28942895if (png_muldiv(&res, 100000, 100000, a) != 0)2896return res;2897#endif28982899return 0; /* error/overflow */2900}2901#endif /* READ_GAMMA || COLORSPACE || INCH_CONVERSIONS || READ_pHYS */29022903#ifdef PNG_READ_GAMMA_SUPPORTED2904/* This is the shared test on whether a gamma value is 'significant' - whether2905* it is worth doing gamma correction.2906*/2907int /* PRIVATE */2908png_gamma_significant(png_fixed_point gamma_val)2909{2910/* sRGB: 1/2.2 == 0.4545(45)2911* AdobeRGB: 1/(2+51/256) ~= 0.45471 5dp2912*2913* So the correction from AdobeRGB to sRGB (output) is:2914*2915* 2.2/(2+51/256) == 1.000355242916*2917* I.e. vanishly small (<4E-4) but still detectable in 16-bit linear (+/-2918* 23). Note that the Adobe choice seems to be something intended to give an2919* exact number with 8 binary fractional digits - it is the closest to 2.22920* that is possible a base 2 .8p representation.2921*/2922return gamma_val < PNG_FP_1 - PNG_GAMMA_THRESHOLD_FIXED ||2923gamma_val > PNG_FP_1 + PNG_GAMMA_THRESHOLD_FIXED;2924}29252926#ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED2927/* A local convenience routine. */2928static png_fixed_point2929png_product2(png_fixed_point a, png_fixed_point b)2930{2931/* The required result is a * b; the following preserves accuracy. */2932#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED /* Should now be unused */2933double r = a * 1E-5;2934r *= b;2935r = floor(r+.5);29362937if (r <= 2147483647. && r >= -2147483648.)2938return (png_fixed_point)r;2939#else2940png_fixed_point res;29412942if (png_muldiv(&res, a, b, 100000) != 0)2943return res;2944#endif29452946return 0; /* overflow */2947}2948#endif /* FLOATING_ARITHMETIC */29492950png_fixed_point2951png_reciprocal2(png_fixed_point a, png_fixed_point b)2952{2953/* The required result is 1/a * 1/b; the following preserves accuracy. */2954#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED2955if (a != 0 && b != 0)2956{2957double r = 1E15/a;2958r /= b;2959r = floor(r+.5);29602961if (r <= 2147483647. && r >= -2147483648.)2962return (png_fixed_point)r;2963}2964#else2965/* This may overflow because the range of png_fixed_point isn't symmetric,2966* but this API is only used for the product of file and screen gamma so it2967* doesn't matter that the smallest number it can produce is 1/21474, not2968* 1/1000002969*/2970png_fixed_point res = png_product2(a, b);29712972if (res != 0)2973return png_reciprocal(res);2974#endif29752976return 0; /* overflow */2977}2978#endif /* READ_GAMMA */29792980#ifdef PNG_READ_GAMMA_SUPPORTED /* gamma table code */2981#ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED2982/* Fixed point gamma.2983*2984* The code to calculate the tables used below can be found in the shell script2985* contrib/tools/intgamma.sh2986*2987* To calculate gamma this code implements fast log() and exp() calls using only2988* fixed point arithmetic. This code has sufficient precision for either 8-bit2989* or 16-bit sample values.2990*2991* The tables used here were calculated using simple 'bc' programs, but C double2992* precision floating point arithmetic would work fine.2993*2994* 8-bit log table2995* This is a table of -log(value/255)/log(2) for 'value' in the range 128 to2996* 255, so it's the base 2 logarithm of a normalized 8-bit floating point2997* mantissa. The numbers are 32-bit fractions.2998*/2999static const png_uint_323000png_8bit_l2[128] =3001{30024270715492U, 4222494797U, 4174646467U, 4127164793U, 4080044201U, 4033279239U,30033986864580U, 3940795015U, 3895065449U, 3849670902U, 3804606499U, 3759867474U,30043715449162U, 3671346997U, 3627556511U, 3584073329U, 3540893168U, 3498011834U,30053455425220U, 3413129301U, 3371120137U, 3329393864U, 3287946700U, 3246774933U,30063205874930U, 3165243125U, 3124876025U, 3084770202U, 3044922296U, 3005329011U,30072965987113U, 2926893432U, 2888044853U, 2849438323U, 2811070844U, 2772939474U,30082735041326U, 2697373562U, 2659933400U, 2622718104U, 2585724991U, 2548951424U,30092512394810U, 2476052606U, 2439922311U, 2404001468U, 2368287663U, 2332778523U,30102297471715U, 2262364947U, 2227455964U, 2192742551U, 2158222529U, 2123893754U,30112089754119U, 2055801552U, 2022034013U, 1988449497U, 1955046031U, 1921821672U,30121888774511U, 1855902668U, 1823204291U, 1790677560U, 1758320682U, 1726131893U,30131694109454U, 1662251657U, 1630556815U, 1599023271U, 1567649391U, 1536433567U,30141505374214U, 1474469770U, 1443718700U, 1413119487U, 1382670639U, 1352370686U,30151322218179U, 1292211689U, 1262349810U, 1232631153U, 1203054352U, 1173618059U,30161144320946U, 1115161701U, 1086139034U, 1057251672U, 1028498358U, 999877854U,3017971388940U, 943030410U, 914801076U, 886699767U, 858725327U, 830876614U,3018803152505U, 775551890U, 748073672U, 720716771U, 693480120U, 666362667U,3019639363374U, 612481215U, 585715177U, 559064263U, 532527486U, 506103872U,3020479792461U, 453592303U, 427502463U, 401522014U, 375650043U, 349885648U,3021324227938U, 298676034U, 273229066U, 247886176U, 222646516U, 197509248U,3022172473545U, 147538590U, 122703574U, 97967701U, 73330182U, 48790236U,302324347096U, 0U30243025#if 03026/* The following are the values for 16-bit tables - these work fine for the3027* 8-bit conversions but produce very slightly larger errors in the 16-bit3028* log (about 1.2 as opposed to 0.7 absolute error in the final value). To3029* use these all the shifts below must be adjusted appropriately.3030*/303165166, 64430, 63700, 62976, 62257, 61543, 60835, 60132, 59434, 58741, 58054,303257371, 56693, 56020, 55352, 54689, 54030, 53375, 52726, 52080, 51439, 50803,303350170, 49542, 48918, 48298, 47682, 47070, 46462, 45858, 45257, 44661, 44068,303443479, 42894, 42312, 41733, 41159, 40587, 40020, 39455, 38894, 38336, 37782,303537230, 36682, 36137, 35595, 35057, 34521, 33988, 33459, 32932, 32408, 31887,303631369, 30854, 30341, 29832, 29325, 28820, 28319, 27820, 27324, 26830, 26339,303725850, 25364, 24880, 24399, 23920, 23444, 22970, 22499, 22029, 21562, 21098,303820636, 20175, 19718, 19262, 18808, 18357, 17908, 17461, 17016, 16573, 16132,303915694, 15257, 14822, 14390, 13959, 13530, 13103, 12678, 12255, 11834, 11415,304010997, 10582, 10168, 9756, 9346, 8937, 8531, 8126, 7723, 7321, 6921, 6523,30416127, 5732, 5339, 4947, 4557, 4169, 3782, 3397, 3014, 2632, 2251, 1872, 1495,30421119, 744, 3723043#endif3044};30453046static png_int_323047png_log8bit(unsigned int x)3048{3049unsigned int lg2 = 0;3050/* Each time 'x' is multiplied by 2, 1 must be subtracted off the final log,3051* because the log is actually negate that means adding 1. The final3052* returned value thus has the range 0 (for 255 input) to 7.994 (for 13053* input), return -1 for the overflow (log 0) case, - so the result is3054* always at most 19 bits.3055*/3056if ((x &= 0xff) == 0)3057return -1;30583059if ((x & 0xf0) == 0)3060lg2 = 4, x <<= 4;30613062if ((x & 0xc0) == 0)3063lg2 += 2, x <<= 2;30643065if ((x & 0x80) == 0)3066lg2 += 1, x <<= 1;30673068/* result is at most 19 bits, so this cast is safe: */3069return (png_int_32)((lg2 << 16) + ((png_8bit_l2[x-128]+32768)>>16));3070}30713072/* The above gives exact (to 16 binary places) log2 values for 8-bit images,3073* for 16-bit images we use the most significant 8 bits of the 16-bit value to3074* get an approximation then multiply the approximation by a correction factor3075* determined by the remaining up to 8 bits. This requires an additional step3076* in the 16-bit case.3077*3078* We want log2(value/65535), we have log2(v'/255), where:3079*3080* value = v' * 256 + v''3081* = v' * f3082*3083* So f is value/v', which is equal to (256+v''/v') since v' is in the range 1283084* to 255 and v'' is in the range 0 to 255 f will be in the range 256 to less3085* than 258. The final factor also needs to correct for the fact that our 8-bit3086* value is scaled by 255, whereas the 16-bit values must be scaled by 65535.3087*3088* This gives a final formula using a calculated value 'x' which is value/v' and3089* scaling by 65536 to match the above table:3090*3091* log2(x/257) * 655363092*3093* Since these numbers are so close to '1' we can use simple linear3094* interpolation between the two end values 256/257 (result -368.61) and 258/2573095* (result 367.179). The values used below are scaled by a further 64 to give3096* 16-bit precision in the interpolation:3097*3098* Start (256): -235913099* Zero (257): 03100* End (258): 234993101*/3102#ifdef PNG_16BIT_SUPPORTED3103static png_int_323104png_log16bit(png_uint_32 x)3105{3106unsigned int lg2 = 0;31073108/* As above, but now the input has 16 bits. */3109if ((x &= 0xffff) == 0)3110return -1;31113112if ((x & 0xff00) == 0)3113lg2 = 8, x <<= 8;31143115if ((x & 0xf000) == 0)3116lg2 += 4, x <<= 4;31173118if ((x & 0xc000) == 0)3119lg2 += 2, x <<= 2;31203121if ((x & 0x8000) == 0)3122lg2 += 1, x <<= 1;31233124/* Calculate the base logarithm from the top 8 bits as a 28-bit fractional3125* value.3126*/3127lg2 <<= 28;3128lg2 += (png_8bit_l2[(x>>8)-128]+8) >> 4;31293130/* Now we need to interpolate the factor, this requires a division by the top3131* 8 bits. Do this with maximum precision.3132*/3133x = ((x << 16) + (x >> 9)) / (x >> 8);31343135/* Since we divided by the top 8 bits of 'x' there will be a '1' at 1<<24,3136* the value at 1<<16 (ignoring this) will be 0 or 1; this gives us exactly3137* 16 bits to interpolate to get the low bits of the result. Round the3138* answer. Note that the end point values are scaled by 64 to retain overall3139* precision and that 'lg2' is current scaled by an extra 12 bits, so adjust3140* the overall scaling by 6-12. Round at every step.3141*/3142x -= 1U << 24;31433144if (x <= 65536U) /* <= '257' */3145lg2 += ((23591U * (65536U-x)) + (1U << (16+6-12-1))) >> (16+6-12);31463147else3148lg2 -= ((23499U * (x-65536U)) + (1U << (16+6-12-1))) >> (16+6-12);31493150/* Safe, because the result can't have more than 20 bits: */3151return (png_int_32)((lg2 + 2048) >> 12);3152}3153#endif /* 16BIT */31543155/* The 'exp()' case must invert the above, taking a 20-bit fixed point3156* logarithmic value and returning a 16 or 8-bit number as appropriate. In3157* each case only the low 16 bits are relevant - the fraction - since the3158* integer bits (the top 4) simply determine a shift.3159*3160* The worst case is the 16-bit distinction between 65535 and 65534. This3161* requires perhaps spurious accuracy in the decoding of the logarithm to3162* distinguish log2(65535/65534.5) - 10^-5 or 17 bits. There is little chance3163* of getting this accuracy in practice.3164*3165* To deal with this the following exp() function works out the exponent of the3166* fractional part of the logarithm by using an accurate 32-bit value from the3167* top four fractional bits then multiplying in the remaining bits.3168*/3169static const png_uint_323170png_32bit_exp[16] =3171{3172/* NOTE: the first entry is deliberately set to the maximum 32-bit value. */31734294967295U, 4112874773U, 3938502376U, 3771522796U, 3611622603U, 3458501653U,31743311872529U, 3171459999U, 3037000500U, 2908241642U, 2784941738U, 2666869345U,31752553802834U, 2445529972U, 2341847524U, 2242560872U3176};31773178/* Adjustment table; provided to explain the numbers in the code below. */3179#if 03180for (i=11;i>=0;--i){ print i, " ", (1 - e(-(2^i)/65536*l(2))) * 2^(32-i), "\n"}318111 44937.64284865548751208448318210 45180.9873484558510116044831839 45303.3193698068735931187231848 45364.6511059532301887078431857 45395.3585036178962461491231866 45410.7225971510203750809631875 45418.4072441322072231116831884 45422.2502178689817300172831893 45424.1718673229841904435231902 45425.1327326994081146470431911 45425.6131755503555864166431920 45425.853399516549438504963193#endif31943195static png_uint_323196png_exp(png_fixed_point x)3197{3198if (x > 0 && x <= 0xfffff) /* Else overflow or zero (underflow) */3199{3200/* Obtain a 4-bit approximation */3201png_uint_32 e = png_32bit_exp[(x >> 12) & 0x0f];32023203/* Incorporate the low 12 bits - these decrease the returned value by3204* multiplying by a number less than 1 if the bit is set. The multiplier3205* is determined by the above table and the shift. Notice that the values3206* converge on 45426 and this is used to allow linear interpolation of the3207* low bits.3208*/3209if (x & 0x800)3210e -= (((e >> 16) * 44938U) + 16U) >> 5;32113212if (x & 0x400)3213e -= (((e >> 16) * 45181U) + 32U) >> 6;32143215if (x & 0x200)3216e -= (((e >> 16) * 45303U) + 64U) >> 7;32173218if (x & 0x100)3219e -= (((e >> 16) * 45365U) + 128U) >> 8;32203221if (x & 0x080)3222e -= (((e >> 16) * 45395U) + 256U) >> 9;32233224if (x & 0x040)3225e -= (((e >> 16) * 45410U) + 512U) >> 10;32263227/* And handle the low 6 bits in a single block. */3228e -= (((e >> 16) * 355U * (x & 0x3fU)) + 256U) >> 9;32293230/* Handle the upper bits of x. */3231e >>= x >> 16;3232return e;3233}32343235/* Check for overflow */3236if (x <= 0)3237return png_32bit_exp[0];32383239/* Else underflow */3240return 0;3241}32423243static png_byte3244png_exp8bit(png_fixed_point lg2)3245{3246/* Get a 32-bit value: */3247png_uint_32 x = png_exp(lg2);32483249/* Convert the 32-bit value to 0..255 by multiplying by 256-1. Note that the3250* second, rounding, step can't overflow because of the first, subtraction,3251* step.3252*/3253x -= x >> 8;3254return (png_byte)(((x + 0x7fffffU) >> 24) & 0xff);3255}32563257#ifdef PNG_16BIT_SUPPORTED3258static png_uint_163259png_exp16bit(png_fixed_point lg2)3260{3261/* Get a 32-bit value: */3262png_uint_32 x = png_exp(lg2);32633264/* Convert the 32-bit value to 0..65535 by multiplying by 65536-1: */3265x -= x >> 16;3266return (png_uint_16)((x + 32767U) >> 16);3267}3268#endif /* 16BIT */3269#endif /* FLOATING_ARITHMETIC */32703271png_byte3272png_gamma_8bit_correct(unsigned int value, png_fixed_point gamma_val)3273{3274if (value > 0 && value < 255)3275{3276# ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3277/* 'value' is unsigned, ANSI-C90 requires the compiler to correctly3278* convert this to a floating point value. This includes values that3279* would overflow if 'value' were to be converted to 'int'.3280*3281* Apparently GCC, however, does an intermediate conversion to (int)3282* on some (ARM) but not all (x86) platforms, possibly because of3283* hardware FP limitations. (E.g. if the hardware conversion always3284* assumes the integer register contains a signed value.) This results3285* in ANSI-C undefined behavior for large values.3286*3287* Other implementations on the same machine might actually be ANSI-C903288* conformant and therefore compile spurious extra code for the large3289* values.3290*3291* We can be reasonably sure that an unsigned to float conversion3292* won't be faster than an int to float one. Therefore this code3293* assumes responsibility for the undefined behavior, which it knows3294* can't happen because of the check above.3295*3296* Note the argument to this routine is an (unsigned int) because, on3297* 16-bit platforms, it is assigned a value which might be out of3298* range for an (int); that would result in undefined behavior in the3299* caller if the *argument* ('value') were to be declared (int).3300*/3301double r = floor(255*pow((int)/*SAFE*/value/255.,gamma_val*.00001)+.5);3302return (png_byte)r;3303# else3304png_int_32 lg2 = png_log8bit(value);3305png_fixed_point res;33063307if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1) != 0)3308return png_exp8bit(res);33093310/* Overflow. */3311value = 0;3312# endif3313}33143315return (png_byte)(value & 0xff);3316}33173318#ifdef PNG_16BIT_SUPPORTED3319png_uint_163320png_gamma_16bit_correct(unsigned int value, png_fixed_point gamma_val)3321{3322if (value > 0 && value < 65535)3323{3324# ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3325/* The same (unsigned int)->(double) constraints apply here as above,3326* however in this case the (unsigned int) to (int) conversion can3327* overflow on an ANSI-C90 compliant system so the cast needs to ensure3328* that this is not possible.3329*/3330double r = floor(65535*pow((png_int_32)value/65535.,3331gamma_val*.00001)+.5);3332return (png_uint_16)r;3333# else3334png_int_32 lg2 = png_log16bit(value);3335png_fixed_point res;33363337if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1) != 0)3338return png_exp16bit(res);33393340/* Overflow. */3341value = 0;3342# endif3343}33443345return (png_uint_16)value;3346}3347#endif /* 16BIT */33483349/* This does the right thing based on the bit_depth field of the3350* png_struct, interpreting values as 8-bit or 16-bit. While the result3351* is nominally a 16-bit value if bit depth is 8 then the result is3352* 8-bit (as are the arguments.)3353*/3354png_uint_16 /* PRIVATE */3355png_gamma_correct(png_structrp png_ptr, unsigned int value,3356png_fixed_point gamma_val)3357{3358if (png_ptr->bit_depth == 8)3359return png_gamma_8bit_correct(value, gamma_val);33603361#ifdef PNG_16BIT_SUPPORTED3362else3363return png_gamma_16bit_correct(value, gamma_val);3364#else3365/* should not reach this */3366return 0;3367#endif /* 16BIT */3368}33693370#ifdef PNG_16BIT_SUPPORTED3371/* Internal function to build a single 16-bit table - the table consists of3372* 'num' 256 entry subtables, where 'num' is determined by 'shift' - the amount3373* to shift the input values right (or 16-number_of_signifiant_bits).3374*3375* The caller is responsible for ensuring that the table gets cleaned up on3376* png_error (i.e. if one of the mallocs below fails) - i.e. the *table argument3377* should be somewhere that will be cleaned.3378*/3379static void3380png_build_16bit_table(png_structrp png_ptr, png_uint_16pp *ptable,3381unsigned int shift, png_fixed_point gamma_val)3382{3383/* Various values derived from 'shift': */3384unsigned int num = 1U << (8U - shift);3385#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3386/* CSE the division and work round wacky GCC warnings (see the comments3387* in png_gamma_8bit_correct for where these come from.)3388*/3389double fmax = 1.0 / (((png_int_32)1 << (16U - shift)) - 1);3390#endif3391unsigned int max = (1U << (16U - shift)) - 1U;3392unsigned int max_by_2 = 1U << (15U - shift);3393unsigned int i;33943395png_uint_16pp table = *ptable =3396(png_uint_16pp)png_calloc(png_ptr, num * (sizeof (png_uint_16p)));33973398for (i = 0; i < num; i++)3399{3400png_uint_16p sub_table = table[i] =3401(png_uint_16p)png_malloc(png_ptr, 256 * (sizeof (png_uint_16)));34023403/* The 'threshold' test is repeated here because it can arise for one of3404* the 16-bit tables even if the others don't hit it.3405*/3406if (png_gamma_significant(gamma_val) != 0)3407{3408/* The old code would overflow at the end and this would cause the3409* 'pow' function to return a result >1, resulting in an3410* arithmetic error. This code follows the spec exactly; ig is3411* the recovered input sample, it always has 8-16 bits.3412*3413* We want input * 65535/max, rounded, the arithmetic fits in 323414* bits (unsigned) so long as max <= 32767.3415*/3416unsigned int j;3417for (j = 0; j < 256; j++)3418{3419png_uint_32 ig = (j << (8-shift)) + i;3420# ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3421/* Inline the 'max' scaling operation: */3422/* See png_gamma_8bit_correct for why the cast to (int) is3423* required here.3424*/3425double d = floor(65535.*pow(ig*fmax, gamma_val*.00001)+.5);3426sub_table[j] = (png_uint_16)d;3427# else3428if (shift != 0)3429ig = (ig * 65535U + max_by_2)/max;34303431sub_table[j] = png_gamma_16bit_correct(ig, gamma_val);3432# endif3433}3434}3435else3436{3437/* We must still build a table, but do it the fast way. */3438unsigned int j;34393440for (j = 0; j < 256; j++)3441{3442png_uint_32 ig = (j << (8-shift)) + i;34433444if (shift != 0)3445ig = (ig * 65535U + max_by_2)/max;34463447sub_table[j] = (png_uint_16)ig;3448}3449}3450}3451}34523453/* NOTE: this function expects the *inverse* of the overall gamma transformation3454* required.3455*/3456static void3457png_build_16to8_table(png_structrp png_ptr, png_uint_16pp *ptable,3458unsigned int shift, png_fixed_point gamma_val)3459{3460unsigned int num = 1U << (8U - shift);3461unsigned int max = (1U << (16U - shift))-1U;3462unsigned int i;3463png_uint_32 last;34643465png_uint_16pp table = *ptable =3466(png_uint_16pp)png_calloc(png_ptr, num * (sizeof (png_uint_16p)));34673468/* 'num' is the number of tables and also the number of low bits of low3469* bits of the input 16-bit value used to select a table. Each table is3470* itself indexed by the high 8 bits of the value.3471*/3472for (i = 0; i < num; i++)3473table[i] = (png_uint_16p)png_malloc(png_ptr,3474256 * (sizeof (png_uint_16)));34753476/* 'gamma_val' is set to the reciprocal of the value calculated above, so3477* pow(out,g) is an *input* value. 'last' is the last input value set.3478*3479* In the loop 'i' is used to find output values. Since the output is3480* 8-bit there are only 256 possible values. The tables are set up to3481* select the closest possible output value for each input by finding3482* the input value at the boundary between each pair of output values3483* and filling the table up to that boundary with the lower output3484* value.3485*3486* The boundary values are 0.5,1.5..253.5,254.5. Since these are 9-bit3487* values the code below uses a 16-bit value in i; the values start at3488* 128.5 (for 0.5) and step by 257, for a total of 254 values (the last3489* entries are filled with 255). Start i at 128 and fill all 'last'3490* table entries <= 'max'3491*/3492last = 0;3493for (i = 0; i < 255; ++i) /* 8-bit output value */3494{3495/* Find the corresponding maximum input value */3496png_uint_16 out = (png_uint_16)(i * 257U); /* 16-bit output value */34973498/* Find the boundary value in 16 bits: */3499png_uint_32 bound = png_gamma_16bit_correct(out+128U, gamma_val);35003501/* Adjust (round) to (16-shift) bits: */3502bound = (bound * max + 32768U)/65535U + 1U;35033504while (last < bound)3505{3506table[last & (0xffU >> shift)][last >> (8U - shift)] = out;3507last++;3508}3509}35103511/* And fill in the final entries. */3512while (last < (num << 8))3513{3514table[last & (0xff >> shift)][last >> (8U - shift)] = 65535U;3515last++;3516}3517}3518#endif /* 16BIT */35193520/* Build a single 8-bit table: same as the 16-bit case but much simpler (and3521* typically much faster). Note that libpng currently does no sBIT processing3522* (apparently contrary to the spec) so a 256-entry table is always generated.3523*/3524static void3525png_build_8bit_table(png_structrp png_ptr, png_bytepp ptable,3526png_fixed_point gamma_val)3527{3528unsigned int i;3529png_bytep table = *ptable = (png_bytep)png_malloc(png_ptr, 256);35303531if (png_gamma_significant(gamma_val) != 0)3532for (i=0; i<256; i++)3533table[i] = png_gamma_8bit_correct(i, gamma_val);35343535else3536for (i=0; i<256; ++i)3537table[i] = (png_byte)(i & 0xff);3538}35393540/* Used from png_read_destroy and below to release the memory used by the gamma3541* tables.3542*/3543void /* PRIVATE */3544png_destroy_gamma_table(png_structrp png_ptr)3545{3546png_free(png_ptr, png_ptr->gamma_table);3547png_ptr->gamma_table = NULL;35483549#ifdef PNG_16BIT_SUPPORTED3550if (png_ptr->gamma_16_table != NULL)3551{3552int i;3553int istop = (1 << (8 - png_ptr->gamma_shift));3554for (i = 0; i < istop; i++)3555{3556png_free(png_ptr, png_ptr->gamma_16_table[i]);3557}3558png_free(png_ptr, png_ptr->gamma_16_table);3559png_ptr->gamma_16_table = NULL;3560}3561#endif /* 16BIT */35623563#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \3564defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \3565defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)3566png_free(png_ptr, png_ptr->gamma_from_1);3567png_ptr->gamma_from_1 = NULL;3568png_free(png_ptr, png_ptr->gamma_to_1);3569png_ptr->gamma_to_1 = NULL;35703571#ifdef PNG_16BIT_SUPPORTED3572if (png_ptr->gamma_16_from_1 != NULL)3573{3574int i;3575int istop = (1 << (8 - png_ptr->gamma_shift));3576for (i = 0; i < istop; i++)3577{3578png_free(png_ptr, png_ptr->gamma_16_from_1[i]);3579}3580png_free(png_ptr, png_ptr->gamma_16_from_1);3581png_ptr->gamma_16_from_1 = NULL;3582}3583if (png_ptr->gamma_16_to_1 != NULL)3584{3585int i;3586int istop = (1 << (8 - png_ptr->gamma_shift));3587for (i = 0; i < istop; i++)3588{3589png_free(png_ptr, png_ptr->gamma_16_to_1[i]);3590}3591png_free(png_ptr, png_ptr->gamma_16_to_1);3592png_ptr->gamma_16_to_1 = NULL;3593}3594#endif /* 16BIT */3595#endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */3596}35973598/* We build the 8- or 16-bit gamma tables here. Note that for 16-bit3599* tables, we don't make a full table if we are reducing to 8-bit in3600* the future. Note also how the gamma_16 tables are segmented so that3601* we don't need to allocate > 64K chunks for a full 16-bit table.3602*3603* TODO: move this to pngrtran.c and make it static. Better yet create3604* pngcolor.c and put all the PNG_COLORSPACE stuff in there.3605*/3606#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \3607defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \3608defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)3609# define GAMMA_TRANSFORMS 1 /* #ifdef CSE */3610#else3611# define GAMMA_TRANSFORMS 03612#endif36133614void /* PRIVATE */3615png_build_gamma_table(png_structrp png_ptr, int bit_depth)3616{3617png_fixed_point file_gamma, screen_gamma;3618png_fixed_point correction;3619# if GAMMA_TRANSFORMS3620png_fixed_point file_to_linear, linear_to_screen;3621# endif36223623png_debug(1, "in png_build_gamma_table");36243625/* Remove any existing table; this copes with multiple calls to3626* png_read_update_info. The warning is because building the gamma tables3627* multiple times is a performance hit - it's harmless but the ability to3628* call png_read_update_info() multiple times is new in 1.5.6 so it seems3629* sensible to warn if the app introduces such a hit.3630*/3631if (png_ptr->gamma_table != NULL || png_ptr->gamma_16_table != NULL)3632{3633png_warning(png_ptr, "gamma table being rebuilt");3634png_destroy_gamma_table(png_ptr);3635}36363637/* The following fields are set, finally, in png_init_read_transformations.3638* If file_gamma is 0 (unset) nothing can be done otherwise if screen_gamma3639* is 0 (unset) there is no gamma correction but to/from linear is possible.3640*/3641file_gamma = png_ptr->file_gamma;3642screen_gamma = png_ptr->screen_gamma;3643# if GAMMA_TRANSFORMS3644file_to_linear = png_reciprocal(file_gamma);3645# endif36463647if (screen_gamma > 0)3648{3649# if GAMMA_TRANSFORMS3650linear_to_screen = png_reciprocal(screen_gamma);3651# endif3652correction = png_reciprocal2(screen_gamma, file_gamma);3653}3654else /* screen gamma unknown */3655{3656# if GAMMA_TRANSFORMS3657linear_to_screen = file_gamma;3658# endif3659correction = PNG_FP_1;3660}36613662if (bit_depth <= 8)3663{3664png_build_8bit_table(png_ptr, &png_ptr->gamma_table, correction);36653666#if GAMMA_TRANSFORMS3667if ((png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY)) != 0)3668{3669png_build_8bit_table(png_ptr, &png_ptr->gamma_to_1, file_to_linear);36703671png_build_8bit_table(png_ptr, &png_ptr->gamma_from_1,3672linear_to_screen);3673}3674#endif /* GAMMA_TRANSFORMS */3675}3676#ifdef PNG_16BIT_SUPPORTED3677else3678{3679png_byte shift, sig_bit;36803681if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)3682{3683sig_bit = png_ptr->sig_bit.red;36843685if (png_ptr->sig_bit.green > sig_bit)3686sig_bit = png_ptr->sig_bit.green;36873688if (png_ptr->sig_bit.blue > sig_bit)3689sig_bit = png_ptr->sig_bit.blue;3690}3691else3692sig_bit = png_ptr->sig_bit.gray;36933694/* 16-bit gamma code uses this equation:3695*3696* ov = table[(iv & 0xff) >> gamma_shift][iv >> 8]3697*3698* Where 'iv' is the input color value and 'ov' is the output value -3699* pow(iv, gamma).3700*3701* Thus the gamma table consists of up to 256 256-entry tables. The table3702* is selected by the (8-gamma_shift) most significant of the low 8 bits3703* of the color value then indexed by the upper 8 bits:3704*3705* table[low bits][high 8 bits]3706*3707* So the table 'n' corresponds to all those 'iv' of:3708*3709* <all high 8-bit values><n << gamma_shift>..<(n+1 << gamma_shift)-1>3710*3711*/3712if (sig_bit > 0 && sig_bit < 16U)3713/* shift == insignificant bits */3714shift = (png_byte)((16U - sig_bit) & 0xff);37153716else3717shift = 0; /* keep all 16 bits */37183719if ((png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8)) != 0)3720{3721/* PNG_MAX_GAMMA_8 is the number of bits to keep - effectively3722* the significant bits in the *input* when the output will3723* eventually be 8 bits. By default it is 11.3724*/3725if (shift < (16U - PNG_MAX_GAMMA_8))3726shift = (16U - PNG_MAX_GAMMA_8);3727}37283729if (shift > 8U)3730shift = 8U; /* Guarantees at least one table! */37313732png_ptr->gamma_shift = shift;37333734/* NOTE: prior to 1.5.4 this test used to include PNG_BACKGROUND (now3735* PNG_COMPOSE). This effectively smashed the background calculation for3736* 16-bit output because the 8-bit table assumes the result will be3737* reduced to 8 bits.3738*/3739if ((png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8)) != 0)3740png_build_16to8_table(png_ptr, &png_ptr->gamma_16_table, shift,3741png_reciprocal(correction));3742else3743png_build_16bit_table(png_ptr, &png_ptr->gamma_16_table, shift,3744correction);37453746# if GAMMA_TRANSFORMS3747if ((png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY)) != 0)3748{3749png_build_16bit_table(png_ptr, &png_ptr->gamma_16_to_1, shift,3750file_to_linear);37513752/* Notice that the '16 from 1' table should be full precision, however3753* the lookup on this table still uses gamma_shift, so it can't be.3754* TODO: fix this.3755*/3756png_build_16bit_table(png_ptr, &png_ptr->gamma_16_from_1, shift,3757linear_to_screen);3758}3759#endif /* GAMMA_TRANSFORMS */3760}3761#endif /* 16BIT */3762}3763#endif /* READ_GAMMA */37643765/* HARDWARE OR SOFTWARE OPTION SUPPORT */3766#ifdef PNG_SET_OPTION_SUPPORTED3767int PNGAPI3768png_set_option(png_structrp png_ptr, int option, int onoff)3769{3770if (png_ptr != NULL && option >= 0 && option < PNG_OPTION_NEXT &&3771(option & 1) == 0)3772{3773png_uint_32 mask = 3U << option;3774png_uint_32 setting = (2U + (onoff != 0)) << option;3775png_uint_32 current = png_ptr->options;37763777png_ptr->options = (png_uint_32)((current & ~mask) | setting);37783779return (int)(current & mask) >> option;3780}37813782return PNG_OPTION_INVALID;3783}3784#endif37853786/* sRGB support */3787#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\3788defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)3789/* sRGB conversion tables; these are machine generated with the code in3790* contrib/tools/makesRGB.c. The actual sRGB transfer curve defined in the3791* specification (see the article at https://en.wikipedia.org/wiki/SRGB)3792* is used, not the gamma=1/2.2 approximation use elsewhere in libpng.3793* The sRGB to linear table is exact (to the nearest 16-bit linear fraction).3794* The inverse (linear to sRGB) table has accuracies as follows:3795*3796* For all possible (255*65535+1) input values:3797*3798* error: -0.515566 - 0.625971, 79441 (0.475369%) of readings inexact3799*3800* For the input values corresponding to the 65536 16-bit values:3801*3802* error: -0.513727 - 0.607759, 308 (0.469978%) of readings inexact3803*3804* In all cases the inexact readings are only off by one.3805*/38063807#ifdef PNG_SIMPLIFIED_READ_SUPPORTED3808/* The convert-to-sRGB table is only currently required for read. */3809const png_uint_16 png_sRGB_table[256] =3810{38110,20,40,60,80,99,119,139,3812159,179,199,219,241,264,288,313,3813340,367,396,427,458,491,526,562,3814599,637,677,718,761,805,851,898,3815947,997,1048,1101,1156,1212,1270,1330,38161391,1453,1517,1583,1651,1720,1790,1863,38171937,2013,2090,2170,2250,2333,2418,2504,38182592,2681,2773,2866,2961,3058,3157,3258,38193360,3464,3570,3678,3788,3900,4014,4129,38204247,4366,4488,4611,4736,4864,4993,5124,38215257,5392,5530,5669,5810,5953,6099,6246,38226395,6547,6700,6856,7014,7174,7335,7500,38237666,7834,8004,8177,8352,8528,8708,8889,38249072,9258,9445,9635,9828,10022,10219,10417,382510619,10822,11028,11235,11446,11658,11873,12090,382612309,12530,12754,12980,13209,13440,13673,13909,382714146,14387,14629,14874,15122,15371,15623,15878,382816135,16394,16656,16920,17187,17456,17727,18001,382918277,18556,18837,19121,19407,19696,19987,20281,383020577,20876,21177,21481,21787,22096,22407,22721,383123038,23357,23678,24002,24329,24658,24990,25325,383225662,26001,26344,26688,27036,27386,27739,28094,383328452,28813,29176,29542,29911,30282,30656,31033,383431412,31794,32179,32567,32957,33350,33745,34143,383534544,34948,35355,35764,36176,36591,37008,37429,383637852,38278,38706,39138,39572,40009,40449,40891,383741337,41785,42236,42690,43147,43606,44069,44534,383845002,45473,45947,46423,46903,47385,47871,48359,383948850,49344,49841,50341,50844,51349,51858,52369,384052884,53401,53921,54445,54971,55500,56032,56567,384157105,57646,58190,58737,59287,59840,60396,60955,384261517,62082,62650,63221,63795,64372,64952,655353843};3844#endif /* SIMPLIFIED_READ */38453846/* The base/delta tables are required for both read and write (but currently3847* only the simplified versions.)3848*/3849const png_uint_16 png_sRGB_base[512] =3850{3851128,1782,3383,4644,5675,6564,7357,8074,38528732,9346,9921,10463,10977,11466,11935,12384,385312816,13233,13634,14024,14402,14769,15125,15473,385415812,16142,16466,16781,17090,17393,17690,17981,385518266,18546,18822,19093,19359,19621,19879,20133,385620383,20630,20873,21113,21349,21583,21813,22041,385722265,22487,22707,22923,23138,23350,23559,23767,385823972,24175,24376,24575,24772,24967,25160,25352,385925542,25730,25916,26101,26284,26465,26645,26823,386027000,27176,27350,27523,27695,27865,28034,28201,386128368,28533,28697,28860,29021,29182,29341,29500,386229657,29813,29969,30123,30276,30429,30580,30730,386330880,31028,31176,31323,31469,31614,31758,31902,386432045,32186,32327,32468,32607,32746,32884,33021,386533158,33294,33429,33564,33697,33831,33963,34095,386634226,34357,34486,34616,34744,34873,35000,35127,386735253,35379,35504,35629,35753,35876,35999,36122,386836244,36365,36486,36606,36726,36845,36964,37083,386937201,37318,37435,37551,37668,37783,37898,38013,387038127,38241,38354,38467,38580,38692,38803,38915,387139026,39136,39246,39356,39465,39574,39682,39790,387239898,40005,40112,40219,40325,40431,40537,40642,387340747,40851,40955,41059,41163,41266,41369,41471,387441573,41675,41777,41878,41979,42079,42179,42279,387542379,42478,42577,42676,42775,42873,42971,43068,387643165,43262,43359,43456,43552,43648,43743,43839,387743934,44028,44123,44217,44311,44405,44499,44592,387844685,44778,44870,44962,45054,45146,45238,45329,387945420,45511,45601,45692,45782,45872,45961,46051,388046140,46229,46318,46406,46494,46583,46670,46758,388146846,46933,47020,47107,47193,47280,47366,47452,388247538,47623,47709,47794,47879,47964,48048,48133,388348217,48301,48385,48468,48552,48635,48718,48801,388448884,48966,49048,49131,49213,49294,49376,49458,388549539,49620,49701,49782,49862,49943,50023,50103,388650183,50263,50342,50422,50501,50580,50659,50738,388750816,50895,50973,51051,51129,51207,51285,51362,388851439,51517,51594,51671,51747,51824,51900,51977,388952053,52129,52205,52280,52356,52432,52507,52582,389052657,52732,52807,52881,52956,53030,53104,53178,389153252,53326,53400,53473,53546,53620,53693,53766,389253839,53911,53984,54056,54129,54201,54273,54345,389354417,54489,54560,54632,54703,54774,54845,54916,389454987,55058,55129,55199,55269,55340,55410,55480,389555550,55620,55689,55759,55828,55898,55967,56036,389656105,56174,56243,56311,56380,56448,56517,56585,389756653,56721,56789,56857,56924,56992,57059,57127,389857194,57261,57328,57395,57462,57529,57595,57662,389957728,57795,57861,57927,57993,58059,58125,58191,390058256,58322,58387,58453,58518,58583,58648,58713,390158778,58843,58908,58972,59037,59101,59165,59230,390259294,59358,59422,59486,59549,59613,59677,59740,390359804,59867,59930,59993,60056,60119,60182,60245,390460308,60370,60433,60495,60558,60620,60682,60744,390560806,60868,60930,60992,61054,61115,61177,61238,390661300,61361,61422,61483,61544,61605,61666,61727,390761788,61848,61909,61969,62030,62090,62150,62211,390862271,62331,62391,62450,62510,62570,62630,62689,390962749,62808,62867,62927,62986,63045,63104,63163,391063222,63281,63340,63398,63457,63515,63574,63632,391163691,63749,63807,63865,63923,63981,64039,64097,391264155,64212,64270,64328,64385,64443,64500,64557,391364614,64672,64729,64786,64843,64900,64956,65013,391465070,65126,65183,65239,65296,65352,65409,654653915};39163917const png_byte png_sRGB_delta[512] =3918{3919207,201,158,129,113,100,90,82,77,72,68,64,61,59,56,54,392052,50,49,47,46,45,43,42,41,40,39,39,38,37,36,36,392135,34,34,33,33,32,32,31,31,30,30,30,29,29,28,28,392228,27,27,27,27,26,26,26,25,25,25,25,24,24,24,24,392323,23,23,23,23,22,22,22,22,22,22,21,21,21,21,21,392421,20,20,20,20,20,20,20,20,19,19,19,19,19,19,19,392519,18,18,18,18,18,18,18,18,18,18,17,17,17,17,17,392617,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,392716,16,16,16,15,15,15,15,15,15,15,15,15,15,15,15,392815,15,15,15,14,14,14,14,14,14,14,14,14,14,14,14,392914,14,14,14,14,14,14,13,13,13,13,13,13,13,13,13,393013,13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,393112,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,393212,12,12,12,12,12,12,12,12,12,12,12,11,11,11,11,393311,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,393411,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,393511,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,393610,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,393710,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,393810,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,39399,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,39409,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,39419,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,39429,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,39438,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,39448,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,39458,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,39468,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,39478,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,39487,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,39497,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,39507,7,7,7,7,7,7,7,7,7,7,7,7,7,7,73951};3952#endif /* SIMPLIFIED READ/WRITE sRGB support */39533954/* SIMPLIFIED READ/WRITE SUPPORT */3955#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\3956defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)3957static int3958png_image_free_function(png_voidp argument)3959{3960png_imagep image = png_voidcast(png_imagep, argument);3961png_controlp cp = image->opaque;3962png_control c;39633964/* Double check that we have a png_ptr - it should be impossible to get here3965* without one.3966*/3967if (cp->png_ptr == NULL)3968return 0;39693970/* First free any data held in the control structure. */3971# ifdef PNG_STDIO_SUPPORTED3972if (cp->owned_file != 0)3973{3974FILE *fp = png_voidcast(FILE *, cp->png_ptr->io_ptr);3975cp->owned_file = 0;39763977/* Ignore errors here. */3978if (fp != NULL)3979{3980cp->png_ptr->io_ptr = NULL;3981(void)fclose(fp);3982}3983}3984# endif39853986/* Copy the control structure so that the original, allocated, version can be3987* safely freed. Notice that a png_error here stops the remainder of the3988* cleanup, but this is probably fine because that would indicate bad memory3989* problems anyway.3990*/3991c = *cp;3992image->opaque = &c;3993png_free(c.png_ptr, cp);39943995/* Then the structures, calling the correct API. */3996if (c.for_write != 0)3997{3998# ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED3999png_destroy_write_struct(&c.png_ptr, &c.info_ptr);4000# else4001png_error(c.png_ptr, "simplified write not supported");4002# endif4003}4004else4005{4006# ifdef PNG_SIMPLIFIED_READ_SUPPORTED4007png_destroy_read_struct(&c.png_ptr, &c.info_ptr, NULL);4008# else4009png_error(c.png_ptr, "simplified read not supported");4010# endif4011}40124013/* Success. */4014return 1;4015}40164017void PNGAPI4018png_image_free(png_imagep image)4019{4020/* Safely call the real function, but only if doing so is safe at this point4021* (if not inside an error handling context). Otherwise assume4022* png_safe_execute will call this API after the return.4023*/4024if (image != NULL && image->opaque != NULL &&4025image->opaque->error_buf == NULL)4026{4027png_image_free_function(image);4028image->opaque = NULL;4029}4030}40314032int /* PRIVATE */4033png_image_error(png_imagep image, png_const_charp error_message)4034{4035/* Utility to log an error. */4036png_safecat(image->message, (sizeof image->message), 0, error_message);4037image->warning_or_error |= PNG_IMAGE_ERROR;4038png_image_free(image);4039return 0;4040}40414042#endif /* SIMPLIFIED READ/WRITE */4043#endif /* READ || WRITE */404440454046