CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/ext/libpng17/png.c
Views: 1401
1/* png.c - location for general purpose libpng functions2*3* Last changed in libpng 1.7.0 [(PENDING RELEASE)]4* Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson5* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)6* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)7*8* This code is released under the libpng license.9* For conditions of distribution and use, see the disclaimer10* and license in png.h11*/1213#include "pngpriv.h"14#define PNG_SRC_FILE PNG_SRC_FILE_png1516/* Generate a compiler error if there is an old png.h in the search path. */17typedef png_libpng_version_1_7_0beta90 Your_png_h_is_not_version_1_7_0beta90;1819/* Tells libpng that we have already handled the first "num_bytes" bytes20* of the PNG file signature. If the PNG data is embedded into another21* stream we can set num_bytes = 8 so that libpng will not attempt to read22* or write any of the magic bytes before it starts on the IHDR.23*/2425#ifdef PNG_READ_SUPPORTED26void PNGAPI27png_set_sig_bytes(png_structrp png_ptr, int num_bytes)28{29png_debug(1, "in png_set_sig_bytes");3031if (png_ptr == NULL)32return;3334if (num_bytes > 8)35png_error(png_ptr, "Too many bytes for PNG signature");3637png_ptr->sig_bytes = png_check_byte(png_ptr, num_bytes < 0 ? 0 : num_bytes);38}3940/* Checks whether the supplied bytes match the PNG signature. We allow41* checking less than the full 8-byte signature so that those apps that42* already read the first few bytes of a file to determine the file type43* can simply check the remaining bytes for extra assurance. Returns44* an integer less than, equal to, or greater than zero if sig is found,45* respectively, to be less than, to match, or be greater than the correct46* PNG signature (this is the same behavior as strcmp, memcmp, etc).47*/48int PNGAPI49png_sig_cmp(png_const_bytep sig, png_size_t start, png_size_t num_to_check)50{51png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};5253if (num_to_check > 8)54num_to_check = 8;5556else if (num_to_check < 1)57return (-1);5859if (start > 7)60return (-1);6162if (start + num_to_check > 8)63num_to_check = 8 - start;6465return ((int)(memcmp(&sig[start], &png_signature[start], num_to_check)));66}6768#endif /* READ */6970#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)71/* Function to allocate memory for zlib */72PNG_FUNCTION(voidpf /* PRIVATE */,73png_zalloc,(voidpf png_ptr, uInt items, uInt size),PNG_ALLOCATED)74{75png_alloc_size_t num_bytes = size;7677if (png_ptr == NULL)78return NULL;7980if (items >= (~(png_alloc_size_t)0)/size)81{82png_warning(png_voidcast(png_structrp, png_ptr),83"Potential overflow in png_zalloc()");84return NULL;85}8687num_bytes *= items;88return png_malloc_warn(png_voidcast(png_structrp, png_ptr), num_bytes);89}9091/* Function to free memory for zlib */92void /* PRIVATE */93png_zfree(voidpf png_ptr, voidpf ptr)94{95png_free(png_voidcast(png_const_structrp,png_ptr), ptr);96}9798/* Reset the CRC variable to 32 bits of 1's. Care must be taken99* in case CRC is > 32 bits to leave the top bits 0.100*/101void /* PRIVATE */102png_reset_crc(png_structrp png_ptr, png_const_bytep chunk_tag)103{104# ifdef PNG_READ_SUPPORTED105if (png_ptr->read_struct)106{107/* Set png_struct::current_crc appropriately. */108if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name))109png_ptr->current_crc = png_ptr->ancillary_crc;110111else /* critical */112png_ptr->current_crc = png_ptr->critical_crc;113}114115else116png_ptr->current_crc = crc_error_quit; /* for write */117118/* Now do not calculate the CRC if it isn't required: */119if (png_ptr->current_crc != crc_quiet_use)120# endif /* READ */121png_ptr->crc = 0xFFFFFFFFU & crc32(0, chunk_tag, 4);122}123124/* Calculate the CRC over a section of data. We can only pass as125* much data to this routine as the largest single buffer size. We126* also check that this data will actually be used before going to the127* trouble of calculating it.128*/129void /* PRIVATE */130png_calculate_crc(png_structrp png_ptr, png_const_voidp ptr, png_size_t length)131{132/* 'uLong' is defined in zlib.h as unsigned long; this means that on some133* systems it is a 64 bit value. crc32, however, returns 32 bits so the134* following cast is safe. 'uInt' may be no more than 16 bits, so it is135* necessary to perform a loop here.136*/137# ifdef PNG_READ_SUPPORTED138if (png_ptr->current_crc != crc_quiet_use)139# endif /* READ */140if (length > 0)141{142uLong crc = png_ptr->crc; /* Should never issue a warning */143const Bytef* rptr = png_voidcast(const Bytef*,ptr);144145do146{147uInt safe_length;148149/* TODO: this uses ZLIB_IO_MAX which may be #defined to less than the150* maximum of a uInt, is this the best thing to do?151*/152if (length > ZLIB_IO_MAX)153safe_length = ZLIB_IO_MAX;154155else156safe_length = (uInt)/*SAFE*/length;157158crc = crc32(crc, PNGZ_INPUT_CAST(rptr), safe_length);159160/* The following should never issue compiler warnings; if they do the161* target system has characteristics that will probably violate other162* assumptions within the libpng code.163*/164rptr += safe_length;165length -= safe_length;166}167while (length > 0);168169/* And the following is always safe because the crc is only 32 bits. */170png_ptr->crc = 0xFFFFFFFFU & crc;171}172}173174/* Check a user supplied version number, called from both read and write175* functions that create a png_struct.176*/177static int178png_user_version_check(png_structrp png_ptr, png_const_charp user_png_ver)179{180/* Libpng versions 1.0.0 and later are binary compatible if the version181* string matches through the second '.'; we must recompile any applications182* that use any older library version.183*/184if (user_png_ver != NULL)185{186int library_match = 1;187int i = -1;188unsigned int found_dots = 0;189190do191{192i++;193if (user_png_ver[i] != PNG_LIBPNG_VER_STRING[i])194library_match = 0;195if (user_png_ver[i] == '.')196found_dots++;197} while (library_match && found_dots < 2 && user_png_ver[i] != 0 &&198PNG_LIBPNG_VER_STRING[i] != 0);199200if (library_match)201return 1; /* Library matches ok */202}203204/* Failure: mismatched library major version number */205#ifdef PNG_WARNINGS_SUPPORTED206{207size_t pos = 0;208char m[128];209210pos = png_safecat(m, (sizeof m), pos,211"Application built with libpng-");212/* This is ok if user_png_ver is NULL, it appends nothing: */213pos = png_safecat(m, (sizeof m), pos, user_png_ver);214pos = png_safecat(m, (sizeof m), pos, " but running with ");215pos = png_safecat(m, (sizeof m), pos, PNG_LIBPNG_VER_STRING);216PNG_UNUSED(pos)217218png_app_warning(png_ptr, m);219}220#endif221222return 0; /* Failure */223PNG_UNUSED(png_ptr) /* if no warning */224}225226/* Generic function to create a png_struct for either read or write - this227* contains the common initialization.228*/229PNG_FUNCTION(png_structp /* PRIVATE */,230png_create_png_struct,(png_const_charp user_png_ver, png_voidp error_ptr,231png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,232png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)233{234png_struct create_struct;235# ifdef PNG_SETJMP_SUPPORTED236jmp_buf create_jmp_buf;237# endif238239/* This is a compile-type only test to ensure that the build satisifies the240* contraints for the row buffer stack allocations. A 'duplicate case241* statements' style of error means that one of the tests below failed:242*/243switch (0)244{245case 0:246case PNG_ROW_BUFFER_SIZE >= PNG_MIN_ROW_BUFFER_SIZE: /*1*/247case 2*(PNG_ROW_BUFFER_SIZE <= PNG_MAX_ROW_BUFFER_SIZE): /*2*/248default:249break;250}251252/* This temporary stack-allocated structure is used to provide a place to253* build enough context to allow the user provided memory allocator (if any)254* to be called.255*/256memset(&create_struct, 0, (sizeof create_struct));257258/* These limits are only used on read at present, and if READ is not turned259* on neither will USER_LIMITS be. The width/height and chunk malloc limits260* are constants, so if they cannot be set they don't get defined in261* png_struct, the user_chunk_cache limits is a down-counter, when it reaches262* 1 no more chunks will be handled. 0 means unlimited, consequently the263* limit is 1 more than the number of chunks that will be handled.264*/265# ifdef PNG_SET_USER_LIMITS_SUPPORTED266create_struct.user_width_max = PNG_USER_WIDTH_MAX;267create_struct.user_height_max = PNG_USER_HEIGHT_MAX;268create_struct.user_chunk_malloc_max = PNG_USER_CHUNK_MALLOC_MAX;269# endif270# ifdef PNG_USER_LIMITS_SUPPORTED271/* Must exist even if the initial value is constant */272create_struct.user_chunk_cache_max = PNG_USER_CHUNK_CACHE_MAX;273# endif274275/* The following two API calls simply set fields in png_struct, so it is safe276* to do them now even though error handling is not yet set up.277*/278# ifdef PNG_USER_MEM_SUPPORTED279png_set_mem_fn(&create_struct, mem_ptr, malloc_fn, free_fn);280# else281PNG_UNUSED(mem_ptr)282PNG_UNUSED(malloc_fn)283PNG_UNUSED(free_fn)284# endif285286/* (*error_fn) can return control to the caller after the error_ptr is set,287* this will result in a memory leak unless the error_fn does something288* extremely sophisticated. The design lacks merit but is implicit in the289* API.290*/291png_set_error_fn(&create_struct, error_ptr, error_fn, warn_fn);292293# ifdef PNG_SETJMP_SUPPORTED294if (!setjmp(create_jmp_buf))295# endif296{297# ifdef PNG_SETJMP_SUPPORTED298/* Temporarily fake out the longjmp information until we have299* successfully completed this function. This only works if we have300* setjmp() support compiled in, but it is safe - this stuff should301* never happen.302*/303create_struct.jmp_buf_ptr = &create_jmp_buf;304create_struct.jmp_buf_size = 0; /*stack allocation*/305create_struct.longjmp_fn = longjmp;306# endif307/* Call the general version checker (shared with read and write code):308*/309if (png_user_version_check(&create_struct, user_png_ver) != 0)310{311png_structrp png_ptr = png_voidcast(png_structrp,312png_malloc_warn(&create_struct, (sizeof *png_ptr)));313314if (png_ptr != NULL)315{316# ifdef PNG_SETJMP_SUPPORTED317/* Eliminate the local error handling: */318create_struct.jmp_buf_ptr = NULL;319create_struct.jmp_buf_size = 0;320create_struct.longjmp_fn = 0;321# endif322323*png_ptr = create_struct;324325/* This is the successful return point */326return png_ptr;327}328}329}330331/* A longjmp because of a bug in the application storage allocator or a332* simple failure to allocate the png_struct.333*/334return NULL;335}336337/* Allocate the memory for an info_struct for the application. */338PNG_FUNCTION(png_infop,PNGAPI339png_create_info_struct,(png_const_structrp png_ptr),PNG_ALLOCATED)340{341png_inforp info_ptr;342343png_debug(1, "in png_create_info_struct");344345if (png_ptr == NULL)346return NULL;347348/* Use the internal API that does not (or at least should not) error out, so349* that this call always returns ok. The application typically sets up the350* error handling *after* creating the info_struct because this is the way it351* has always been done in 'example.c'.352*/353info_ptr = png_voidcast(png_inforp, png_malloc_base(png_ptr,354(sizeof *info_ptr)));355356if (info_ptr != NULL)357memset(info_ptr, 0, (sizeof *info_ptr));358359return info_ptr;360}361362/* This function frees the memory associated with a single info struct.363* Normally, one would use either png_destroy_read_struct() or364* png_destroy_write_struct() to free an info struct, but this may be365* useful for some applications. From libpng 1.6.0 this function is also used366* internally to implement the png_info release part of the 'struct' destroy367* APIs. This ensures that all possible approaches free the same data (all of368* it).369*/370void PNGAPI371png_destroy_info_struct(png_const_structrp png_ptr, png_infopp info_ptr_ptr)372{373png_inforp info_ptr = NULL;374375png_debug(1, "in png_destroy_info_struct");376377if (png_ptr == NULL)378return;379380if (info_ptr_ptr != NULL)381info_ptr = *info_ptr_ptr;382383if (info_ptr != NULL)384{385/* Do this first in case of an error below; if the app implements its own386* memory management this can lead to png_free calling png_error, which387* will abort this routine and return control to the app error handler.388* An infinite loop may result if it then tries to free the same info389* ptr.390*/391*info_ptr_ptr = NULL;392393png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);394memset(info_ptr, 0, (sizeof *info_ptr));395png_free(png_ptr, info_ptr);396}397}398399void PNGAPI400png_free_data(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 mask,401int num)402{403png_debug(1, "in png_free_data");404405if (png_ptr == NULL || info_ptr == NULL)406return;407408#ifdef PNG_TEXT_SUPPORTED409/* Free text item num or (if num == -1) all text items */410if (info_ptr->text != 0 &&411((mask & PNG_FREE_TEXT) & info_ptr->free_me) != 0)412{413if (num != -1)414{415png_free(png_ptr, info_ptr->text[num].key);416info_ptr->text[num].key = NULL;417}418419else420{421int i;422423for (i = 0; i < info_ptr->num_text; i++)424png_free(png_ptr, info_ptr->text[i].key);425426png_free(png_ptr, info_ptr->text);427info_ptr->text = NULL;428info_ptr->num_text = 0;429info_ptr->max_text = 0;430}431}432#endif433434#ifdef PNG_tRNS_SUPPORTED435/* Free any tRNS entry */436if (((mask & PNG_FREE_TRNS) & info_ptr->free_me) != 0)437{438info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_tRNS);439png_free(png_ptr, info_ptr->trans_alpha);440info_ptr->trans_alpha = NULL;441info_ptr->num_trans = 0;442}443#endif444445#ifdef PNG_sCAL_SUPPORTED446/* Free any sCAL entry */447if (((mask & PNG_FREE_SCAL) & info_ptr->free_me) != 0)448{449png_free(png_ptr, info_ptr->scal_s_width);450png_free(png_ptr, info_ptr->scal_s_height);451info_ptr->scal_s_width = NULL;452info_ptr->scal_s_height = NULL;453info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_sCAL);454}455#endif456457#ifdef PNG_pCAL_SUPPORTED458/* Free any pCAL entry */459if (((mask & PNG_FREE_PCAL) & info_ptr->free_me) != 0)460{461png_free(png_ptr, info_ptr->pcal_purpose);462png_free(png_ptr, info_ptr->pcal_units);463info_ptr->pcal_purpose = NULL;464info_ptr->pcal_units = NULL;465466if (info_ptr->pcal_params != NULL)467{468int i;469470for (i = 0; i < info_ptr->pcal_nparams; i++)471png_free(png_ptr, info_ptr->pcal_params[i]);472473png_free(png_ptr, info_ptr->pcal_params);474info_ptr->pcal_params = NULL;475}476info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_pCAL);477}478#endif479480#ifdef PNG_iCCP_SUPPORTED481/* Free any profile entry */482if (((mask & PNG_FREE_ICCP) & info_ptr->free_me) != 0)483{484png_free(png_ptr, info_ptr->iccp_name);485png_free(png_ptr, info_ptr->iccp_profile);486info_ptr->iccp_name = NULL;487info_ptr->iccp_profile = NULL;488info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_iCCP);489}490#endif491492#ifdef PNG_sPLT_SUPPORTED493/* Free a given sPLT entry, or (if num == -1) all sPLT entries */494if (info_ptr->splt_palettes != 0 &&495((mask & PNG_FREE_SPLT) & info_ptr->free_me) != 0)496{497if (num != -1)498{499png_free(png_ptr, info_ptr->splt_palettes[num].name);500png_free(png_ptr, info_ptr->splt_palettes[num].entries);501info_ptr->splt_palettes[num].name = NULL;502info_ptr->splt_palettes[num].entries = NULL;503}504505else506{507int i;508509for (i = 0; i < info_ptr->splt_palettes_num; i++)510{511png_free(png_ptr, info_ptr->splt_palettes[i].name);512png_free(png_ptr, info_ptr->splt_palettes[i].entries);513}514515png_free(png_ptr, info_ptr->splt_palettes);516info_ptr->splt_palettes = NULL;517info_ptr->splt_palettes_num = 0;518info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_sPLT);519}520}521#endif522523#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED524if (info_ptr->unknown_chunks != 0 &&525((mask & PNG_FREE_UNKN) & info_ptr->free_me) != 0)526{527if (num != -1)528{529png_free(png_ptr, info_ptr->unknown_chunks[num].data);530info_ptr->unknown_chunks[num].data = NULL;531}532533else534{535int i;536537for (i = 0; i < info_ptr->unknown_chunks_num; i++)538png_free(png_ptr, info_ptr->unknown_chunks[i].data);539540png_free(png_ptr, info_ptr->unknown_chunks);541info_ptr->unknown_chunks = NULL;542info_ptr->unknown_chunks_num = 0;543}544}545#endif546547#ifdef PNG_hIST_SUPPORTED548/* Free any hIST entry */549if (((mask & PNG_FREE_HIST) & info_ptr->free_me) != 0)550{551png_free(png_ptr, info_ptr->hist);552info_ptr->hist = NULL;553info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_hIST);554}555#endif556557/* Free any PLTE entry that was internally allocated */558if (((mask & PNG_FREE_PLTE) & info_ptr->free_me) != 0)559{560png_free(png_ptr, info_ptr->palette);561info_ptr->palette = NULL;562info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_PLTE);563info_ptr->num_palette = 0;564}565566#ifdef PNG_INFO_IMAGE_SUPPORTED567/* Free any image bits attached to the info structure */568if (((mask & PNG_FREE_ROWS) & info_ptr->free_me) != 0)569{570if (info_ptr->row_pointers != 0)571{572png_uint_32 row;573for (row = 0; row < info_ptr->height; row++)574png_free(png_ptr, info_ptr->row_pointers[row]);575576png_free(png_ptr, info_ptr->row_pointers);577info_ptr->row_pointers = NULL;578}579info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_IDAT);580}581#endif582583if (num != -1)584mask &= PNG_BIC_MASK(PNG_FREE_MUL);585586info_ptr->free_me &= ~mask;587}588#endif /* READ || WRITE */589590/* This function returns a pointer to the io_ptr associated with the user591* functions. The application should free any memory associated with this592* pointer before png_write_destroy() or png_read_destroy() are called.593*/594png_voidp PNGAPI595png_get_io_ptr(png_const_structrp png_ptr)596{597if (png_ptr == NULL)598return (NULL);599600return (png_ptr->io_ptr);601}602603#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)604# ifdef PNG_STDIO_SUPPORTED605/* Initialize the default input/output functions for the PNG file. If you606* use your own read or write routines, you can call either png_set_read_fn()607* or png_set_write_fn() instead of png_init_io(). If you have defined608* PNG_NO_STDIO or otherwise disabled PNG_STDIO_SUPPORTED, you must use a609* function of your own because "FILE *" isn't necessarily available.610*/611void PNGAPI612png_init_io(png_structrp png_ptr, png_FILE_p fp)613{614png_debug(1, "in png_init_io");615616if (png_ptr == NULL)617return;618619if (png_ptr->rw_data_fn == NULL)620{621# ifdef PNG_READ_SUPPORTED622if (png_ptr->read_struct)623png_set_read_fn(png_ptr, fp, png_default_read_data);624# ifdef PNG_WRITE_SUPPORTED625else626# endif /* WRITE */627# endif /* READ */628# ifdef PNG_WRITE_SUPPORTED629if (!png_ptr->read_struct)630# ifdef PNG_WRITE_FLUSH_SUPPORTED631png_set_write_fn(png_ptr, fp, png_default_write_data,632png_default_flush);633# else634png_set_write_fn(png_ptr, fp, png_default_write_data, NULL);635# endif636# endif /* WRITE */637}638639else640png_ptr->io_ptr = fp;641}642# endif /* STDIO */643644# ifdef PNG_TIME_RFC1123_SUPPORTED645/* Convert the supplied time into an RFC 1123 string suitable for use in646* a "Creation Time" or other text-based time string.647*/648int PNGAPI649png_convert_to_rfc1123_buffer(char out[29], png_const_timep ptime)650{651static PNG_CONST char short_months[12][4] =652{"Jan", "Feb", "Mar", "Apr", "May", "Jun",653"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};654655if (out == NULL)656return 0;657658if (ptime->year > 9999 /* RFC1123 limitation */ ||659ptime->month == 0 || ptime->month > 12 ||660ptime->day == 0 || ptime->day > 31 ||661ptime->hour > 23 || ptime->minute > 59 ||662ptime->second > 60)663return 0;664665{666size_t pos = 0;667char number_buf[5]; /* enough for a four-digit year */668669# define APPEND_STRING(string) pos = png_safecat(out, 29, pos, (string))670# define APPEND_NUMBER(format, value)\671APPEND_STRING(PNG_FORMAT_NUMBER(number_buf, format, (value)))672# define APPEND(ch) if (pos < 28) out[pos++] = (ch)673674APPEND_NUMBER(PNG_NUMBER_FORMAT_u, (unsigned)ptime->day);675APPEND(' ');676APPEND_STRING(short_months[(ptime->month - 1)]);677APPEND(' ');678APPEND_NUMBER(PNG_NUMBER_FORMAT_u, ptime->year);679APPEND(' ');680APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->hour);681APPEND(':');682APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->minute);683APPEND(':');684APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->second);685APPEND_STRING(" +0000"); /* This reliably terminates the buffer */686687# undef APPEND688# undef APPEND_NUMBER689# undef APPEND_STRING690}691692return 1;693}694# endif /* TIME_RFC1123 */695696#endif /* READ || WRITE */697698png_const_charp PNGAPI699png_get_copyright(png_const_structrp png_ptr)700{701PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */702#ifdef PNG_STRING_COPYRIGHT703return PNG_STRING_COPYRIGHT704#else705# ifdef __STDC__706return PNG_STRING_NEWLINE \707"libpng version 1.7.0beta90 - August 28, 2017" PNG_STRING_NEWLINE \708"Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson" \709PNG_STRING_NEWLINE \710"Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \711"Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \712PNG_STRING_NEWLINE;713# else714return "libpng version 1.7.0beta90 - August 28, 2017\715Copyright (c) 1998-2002,2004,2006-2017 Glenn Randers-Pehrson\716Copyright (c) 1996-1997 Andreas Dilger\717Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.";718# endif719#endif720}721722/* The following return the library version as a short string in the723* format 1.0.0 through 99.99.99zz. To get the version of *.h files724* used with your application, print out PNG_LIBPNG_VER_STRING, which725* is defined in png.h.726* Note: now there is no difference between png_get_libpng_ver() and727* png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,728* it is guaranteed that png.c uses the correct version of png.h.729*/730png_const_charp PNGAPI731png_get_libpng_ver(png_const_structrp png_ptr)732{733/* Version of *.c files used when building libpng */734return png_get_header_ver(png_ptr);735}736737png_const_charp PNGAPI738png_get_header_ver(png_const_structrp png_ptr)739{740/* Version of *.h files used when building libpng */741PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */742return PNG_LIBPNG_VER_STRING;743}744745png_const_charp PNGAPI746png_get_header_version(png_const_structrp png_ptr)747{748/* Returns longer string containing both version and date */749PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */750#ifdef __STDC__751# ifndef PNG_READ_SUPPORTED752return PNG_HEADER_VERSION_STRING " (NO READ SUPPORT)" PNG_STRING_NEWLINE;753# else754return PNG_HEADER_VERSION_STRING PNG_STRING_NEWLINE;755# endif756#else757return PNG_HEADER_VERSION_STRING;758#endif759}760761#ifdef PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED762/* NOTE: this routine is not used internally! */763/* Build a grayscale palette. Palette is assumed to be 1 << bit_depth764* large of png_color. This lets grayscale images be treated as765* paletted. Most useful for gamma correction and simplification766* of code. This API is not used internally.767*/768void PNGAPI769png_build_grayscale_palette(int bit_depth, png_colorp palette)770{771int num_palette;772png_byte color_inc;773int i;774png_byte v;775776png_debug(1, "in png_do_build_grayscale_palette");777778if (palette == NULL)779return;780781switch (bit_depth)782{783case 1:784num_palette = 2;785color_inc = 0xff;786break;787788case 2:789num_palette = 4;790color_inc = 0x55;791break;792793case 4:794num_palette = 16;795color_inc = 0x11;796break;797798case 8:799num_palette = 256;800color_inc = 1;801break;802803default:804num_palette = 0;805color_inc = 0;806break;807}808809for (i = 0, v = 0; i < num_palette; ++i, v = PNG_BYTE(v+color_inc))810palette[i].red = palette[i].green = palette[i].blue = v;811}812#endif813814#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED815int PNGAPI816png_handle_as_unknown(png_const_structrp png_ptr, png_const_bytep chunk_name)817{818/* Check chunk_name and return "keep" value if it's on the list, else 0 */819png_const_bytep p, p_end;820821if (png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list == 0)822return PNG_HANDLE_CHUNK_AS_DEFAULT;823824p_end = png_ptr->chunk_list;825p = p_end + png_ptr->num_chunk_list*5; /* beyond end */826827/* The code is the fifth byte after each four byte string. Historically this828* code was always searched from the end of the list, this is no longer829* necessary because the 'set' routine handles duplicate entries correcty.830*/831do /* num_chunk_list > 0, so at least one */832{833p -= 5;834835if (memcmp(chunk_name, p, 4) == 0)836return p[4];837}838while (p > p_end);839840/* This means that known chunks should be processed and unknown chunks should841* be handled according to the value of png_ptr->unknown_default; this can be842* confusing because, as a result, there are two levels of defaulting for843* unknown chunks.844*/845return PNG_HANDLE_CHUNK_AS_DEFAULT;846}847#endif /* SET_UNKNOWN_CHUNKS */848849/* This function was added to libpng-1.0.7 */850png_uint_32 PNGAPI851png_access_version_number(void)852{853/* Version of *.c files used when building libpng */854return((png_uint_32)PNG_LIBPNG_VER);855}856857#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)858/* Ensure that png_ptr->zstream.msg holds some appropriate error message string.859* If it doesn't 'ret' is used to set it to something appropriate, even in cases860* like Z_OK or Z_STREAM_END where the error code is apparently a success code.861*/862void /* PRIVATE */863png_zstream_error(z_stream *zstream, int ret)864{865/* Translate 'ret' into an appropriate error string, priority is given to the866* one in zstream if set. This always returns a string, even in cases like867* Z_OK or Z_STREAM_END where the error code is a success code.868*/869if (zstream->msg == NULL) switch (ret)870{871default:872case Z_OK:873zstream->msg = PNGZ_MSG_CAST("unexpected zlib return code");874break;875876case Z_STREAM_END:877/* Normal exit */878zstream->msg = PNGZ_MSG_CAST("unexpected end of LZ stream");879break;880881case Z_NEED_DICT:882/* This means the deflate stream did not have a dictionary; this883* indicates a bogus PNG.884*/885zstream->msg = PNGZ_MSG_CAST("missing LZ dictionary");886break;887888case Z_ERRNO:889/* gz APIs only: should not happen */890zstream->msg = PNGZ_MSG_CAST("zlib IO error");891break;892893case Z_STREAM_ERROR:894/* internal libpng error */895zstream->msg = PNGZ_MSG_CAST("bad parameters to zlib");896break;897898case Z_DATA_ERROR:899zstream->msg = PNGZ_MSG_CAST("damaged LZ stream");900break;901902case Z_MEM_ERROR:903zstream->msg = PNGZ_MSG_CAST("insufficient memory");904break;905906case Z_BUF_ERROR:907/* End of input or output; not a problem if the caller is doing908* incremental read or write.909*/910zstream->msg = PNGZ_MSG_CAST("truncated");911break;912913case Z_VERSION_ERROR:914zstream->msg = PNGZ_MSG_CAST("unsupported zlib version");915break;916917case PNG_UNEXPECTED_ZLIB_RETURN:918/* Compile errors here mean that zlib now uses the value co-opted in919* pngpriv.h for PNG_UNEXPECTED_ZLIB_RETURN; update the switch above920* and change pngpriv.h. Note that this message is "... return",921* whereas the default/Z_OK one is "... return code".922*/923zstream->msg = PNGZ_MSG_CAST("unexpected zlib return");924break;925}926}927928/* png_convert_size: a PNGAPI but no longer in png.h, so deleted929* at libpng 1.5.5!930*/931932/* Added at libpng version 1.2.34 and 1.4.0 (moved from pngset.c) */933#ifdef PNG_GAMMA_SUPPORTED /* always set if COLORSPACE */934static int935png_colorspace_check_gamma(png_const_structrp png_ptr,936png_colorspacerp colorspace, png_fixed_point gAMA, int from)937/* This is called to check a new gamma value against an existing one. The938* routine returns false if the new gamma value should not be written.939*940* 'from' says where the new gamma value comes from:941*942* 0: the new gamma value is the libpng estimate for an ICC profile943* 1: the new gamma value comes from a gAMA chunk944* 2: the new gamma value comes from an sRGB chunk945*946* API CHANGE: libpng 1.7.0: prior to 1.7 the check below used the build-time947* constant PNG_GAMMA_THRESHOLD_FIXED and the results would therefore depend948* on a parameter that was intended for tuning the READ_GAMMA support. In949* 1.7 a fixed value of +/-1% is used instead; this reflects the fact that950* gamma values are rarely quoted to more than 2 decimal digits of precision.951*/952{953png_fixed_point gtest;954955if ((colorspace->flags & PNG_COLORSPACE_HAVE_GAMMA) != 0 &&956(png_muldiv(>est, colorspace->gamma, PNG_FP_1, gAMA) == 0 ||957gtest < PNG_FP_1 - 1000 || gtest > PNG_FP_1 + 1000))958{959/* Either this is an sRGB image, in which case the calculated gamma960* approximation should match, or this is an image with a profile and the961* value libpng calculates for the gamma of the profile does not match the962* value recorded in the file. The former, sRGB, case is an error, the963* latter is just a warning.964*/965if ((colorspace->flags & PNG_COLORSPACE_FROM_sRGB) != 0 || from == 2)966{967png_chunk_report(png_ptr, "gamma value does not match sRGB",968PNG_CHUNK_ERROR);969/* Do not overwrite an sRGB value */970return from == 2;971}972973else /* sRGB tag not involved */974{975png_chunk_report(png_ptr, "gamma value does not match libpng estimate",976PNG_CHUNK_WARNING);977return from == 1;978}979}980981return 1;982}983984void /* PRIVATE */985png_colorspace_set_gamma(png_const_structrp png_ptr,986png_colorspacerp colorspace, png_fixed_point gAMA)987{988/* Changed in libpng-1.5.4 to limit the values to ensure overflow can't989* occur. Since the fixed point representation is asymmetrical it is990* possible for 1/gamma to overflow the limit of 21474 and this means the991* gamma value must be at least 5/100000 and hence at most 20000.0. For992* safety the limits here are a little narrower. The values are 0.00016 to993* 6250.0, which are truly ridiculous gamma values (and will produce994* displays that are all black or all white.)995*996* In 1.6.0 this test replaces the ones in pngrutil.c, in the gAMA chunk997* handling code, which only required the value to be >0.998*/999# if (defined PNG_TRANSFORM_MECH_SUPPORTED) &&\1000(defined PNG_ERROR_TEXT_SUPPORTED)1001# define ERRMSG 11002# else1003# define ERRMSG 01004# endif10051006# if ERRMSG1007png_const_charp errmsg;1008# endif10091010if (gAMA < 16 || gAMA > 625000000)1011{1012# if ERRMSG1013errmsg = "gamma value out of range";1014# endif1015}10161017# ifdef PNG_READ_gAMA_SUPPORTED1018/* Allow the application to set the gamma value more than once */1019else if (png_ptr->read_struct &&1020(colorspace->flags & PNG_COLORSPACE_FROM_gAMA) != 0)1021{1022# if ERRMSG1023errmsg = "duplicate";1024# endif1025}1026# endif10271028/* Do nothing if the colorspace is already invalid */1029else if ((colorspace->flags & PNG_COLORSPACE_INVALID) != 0)1030return;10311032else1033{1034if (png_colorspace_check_gamma(png_ptr, colorspace, gAMA,10351/*from gAMA*/) != 0)1036{1037/* Store this gamma value. */1038colorspace->gamma = gAMA;1039colorspace->flags |=1040(PNG_COLORSPACE_HAVE_GAMMA | PNG_COLORSPACE_FROM_gAMA);1041}10421043/* At present if the check_gamma test fails the gamma of the colorspace is1044* not updated however the colorspace is not invalidated. This1045* corresponds to the case where the existing gamma comes from an sRGB1046* chunk or profile. An error message has already been output.1047*/1048return;1049}10501051/* Error exit - errmsg has been set. */1052# undef ERRMSG1053colorspace->flags |= PNG_COLORSPACE_INVALID;1054png_chunk_report(png_ptr, errmsg, PNG_CHUNK_WRITE_ERROR);1055}10561057void /* PRIVATE */1058png_colorspace_sync_info(png_const_structrp png_ptr, png_inforp info_ptr)1059{1060if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0)1061{1062/* Everything is invalid */1063info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_gAMA|PNG_INFO_cHRM|PNG_INFO_sRGB|1064PNG_INFO_iCCP);10651066# ifdef PNG_COLORSPACE_SUPPORTED1067/* Clean up the iCCP profile now if it won't be used. */1068png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, -1/*not used*/);1069# else1070PNG_UNUSED(png_ptr)1071# endif1072}10731074else1075{1076# ifdef PNG_COLORSPACE_SUPPORTED1077/* Leave the INFO_iCCP flag set if the pngset.c code has already set1078* it; this allows a PNG to contain a profile which matches sRGB and1079* yet still have that profile retrievable by the application.1080*/1081if ((info_ptr->colorspace.flags & PNG_COLORSPACE_MATCHES_sRGB) != 0)1082info_ptr->valid |= PNG_INFO_sRGB;10831084else1085info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_sRGB);10861087if ((info_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0)1088info_ptr->valid |= PNG_INFO_cHRM;10891090else1091info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_cHRM);1092# endif10931094if ((info_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_GAMMA) != 0)1095info_ptr->valid |= PNG_INFO_gAMA;10961097else1098info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_gAMA);1099}1100}11011102#ifdef PNG_READ_SUPPORTED1103void /* PRIVATE */1104png_colorspace_sync(png_const_structrp png_ptr, png_inforp info_ptr)1105{1106if (info_ptr == NULL) /* reduce code size; check here not in the caller */1107return;11081109info_ptr->colorspace = png_ptr->colorspace;1110png_colorspace_sync_info(png_ptr, info_ptr);1111}1112#endif1113#endif11141115#ifdef PNG_COLORSPACE_SUPPORTED1116/* Calculate a reciprocal, return 0 on div-by-zero or overflow. */1117static png_fixed_point1118png_reciprocal(png_fixed_point a)1119{1120#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED1121double r = floor(1E10/a+.5);11221123if (r <= 2147483647. && r >= -2147483648.)1124return (png_fixed_point)r;1125#else1126png_fixed_point res;11271128if (png_muldiv(&res, PNG_FP_1, PNG_FP_1, a) != 0)1129return res;1130#endif11311132return 0; /* error/overflow */1133}11341135/* Added at libpng-1.5.5 to support read and write of true CIEXYZ values for1136* cHRM, as opposed to using chromaticities. These internal APIs return1137* non-zero on a parameter error. The X, Y and Z values are required to be1138* positive and less than 1.0.1139*/1140static int1141png_xy_from_XYZ(png_xy *xy, const png_XYZ *XYZ)1142{1143png_int_32 d, dwhite, whiteX, whiteY;11441145d = XYZ->red_X + XYZ->red_Y + XYZ->red_Z;1146if (png_muldiv(&xy->redx, XYZ->red_X, PNG_FP_1, d) == 0)1147return 1;1148if (png_muldiv(&xy->redy, XYZ->red_Y, PNG_FP_1, d) == 0)1149return 1;1150dwhite = d;1151whiteX = XYZ->red_X;1152whiteY = XYZ->red_Y;11531154d = XYZ->green_X + XYZ->green_Y + XYZ->green_Z;1155if (png_muldiv(&xy->greenx, XYZ->green_X, PNG_FP_1, d) == 0)1156return 1;1157if (png_muldiv(&xy->greeny, XYZ->green_Y, PNG_FP_1, d) == 0)1158return 1;1159dwhite += d;1160whiteX += XYZ->green_X;1161whiteY += XYZ->green_Y;11621163d = XYZ->blue_X + XYZ->blue_Y + XYZ->blue_Z;1164if (png_muldiv(&xy->bluex, XYZ->blue_X, PNG_FP_1, d) == 0)1165return 1;1166if (png_muldiv(&xy->bluey, XYZ->blue_Y, PNG_FP_1, d) == 0)1167return 1;1168dwhite += d;1169whiteX += XYZ->blue_X;1170whiteY += XYZ->blue_Y;11711172/* The reference white is simply the sum of the end-point (X,Y,Z) vectors,1173* thus:1174*/1175if (png_muldiv(&xy->whitex, whiteX, PNG_FP_1, dwhite) == 0)1176return 1;1177if (png_muldiv(&xy->whitey, whiteY, PNG_FP_1, dwhite) == 0)1178return 1;11791180return 0;1181}11821183static int1184png_XYZ_from_xy(png_XYZ *XYZ, const png_xy *xy)1185{1186png_fixed_point red_inverse, green_inverse, blue_scale;1187png_fixed_point left, right, denominator;11881189/* Check xy and, implicitly, z. Note that wide gamut color spaces typically1190* have end points with 0 tristimulus values (these are impossible end1191* points, but they are used to cover the possible colors). We check1192* xy->whitey against 5, not 0, to avoid a possible integer overflow.1193*/1194if (xy->redx < 0 || xy->redx > PNG_FP_1) return 1;1195if (xy->redy < 0 || xy->redy > PNG_FP_1-xy->redx) return 1;1196if (xy->greenx < 0 || xy->greenx > PNG_FP_1) return 1;1197if (xy->greeny < 0 || xy->greeny > PNG_FP_1-xy->greenx) return 1;1198if (xy->bluex < 0 || xy->bluex > PNG_FP_1) return 1;1199if (xy->bluey < 0 || xy->bluey > PNG_FP_1-xy->bluex) return 1;1200if (xy->whitex < 0 || xy->whitex > PNG_FP_1) return 1;1201if (xy->whitey < 5 || xy->whitey > PNG_FP_1-xy->whitex) return 1;12021203/* The reverse calculation is more difficult because the original tristimulus1204* value had 9 independent values (red,green,blue)x(X,Y,Z) however only 81205* derived values were recorded in the cHRM chunk;1206* (red,green,blue,white)x(x,y). This loses one degree of freedom and1207* therefore an arbitrary ninth value has to be introduced to undo the1208* original transformations.1209*1210* Think of the original end-points as points in (X,Y,Z) space. The1211* chromaticity values (c) have the property:1212*1213* C1214* c = ---------1215* X + Y + Z1216*1217* For each c (x,y,z) from the corresponding original C (X,Y,Z). Thus the1218* three chromaticity values (x,y,z) for each end-point obey the1219* relationship:1220*1221* x + y + z = 11222*1223* This describes the plane in (X,Y,Z) space that intersects each axis at the1224* value 1.0; call this the chromaticity plane. Thus the chromaticity1225* calculation has scaled each end-point so that it is on the x+y+z=1 plane1226* and chromaticity is the intersection of the vector from the origin to the1227* (X,Y,Z) value with the chromaticity plane.1228*1229* To fully invert the chromaticity calculation we would need the three1230* end-point scale factors, (red-scale, green-scale, blue-scale), but these1231* were not recorded. Instead we calculated the reference white (X,Y,Z) and1232* recorded the chromaticity of this. The reference white (X,Y,Z) would have1233* given all three of the scale factors since:1234*1235* color-C = color-c * color-scale1236* white-C = red-C + green-C + blue-C1237* = red-c*red-scale + green-c*green-scale + blue-c*blue-scale1238*1239* But cHRM records only white-x and white-y, so we have lost the white scale1240* factor:1241*1242* white-C = white-c*white-scale1243*1244* To handle this the inverse transformation makes an arbitrary assumption1245* about white-scale:1246*1247* Assume: white-Y = 1.01248* Hence: white-scale = 1/white-y1249* Or: red-Y + green-Y + blue-Y = 1.01250*1251* Notice the last statement of the assumption gives an equation in three of1252* the nine values we want to calculate. 8 more equations come from the1253* above routine as summarised at the top above (the chromaticity1254* calculation):1255*1256* Given: color-x = color-X / (color-X + color-Y + color-Z)1257* Hence: (color-x - 1)*color-X + color.x*color-Y + color.x*color-Z = 01258*1259* This is 9 simultaneous equations in the 9 variables "color-C" and can be1260* solved by Cramer's rule. Cramer's rule requires calculating 10 9x9 matrix1261* determinants, however this is not as bad as it seems because only 28 of1262* the total of 90 terms in the various matrices are non-zero. Nevertheless1263* Cramer's rule is notoriously numerically unstable because the determinant1264* calculation involves the difference of large, but similar, numbers. It is1265* difficult to be sure that the calculation is stable for real world values1266* and it is certain that it becomes unstable where the end points are close1267* together.1268*1269* So this code uses the perhaps slightly less optimal but more1270* understandable and totally obvious approach of calculating color-scale.1271*1272* This algorithm depends on the precision in white-scale and that is1273* (1/white-y), so we can immediately see that as white-y approaches 0 the1274* accuracy inherent in the cHRM chunk drops off substantially.1275*1276* libpng arithmetic: a simple inversion of the above equations1277* ------------------------------------------------------------1278*1279* white_scale = 1/white-y1280* white-X = white-x * white-scale1281* white-Y = 1.01282* white-Z = (1 - white-x - white-y) * white_scale1283*1284* white-C = red-C + green-C + blue-C1285* = red-c*red-scale + green-c*green-scale + blue-c*blue-scale1286*1287* This gives us three equations in (red-scale,green-scale,blue-scale) where1288* all the coefficients are now known:1289*1290* red-x*red-scale + green-x*green-scale + blue-x*blue-scale1291* = white-x/white-y1292* red-y*red-scale + green-y*green-scale + blue-y*blue-scale = 11293* red-z*red-scale + green-z*green-scale + blue-z*blue-scale1294* = (1 - white-x - white-y)/white-y1295*1296* In the last equation color-z is (1 - color-x - color-y) so we can add all1297* three equations together to get an alternative third:1298*1299* red-scale + green-scale + blue-scale = 1/white-y = white-scale1300*1301* So now we have a Cramer's rule solution where the determinants are just1302* 3x3 - far more tractible. Unfortunately 3x3 determinants still involve1303* multiplication of three coefficients so we can't guarantee to avoid1304* overflow in the libpng fixed point representation. Using Cramer's rule in1305* floating point is probably a good choice here, but it's not an option for1306* fixed point. Instead proceed to simplify the first two equations by1307* eliminating what is likely to be the largest value, blue-scale:1308*1309* blue-scale = white-scale - red-scale - green-scale1310*1311* Hence:1312*1313* (red-x - blue-x)*red-scale + (green-x - blue-x)*green-scale =1314* (white-x - blue-x)*white-scale1315*1316* (red-y - blue-y)*red-scale + (green-y - blue-y)*green-scale =1317* 1 - blue-y*white-scale1318*1319* And now we can trivially solve for (red-scale,green-scale):1320*1321* green-scale =1322* (white-x - blue-x)*white-scale - (red-x - blue-x)*red-scale1323* -----------------------------------------------------------1324* green-x - blue-x1325*1326* red-scale =1327* 1 - blue-y*white-scale - (green-y - blue-y) * green-scale1328* ---------------------------------------------------------1329* red-y - blue-y1330*1331* Hence:1332*1333* red-scale =1334* ( (green-x - blue-x) * (white-y - blue-y) -1335* (green-y - blue-y) * (white-x - blue-x) ) / white-y1336* -------------------------------------------------------------------------1337* (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)1338*1339* green-scale =1340* ( (red-y - blue-y) * (white-x - blue-x) -1341* (red-x - blue-x) * (white-y - blue-y) ) / white-y1342* -------------------------------------------------------------------------1343* (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)1344*1345* Accuracy:1346* The input values have 5 decimal digits of accuracy. The values are all in1347* the range 0 < value < 1, so simple products are in the same range but may1348* need up to 10 decimal digits to preserve the original precision and avoid1349* underflow. Because we are using a 32-bit signed representation we cannot1350* match this; the best is a little over 9 decimal digits, less than 10.1351*1352* The approach used here is to preserve the maximum precision within the1353* signed representation. Because the red-scale calculation above uses the1354* difference between two products of values that must be in the range -1..+11355* it is sufficient to divide the product by 7; ceil(100,000/32767*2). The1356* factor is irrelevant in the calculation because it is applied to both1357* numerator and denominator.1358*1359* Note that the values of the differences of the products of the1360* chromaticities in the above equations tend to be small, for example for1361* the sRGB chromaticities they are:1362*1363* red numerator: -0.047511364* green numerator: -0.087881365* denominator: -0.2241 (without white-y multiplication)1366*1367* The resultant Y coefficients from the chromaticities of some widely used1368* color space definitions are (to 15 decimal places):1369*1370* sRGB1371* 0.212639005871510 0.715168678767756 0.0721923153607341372* Kodak ProPhoto1373* 0.288071128229293 0.711843217810102 0.0000856539606051374* Adobe RGB1375* 0.297344975250536 0.627363566255466 0.0752914584939981376* Adobe Wide Gamut RGB1377* 0.258728243040113 0.724682314948566 0.0165894420113211378*/1379/* By the argument, above overflow should be impossible here. The return1380* value of 2 indicates an internal error to the caller.1381*/1382if (png_muldiv(&left, xy->greenx-xy->bluex, xy->redy - xy->bluey, 7) == 0)1383return 2;1384if (png_muldiv(&right, xy->greeny-xy->bluey, xy->redx - xy->bluex, 7) == 0)1385return 2;1386denominator = left - right;13871388/* Now find the red numerator. */1389if (png_muldiv(&left, xy->greenx-xy->bluex, xy->whitey-xy->bluey, 7) == 0)1390return 2;1391if (png_muldiv(&right, xy->greeny-xy->bluey, xy->whitex-xy->bluex, 7) == 0)1392return 2;13931394/* Overflow is possible here and it indicates an extreme set of PNG cHRM1395* chunk values. This calculation actually returns the reciprocal of the1396* scale value because this allows us to delay the multiplication of white-y1397* into the denominator, which tends to produce a small number.1398*/1399if (png_muldiv(&red_inverse, xy->whitey, denominator, left-right) == 0 ||1400red_inverse <= xy->whitey /* r+g+b scales = white scale */)1401return 1;14021403/* Similarly for green_inverse: */1404if (png_muldiv(&left, xy->redy-xy->bluey, xy->whitex-xy->bluex, 7) == 0)1405return 2;1406if (png_muldiv(&right, xy->redx-xy->bluex, xy->whitey-xy->bluey, 7) == 0)1407return 2;1408if (png_muldiv(&green_inverse, xy->whitey, denominator, left-right) == 0 ||1409green_inverse <= xy->whitey)1410return 1;14111412/* And the blue scale, the checks above guarantee this can't overflow but it1413* can still produce 0 for extreme cHRM values.1414*/1415blue_scale = png_reciprocal(xy->whitey) - png_reciprocal(red_inverse) -1416png_reciprocal(green_inverse);1417if (blue_scale <= 0)1418return 1;141914201421/* And fill in the png_XYZ: */1422if (png_muldiv(&XYZ->red_X, xy->redx, PNG_FP_1, red_inverse) == 0)1423return 1;1424if (png_muldiv(&XYZ->red_Y, xy->redy, PNG_FP_1, red_inverse) == 0)1425return 1;1426if (png_muldiv(&XYZ->red_Z, PNG_FP_1 - xy->redx - xy->redy, PNG_FP_1,1427red_inverse) == 0)1428return 1;14291430if (png_muldiv(&XYZ->green_X, xy->greenx, PNG_FP_1, green_inverse) == 0)1431return 1;1432if (png_muldiv(&XYZ->green_Y, xy->greeny, PNG_FP_1, green_inverse) == 0)1433return 1;1434if (png_muldiv(&XYZ->green_Z, PNG_FP_1 - xy->greenx - xy->greeny, PNG_FP_1,1435green_inverse) == 0)1436return 1;14371438if (png_muldiv(&XYZ->blue_X, xy->bluex, blue_scale, PNG_FP_1) == 0)1439return 1;1440if (png_muldiv(&XYZ->blue_Y, xy->bluey, blue_scale, PNG_FP_1) == 0)1441return 1;1442if (png_muldiv(&XYZ->blue_Z, PNG_FP_1 - xy->bluex - xy->bluey, blue_scale,1443PNG_FP_1) == 0)1444return 1;14451446return 0; /*success*/1447}14481449static int1450png_XYZ_normalize(png_XYZ *XYZ)1451{1452png_int_32 Y;14531454if (XYZ->red_Y < 0 || XYZ->green_Y < 0 || XYZ->blue_Y < 0 ||1455XYZ->red_X < 0 || XYZ->green_X < 0 || XYZ->blue_X < 0 ||1456XYZ->red_Z < 0 || XYZ->green_Z < 0 || XYZ->blue_Z < 0)1457return 1;14581459/* Normalize by scaling so the sum of the end-point Y values is PNG_FP_1.1460* IMPLEMENTATION NOTE: ANSI requires signed overflow not to occur, therefore1461* relying on addition of two positive values producing a negative one is not1462* safe.1463*/1464Y = XYZ->red_Y;1465if (0x7fffffff - Y < XYZ->green_X)1466return 1;1467Y += XYZ->green_Y;1468if (0x7fffffff - Y < XYZ->blue_X)1469return 1;1470Y += XYZ->blue_Y;14711472if (Y != PNG_FP_1)1473{1474if (png_muldiv(&XYZ->red_X, XYZ->red_X, PNG_FP_1, Y) == 0)1475return 1;1476if (png_muldiv(&XYZ->red_Y, XYZ->red_Y, PNG_FP_1, Y) == 0)1477return 1;1478if (png_muldiv(&XYZ->red_Z, XYZ->red_Z, PNG_FP_1, Y) == 0)1479return 1;14801481if (png_muldiv(&XYZ->green_X, XYZ->green_X, PNG_FP_1, Y) == 0)1482return 1;1483if (png_muldiv(&XYZ->green_Y, XYZ->green_Y, PNG_FP_1, Y) == 0)1484return 1;1485if (png_muldiv(&XYZ->green_Z, XYZ->green_Z, PNG_FP_1, Y) == 0)1486return 1;14871488if (png_muldiv(&XYZ->blue_X, XYZ->blue_X, PNG_FP_1, Y) == 0)1489return 1;1490if (png_muldiv(&XYZ->blue_Y, XYZ->blue_Y, PNG_FP_1, Y) == 0)1491return 1;1492if (png_muldiv(&XYZ->blue_Z, XYZ->blue_Z, PNG_FP_1, Y) == 0)1493return 1;1494}14951496return 0;1497}14981499static int1500png_colorspace_endpoints_match(const png_xy *xy1, const png_xy *xy2, int delta)1501{1502/* Allow an error of +/-0.01 (absolute value) on each chromaticity */1503if (PNG_OUT_OF_RANGE(xy1->whitex, xy2->whitex,delta) ||1504PNG_OUT_OF_RANGE(xy1->whitey, xy2->whitey,delta) ||1505PNG_OUT_OF_RANGE(xy1->redx, xy2->redx, delta) ||1506PNG_OUT_OF_RANGE(xy1->redy, xy2->redy, delta) ||1507PNG_OUT_OF_RANGE(xy1->greenx, xy2->greenx,delta) ||1508PNG_OUT_OF_RANGE(xy1->greeny, xy2->greeny,delta) ||1509PNG_OUT_OF_RANGE(xy1->bluex, xy2->bluex, delta) ||1510PNG_OUT_OF_RANGE(xy1->bluey, xy2->bluey, delta))1511return 0;1512return 1;1513}15141515/* Added in libpng-1.6.0, a different check for the validity of a set of cHRM1516* chunk chromaticities. Earlier checks used to simply look for the overflow1517* condition (where the determinant of the matrix to solve for XYZ ends up zero1518* because the chromaticity values are not all distinct.) Despite this it is1519* theoretically possible to produce chromaticities that are apparently valid1520* but that rapidly degrade to invalid, potentially crashing, sets because of1521* arithmetic inaccuracies when calculations are performed on them. The new1522* check is to round-trip xy -> XYZ -> xy and then check that the result is1523* within a small percentage of the original.1524*/1525static int1526png_colorspace_check_xy(png_XYZ *XYZ, const png_xy *xy)1527{1528int result;1529png_xy xy_test;15301531/* As a side-effect this routine also returns the XYZ endpoints. */1532result = png_XYZ_from_xy(XYZ, xy);1533if (result != 0)1534return result;15351536result = png_xy_from_XYZ(&xy_test, XYZ);1537if (result != 0)1538return result;15391540if (png_colorspace_endpoints_match(xy, &xy_test,15415/*actually, the math is pretty accurate*/) != 0)1542return 0;15431544/* Too much slip */1545return 1;1546}15471548/* This is the check going the other way. The XYZ is modified to normalize it1549* (another side-effect) and the xy chromaticities are returned.1550*/1551static int1552png_colorspace_check_XYZ(png_xy *xy, png_XYZ *XYZ)1553{1554int result;1555png_XYZ XYZtemp;15561557result = png_XYZ_normalize(XYZ);1558if (result != 0)1559return result;15601561result = png_xy_from_XYZ(xy, XYZ);1562if (result != 0)1563return result;15641565XYZtemp = *XYZ;1566return png_colorspace_check_xy(&XYZtemp, xy);1567}15681569/* Used to check for an endpoint match against sRGB */1570static const png_xy sRGB_xy = /* From ITU-R BT.709-3 */1571{1572/* color x y */1573/* red */ 64000, 33000,1574/* green */ 30000, 60000,1575/* blue */ 15000, 6000,1576/* white */ 31270, 329001577};15781579static int1580png_colorspace_set_xy_and_XYZ(png_const_structrp png_ptr,1581png_colorspacerp colorspace, const png_xy *xy, const png_XYZ *XYZ,1582int preferred)1583{1584if ((colorspace->flags & PNG_COLORSPACE_INVALID) != 0)1585return 0;15861587/* The consistency check is performed on the chromaticities; this factors out1588* variations because of the normalization (or not) of the end point Y1589* values.1590*/1591if (preferred < 2 &&1592(colorspace->flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0)1593{1594/* The end points must be reasonably close to any we already have. The1595* following allows an error of up to +/-.0011596*/1597if (png_colorspace_endpoints_match(xy, &colorspace->end_points_xy,1598100) == 0)1599{1600colorspace->flags |= PNG_COLORSPACE_INVALID;1601png_benign_error(png_ptr, "inconsistent chromaticities");1602return 0; /* failed */1603}16041605/* Only overwrite with preferred values */1606if (preferred == 0)1607return 1; /* ok, but no change */1608}16091610colorspace->end_points_xy = *xy;1611colorspace->end_points_XYZ = *XYZ;1612colorspace->flags |= PNG_COLORSPACE_HAVE_ENDPOINTS;16131614/* The end points are normally quoted to two decimal digits, so allow +/-0.011615* on this test.1616*/1617if (png_colorspace_endpoints_match(xy, &sRGB_xy, 1000) != 0)1618colorspace->flags |= PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB;16191620else1621colorspace->flags &= PNG_COLORSPACE_CANCEL(1622PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB);16231624return 2; /* ok and changed */1625}16261627int /* PRIVATE */1628png_colorspace_set_chromaticities(png_const_structrp png_ptr,1629png_colorspacerp colorspace, const png_xy *xy, int preferred)1630{1631/* We must check the end points to ensure they are reasonable - in the past1632* color management systems have crashed as a result of getting bogus1633* colorant values, while this isn't the fault of libpng it is the1634* responsibility of libpng because PNG carries the bomb and libpng is in a1635* position to protect against it.1636*/1637png_XYZ XYZ;16381639switch (png_colorspace_check_xy(&XYZ, xy))1640{1641case 0: /* success */1642return png_colorspace_set_xy_and_XYZ(png_ptr, colorspace, xy, &XYZ,1643preferred);16441645case 1:1646/* We can't invert the chromaticities so we can't produce value XYZ1647* values. Likely as not a color management system will fail too.1648*/1649colorspace->flags |= PNG_COLORSPACE_INVALID;1650png_benign_error(png_ptr, "invalid chromaticities");1651break;16521653default:1654/* libpng is broken; this should be a warning but if it happens we1655* want error reports so for the moment it is an error.1656*/1657colorspace->flags |= PNG_COLORSPACE_INVALID;1658impossible("error checking chromaticities");1659break;1660}16611662return 0; /* failed */1663}16641665int /* PRIVATE */1666png_colorspace_set_endpoints(png_const_structrp png_ptr,1667png_colorspacerp colorspace, const png_XYZ *XYZ_in, int preferred)1668{1669png_XYZ XYZ = *XYZ_in;1670png_xy xy;16711672switch (png_colorspace_check_XYZ(&xy, &XYZ))1673{1674case 0:1675return png_colorspace_set_xy_and_XYZ(png_ptr, colorspace, &xy, &XYZ,1676preferred);16771678case 1:1679/* End points are invalid. */1680colorspace->flags |= PNG_COLORSPACE_INVALID;1681png_benign_error(png_ptr, "invalid end points");1682break;16831684default:1685colorspace->flags |= PNG_COLORSPACE_INVALID;1686impossible("error checking chromaticities");1687break;1688}16891690return 0; /* failed */1691}16921693#if defined(PNG_sRGB_SUPPORTED) || defined(PNG_iCCP_SUPPORTED)1694/* Error message generation */1695static char1696png_icc_tag_char(png_uint_32 byte)1697{1698byte &= 0xff;1699if (byte >= 32 && byte <= 126)1700return (char)/*SAFE*/byte;1701else1702return '?';1703}17041705static void1706png_icc_tag_name(char *name, png_uint_32 tag)1707{1708name[0] = '\'';1709name[1] = png_icc_tag_char(tag >> 24);1710name[2] = png_icc_tag_char(tag >> 16);1711name[3] = png_icc_tag_char(tag >> 8);1712name[4] = png_icc_tag_char(tag );1713name[5] = '\'';1714}17151716static int1717is_ICC_signature_char(png_alloc_size_t it)1718{1719return it == 32 || (it >= 48 && it <= 57) || (it >= 65 && it <= 90) ||1720(it >= 97 && it <= 122);1721}17221723static int1724is_ICC_signature(png_alloc_size_t it)1725{1726return is_ICC_signature_char(it >> 24) /* checks all the top bits */ &&1727is_ICC_signature_char((it >> 16) & 0xff) &&1728is_ICC_signature_char((it >> 8) & 0xff) &&1729is_ICC_signature_char(it & 0xff);1730}17311732static int1733png_icc_profile_error(png_const_structrp png_ptr, png_colorspacerp colorspace,1734png_const_charp name, png_alloc_size_t value, png_const_charp reason)1735{1736size_t pos;1737char message[196]; /* see below for calculation */17381739if (colorspace != NULL)1740colorspace->flags |= PNG_COLORSPACE_INVALID;17411742pos = png_safecat(message, (sizeof message), 0, "profile '"); /* 9 chars */1743pos = png_safecat(message, pos+79, pos, name); /* Truncate to 79 chars */1744pos = png_safecat(message, (sizeof message), pos, "': "); /* +2 = 90 */1745if (is_ICC_signature(value) != 0)1746{1747/* So 'value' is at most 4 bytes and the following cast is safe */1748png_icc_tag_name(message+pos, (png_uint_32)value);1749pos += 6; /* total +8; less than the else clause */1750message[pos++] = ':';1751message[pos++] = ' ';1752}1753# ifdef PNG_WARNINGS_SUPPORTED1754else1755{1756char number[PNG_NUMBER_BUFFER_SIZE]; /* +24 = 114*/17571758pos = png_safecat(message, (sizeof message), pos,1759png_format_number(number, number+(sizeof number),1760PNG_NUMBER_FORMAT_x, value));1761pos = png_safecat(message, (sizeof message), pos, "h: "); /*+2 = 116*/1762}1763# endif1764/* The 'reason' is an arbitrary message, allow +79 maximum 195 */1765pos = png_safecat(message, (sizeof message), pos, reason);1766PNG_UNUSED(pos)17671768/* This is recoverable, but make it unconditionally an app_error on write to1769* avoid writing invalid ICC profiles into PNG files (i.e., we handle them1770* on read, with a warning, but on write unless the app turns off1771* application errors the PNG won't be written.)1772*/1773png_chunk_report(png_ptr, message,1774(colorspace != NULL) ? PNG_CHUNK_ERROR : PNG_CHUNK_WRITE_ERROR);17751776return 0;1777}1778#endif /* sRGB || iCCP */17791780#ifdef PNG_sRGB_SUPPORTED1781int /* PRIVATE */1782png_colorspace_set_sRGB(png_const_structrp png_ptr, png_colorspacerp colorspace,1783int intent)1784{1785/* sRGB sets known gamma, end points and (from the chunk) intent. */1786/* IMPORTANT: these are not necessarily the values found in an ICC profile1787* because ICC profiles store values adapted to a D50 environment; it is1788* expected that the ICC profile mediaWhitePointTag will be D50; see the1789* checks and code elsewhere to understand this better.1790*1791* These XYZ values, which are accurate to 5dp, produce rgb to gray1792* coefficients of (6968,23435,2366), which are reduced (because they add up1793* to 32769 not 32768) to (6968,23434,2366). These are the values that1794* libpng has traditionally used (and are the best values given the 15bit1795* algorithm used by the rgb to gray code.)1796*/1797static const png_XYZ sRGB_XYZ = /* D65 XYZ (*not* the D50 adapted values!) */1798{1799/* color X Y Z */1800/* red */ 41239, 21264, 1933,1801/* green */ 35758, 71517, 11919,1802/* blue */ 18048, 7219, 950531803};18041805/* Do nothing if the colorspace is already invalidated. */1806if ((colorspace->flags & PNG_COLORSPACE_INVALID) != 0)1807return 0;18081809/* Check the intent, then check for existing settings. It is valid for the1810* PNG file to have cHRM or gAMA chunks along with sRGB, but the values must1811* be consistent with the correct values. If, however, this function is1812* called below because an iCCP chunk matches sRGB then it is quite1813* conceivable that an older app recorded incorrect gAMA and cHRM because of1814* an incorrect calculation based on the values in the profile - this does1815* *not* invalidate the profile (though it still produces an error, which can1816* be ignored.)1817*/1818if (intent < 0 || intent >= PNG_sRGB_INTENT_LAST)1819return png_icc_profile_error(png_ptr, colorspace, "sRGB",1820(unsigned)intent, "invalid sRGB rendering intent");18211822if ((colorspace->flags & PNG_COLORSPACE_HAVE_INTENT) != 0 &&1823colorspace->rendering_intent != intent)1824return png_icc_profile_error(png_ptr, colorspace, "sRGB",1825(unsigned)intent, "inconsistent rendering intents");18261827if ((colorspace->flags & PNG_COLORSPACE_FROM_sRGB) != 0)1828{1829png_benign_error(png_ptr, "duplicate sRGB information ignored");1830return 0;1831}18321833/* If the standard sRGB cHRM chunk does not match the one from the PNG file1834* warn but overwrite the value with the correct one.1835*/1836if ((colorspace->flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0 &&1837!png_colorspace_endpoints_match(&sRGB_xy, &colorspace->end_points_xy,1838100))1839png_chunk_report(png_ptr, "cHRM chunk does not match sRGB",1840PNG_CHUNK_ERROR);18411842/* This check is just done for the error reporting - the routine always1843* returns true when the 'from' argument corresponds to sRGB (2).1844*/1845(void)png_colorspace_check_gamma(png_ptr, colorspace, PNG_GAMMA_sRGB_INVERSE,18462/*from sRGB*/);18471848/* intent: bugs in GCC force 'int' to be used as the parameter type. */1849colorspace->rendering_intent = png_check_u16(png_ptr, intent);1850colorspace->flags |= PNG_COLORSPACE_HAVE_INTENT;18511852/* endpoints */1853colorspace->end_points_xy = sRGB_xy;1854colorspace->end_points_XYZ = sRGB_XYZ;1855colorspace->flags |=1856(PNG_COLORSPACE_HAVE_ENDPOINTS|PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB);18571858/* gamma */1859colorspace->gamma = PNG_GAMMA_sRGB_INVERSE;1860colorspace->flags |= PNG_COLORSPACE_HAVE_GAMMA;18611862/* Finally record that we have an sRGB profile */1863colorspace->flags |=1864(PNG_COLORSPACE_MATCHES_sRGB|PNG_COLORSPACE_FROM_sRGB);18651866return 1; /* set */1867}1868#endif /* sRGB */18691870#ifdef PNG_iCCP_SUPPORTED1871/* Encoded value of D50 as an ICC XYZNumber. From the ICC 2010 spec the value1872* is XYZ(0.9642,1.0,0.8249), which scales to:1873*1874* (63189.8112, 65536, 54060.6464)1875*/1876static const png_byte D50_nCIEXYZ[12] =1877{ 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d };18781879int /* PRIVATE */1880png_icc_check_length(png_const_structrp png_ptr, png_colorspacerp colorspace,1881png_const_charp name, png_uint_32 profile_length)1882{1883if (profile_length < 132)1884return png_icc_profile_error(png_ptr, colorspace, name, profile_length,1885"too short");18861887if (profile_length & 3)1888return png_icc_profile_error(png_ptr, colorspace, name, profile_length,1889"invalid length");18901891return 1;1892}18931894int /* PRIVATE */1895png_icc_check_header(png_const_structrp png_ptr, png_colorspacerp colorspace,1896png_const_charp name, png_uint_32 profile_length,1897png_const_bytep profile/* first 132 bytes only */, int is_color)1898{1899png_uint_32 temp;19001901/* Length check; this cannot be ignored in this code because profile_length1902* is used later to check the tag table, so even if the profile seems over1903* long profile_length from the caller must be correct. The caller can fix1904* this up on read or write by just passing in the profile header length.1905*/1906temp = png_get_uint_32(profile);1907if (temp != profile_length)1908return png_icc_profile_error(png_ptr, colorspace, name, temp,1909"length does not match profile");19101911temp = png_get_uint_32(profile+128); /* tag count: 12 bytes/tag */1912if (temp > 357913930 || /* (2^32-4-132)/12: maximum possible tag count */1913profile_length < 132+12*temp) /* truncated tag table */1914return png_icc_profile_error(png_ptr, colorspace, name, temp,1915"tag count too large");19161917/* The 'intent' must be valid or we can't store it, ICC limits the intent to1918* 16 bits.1919*/1920temp = png_get_uint_32(profile+64);1921if (temp >= 0xffff) /* The ICC limit */1922return png_icc_profile_error(png_ptr, colorspace, name, temp,1923"invalid rendering intent");19241925/* This is just a warning because the profile may be valid in future1926* versions.1927*/1928if (temp >= PNG_sRGB_INTENT_LAST)1929(void)png_icc_profile_error(png_ptr, NULL, name, temp,1930"intent outside defined range");19311932/* At this point the tag table can't be checked because it hasn't necessarily1933* been loaded; however, various header fields can be checked. These checks1934* are for values permitted by the PNG spec in an ICC profile; the PNG spec1935* restricts the profiles that can be passed in an iCCP chunk (they must be1936* appropriate to processing PNG data!)1937*/19381939/* Data checks (could be skipped). These checks must be independent of the1940* version number; however, the version number doesn't accomodate changes in1941* the header fields (just the known tags and the interpretation of the1942* data.)1943*/1944temp = png_get_uint_32(profile+36); /* signature 'ascp' */1945if (temp != 0x61637370)1946return png_icc_profile_error(png_ptr, colorspace, name, temp,1947"invalid signature");19481949/* Currently the PCS illuminant/adopted white point (the computational1950* white point) are required to be D50,1951* however the profile contains a record of the illuminant so perhaps ICC1952* expects to be able to change this in the future (despite the rationale in1953* the introduction for using a fixed PCS adopted white.) Consequently the1954* following is just a warning.1955*/1956if (memcmp(profile+68, D50_nCIEXYZ, 12) != 0)1957(void)png_icc_profile_error(png_ptr, NULL, name, 0/*no tag value*/,1958"PCS illuminant is not D50");19591960/* The PNG spec requires this:1961* "If the iCCP chunk is present, the image samples conform to the colour1962* space represented by the embedded ICC profile as defined by the1963* International Color Consortium [ICC]. The colour space of the ICC profile1964* shall be an RGB colour space for colour images (PNG colour types 2, 3, and1965* 6), or a greyscale colour space for greyscale images (PNG colour types 01966* and 4)."1967*1968* This checking code ensures the embedded profile (on either read or write)1969* conforms to the specification requirements. Notice that an ICC 'gray'1970* color-space profile contains the information to transform the monochrome1971* data to XYZ or L*a*b (according to which PCS the profile uses) and this1972* should be used in preference to the standard libpng K channel replication1973* into R, G and B channels.1974*1975* Previously it was suggested that an RGB profile on grayscale data could be1976* handled. However it it is clear that using an RGB profile in this context1977* must be an error - there is no specification of what it means. Thus it is1978* almost certainly more correct to ignore the profile.1979*/1980temp = png_get_uint_32(profile+16); /* data colour space field */1981switch (temp)1982{1983case 0x52474220: /* 'RGB ' */1984if (!is_color)1985return png_icc_profile_error(png_ptr, colorspace, name, temp,1986"RGB color space not permitted on grayscale PNG");1987break;19881989case 0x47524159: /* 'GRAY' */1990if (is_color)1991return png_icc_profile_error(png_ptr, colorspace, name, temp,1992"Gray color space not permitted on RGB PNG");1993break;19941995default:1996return png_icc_profile_error(png_ptr, colorspace, name, temp,1997"invalid ICC profile color space");1998}19992000/* It is up to the application to check that the profile class matches the2001* application requirements; the spec provides no guidance, but it's pretty2002* weird if the profile is not scanner ('scnr'), monitor ('mntr'), printer2003* ('prtr') or 'spac' (for generic color spaces). Issue a warning in these2004* cases. Issue an error for device link or abstract profiles - these don't2005* contain the records necessary to transform the color-space to anything2006* other than the target device (and not even that for an abstract profile).2007* Profiles of these classes may not be embedded in images.2008*/2009temp = png_get_uint_32(profile+12); /* profile/device class */2010switch (temp)2011{2012case 0x73636E72: /* 'scnr' */2013case 0x6D6E7472: /* 'mntr' */2014case 0x70727472: /* 'prtr' */2015case 0x73706163: /* 'spac' */2016/* All supported */2017break;20182019case 0x61627374: /* 'abst' */2020/* May not be embedded in an image */2021return png_icc_profile_error(png_ptr, colorspace, name, temp,2022"invalid embedded Abstract ICC profile");20232024case 0x6C696E6B: /* 'link' */2025/* DeviceLink profiles cannot be interpreted in a non-device specific2026* fashion, if an app uses the AToB0Tag in the profile the results are2027* undefined unless the result is sent to the intended device,2028* therefore a DeviceLink profile should not be found embedded in a2029* PNG.2030*/2031return png_icc_profile_error(png_ptr, colorspace, name, temp,2032"unexpected DeviceLink ICC profile class");20332034case 0x6E6D636C: /* 'nmcl' */2035/* A NamedColor profile is also device specific, however it doesn't2036* contain an AToB0 tag that is open to misinterpretation. Almost2037* certainly it will fail the tests below.2038*/2039(void)png_icc_profile_error(png_ptr, NULL, name, temp,2040"unexpected NamedColor ICC profile class");2041break;20422043default:2044/* To allow for future enhancements to the profile accept unrecognized2045* profile classes with a warning, these then hit the test below on the2046* tag content to ensure they are backward compatible with one of the2047* understood profiles.2048*/2049(void)png_icc_profile_error(png_ptr, NULL, name, temp,2050"unrecognized ICC profile class");2051break;2052}20532054/* For any profile other than a device link one the PCS must be encoded2055* either in XYZ or Lab.2056*/2057temp = png_get_uint_32(profile+20);2058switch (temp)2059{2060case 0x58595A20: /* 'XYZ ' */2061case 0x4C616220: /* 'Lab ' */2062break;20632064default:2065return png_icc_profile_error(png_ptr, colorspace, name, temp,2066"unexpected ICC PCS encoding");2067}20682069return 1;2070}20712072int /* PRIVATE */2073png_icc_check_tag_table(png_const_structrp png_ptr, png_colorspacerp colorspace,2074png_const_charp name, png_uint_32 profile_length,2075png_const_bytep profile /* header plus whole tag table */)2076{2077png_uint_32 tag_count = png_get_uint_32(profile+128);2078png_uint_32 itag;2079png_const_bytep tag = profile+132; /* The first tag */20802081/* First scan all the tags in the table and add bits to the icc_info value2082* (temporarily in 'tags').2083*/2084for (itag=0; itag < tag_count; ++itag, tag += 12)2085{2086png_uint_32 tag_id = png_get_uint_32(tag+0);2087png_uint_32 tag_start = png_get_uint_32(tag+4); /* must be aligned */2088png_uint_32 tag_length = png_get_uint_32(tag+8);/* not padded */20892090/* The ICC specification does not exclude zero length tags, therefore the2091* start might actually be anywhere if there is no data, but this would be2092* a clear abuse of the intent of the standard so the start is checked for2093* being in range. All defined tag types have an 8 byte header - a 4 byte2094* type signature then 0.2095*/2096if ((tag_start & 3) != 0)2097{2098/* CNHP730S.icc shipped with Microsoft Windows 64 violates this, it is2099* only a warning here because libpng does not care about the2100* alignment.2101*/2102(void)png_icc_profile_error(png_ptr, NULL, name, tag_id,2103"ICC profile tag start not a multiple of 4");2104}21052106/* This is a hard error; potentially it can cause read outside the2107* profile.2108*/2109if (tag_start > profile_length || tag_length > profile_length - tag_start)2110return png_icc_profile_error(png_ptr, colorspace, name, tag_id,2111"ICC profile tag outside profile");2112}21132114return 1; /* success, maybe with warnings */2115}21162117#ifdef PNG_sRGB_SUPPORTED2118#if PNG_sRGB_PROFILE_CHECKS >= 02119/* Information about the known ICC sRGB profiles */2120static const struct2121{2122png_uint_32 adler, crc, length;2123png_uint_32 md5[4];2124png_byte have_md5;2125png_byte is_broken;2126png_uint_16 intent;21272128# define PNG_MD5(a,b,c,d) { a, b, c, d }, (a!=0)||(b!=0)||(c!=0)||(d!=0)2129# define PNG_ICC_CHECKSUM(adler, crc, md5, intent, broke, date, length, fname)\2130{ adler, crc, length, md5, broke, intent },21312132} png_sRGB_checks[] =2133{2134/* This data comes from contrib/tools/checksum-icc run on downloads of2135* all four ICC sRGB profiles from www.color.org.2136*/2137/* adler32, crc32, MD5[4], intent, date, length, file-name */2138PNG_ICC_CHECKSUM(0x0a3fd9f6, 0x3b8772b9,2139PNG_MD5(0x29f83dde, 0xaff255ae, 0x7842fae4, 0xca83390d), 0, 0,2140"2009/03/27 21:36:31", 3048, "sRGB_IEC61966-2-1_black_scaled.icc")21412142/* ICC sRGB v2 perceptual no black-compensation: */2143PNG_ICC_CHECKSUM(0x4909e5e1, 0x427ebb21,2144PNG_MD5(0xc95bd637, 0xe95d8a3b, 0x0df38f99, 0xc1320389), 1, 0,2145"2009/03/27 21:37:45", 3052, "sRGB_IEC61966-2-1_no_black_scaling.icc")21462147PNG_ICC_CHECKSUM(0xfd2144a1, 0x306fd8ae,2148PNG_MD5(0xfc663378, 0x37e2886b, 0xfd72e983, 0x8228f1b8), 0, 0,2149"2009/08/10 17:28:01", 60988, "sRGB_v4_ICC_preference_displayclass.icc")21502151/* ICC sRGB v4 perceptual */2152PNG_ICC_CHECKSUM(0x209c35d2, 0xbbef7812,2153PNG_MD5(0x34562abf, 0x994ccd06, 0x6d2c5721, 0xd0d68c5d), 0, 0,2154"2007/07/25 00:05:37", 60960, "sRGB_v4_ICC_preference.icc")21552156/* The following profiles have no known MD5 checksum. If there is a match2157* on the (empty) MD5 the other fields are used to attempt a match and2158* a warning is produced. The first two of these profiles have a 'cprt' tag2159* which suggests that they were also made by Hewlett Packard.2160*/2161PNG_ICC_CHECKSUM(0xa054d762, 0x5d5129ce,2162PNG_MD5(0x00000000, 0x00000000, 0x00000000, 0x00000000), 1, 0,2163"2004/07/21 18:57:42", 3024, "sRGB_IEC61966-2-1_noBPC.icc")21642165/* This is a 'mntr' (display) profile with a mediaWhitePointTag that does not2166* match the D50 PCS illuminant in the header (it is in fact the D65 values,2167* so the white point is recorded as the un-adapted value.) The profiles2168* below only differ in one byte - the intent - and are basically the same as2169* the previous profile except for the mediaWhitePointTag error and a missing2170* chromaticAdaptationTag.2171*/2172PNG_ICC_CHECKSUM(0xf784f3fb, 0x182ea552,2173PNG_MD5(0x00000000, 0x00000000, 0x00000000, 0x00000000), 0, 1/*broken*/,2174"1998/02/09 06:49:00", 3144, "HP-Microsoft sRGB v2 perceptual")21752176PNG_ICC_CHECKSUM(0x0398f3fc, 0xf29e526d,2177PNG_MD5(0x00000000, 0x00000000, 0x00000000, 0x00000000), 1, 1/*broken*/,2178"1998/02/09 06:49:00", 3144, "HP-Microsoft sRGB v2 media-relative")2179};21802181static int2182png_compare_ICC_profile_with_sRGB(png_const_structrp png_ptr,2183png_const_bytep profile, uLong adler)2184{2185/* The quick check is to verify just the MD5 signature and trust the2186* rest of the data. Because the profile has already been verified for2187* correctness this is safe. png_colorspace_set_sRGB will check the 'intent'2188* field too, so if the profile has been edited with an intent not defined2189* by sRGB (but maybe defined by a later ICC specification) the read of2190* the profile will fail at that point.2191*/2192png_uint_32 length = 0;2193png_uint_32 intent = 0x10000; /* invalid */2194#if PNG_sRGB_PROFILE_CHECKS > 12195uLong crc = 0; /* the value for 0 length data */2196#endif2197unsigned int i;21982199# ifdef PNG_SET_OPTION_SUPPORTED2200# ifdef PNG_SKIP_sRGB_CHECK_PROFILE2201/* First see if PNG_SKIP_sRGB_CHECK_PROFILE has been set to "on" */2202if (!png_ptr->skip_sRGB_profile_check)2203# endif /* SKIP_sRGB_CHECK_PROFILE */2204# endif /* SET_OPTION */2205for (i=0; i < (sizeof png_sRGB_checks) / (sizeof png_sRGB_checks[0]); ++i)2206{2207if (png_get_uint_32(profile+84) == png_sRGB_checks[i].md5[0] &&2208png_get_uint_32(profile+88) == png_sRGB_checks[i].md5[1] &&2209png_get_uint_32(profile+92) == png_sRGB_checks[i].md5[2] &&2210png_get_uint_32(profile+96) == png_sRGB_checks[i].md5[3])2211{2212/* This may be one of the old HP profiles without an MD5, in that2213* case we can only use the length and Adler32 (note that these2214* are not used by default if there is an MD5!)2215*/2216# if PNG_sRGB_PROFILE_CHECKS == 02217if (png_sRGB_checks[i].have_md5 != 0)2218return 1+png_sRGB_checks[i].is_broken;2219# endif22202221/* Profile is unsigned or more checks have been configured in. */2222if (length == 0)2223{2224length = png_get_uint_32(profile);2225intent = png_get_uint_32(profile+64);2226}22272228/* Length *and* intent must match */2229if (length == png_sRGB_checks[i].length &&2230intent == (png_uint_32) png_sRGB_checks[i].intent)2231{2232/* Now calculate the adler32 if not done already. */2233if (adler == 0)2234{2235adler = adler32(0, NULL, 0);2236adler = adler32(adler, profile, length);2237}22382239if (adler == png_sRGB_checks[i].adler)2240{2241/* These basic checks suggest that the data has not been2242* modified, but if the check level is more than 1 perform2243* our own crc32 checksum on the data.2244*/2245# if PNG_sRGB_PROFILE_CHECKS > 12246if (crc == 0)2247{2248crc = crc32(0, NULL, 0);2249crc = crc32(crc, profile, length);2250}22512252/* So this check must pass for the 'return' below to happen.2253*/2254if (crc == png_sRGB_checks[i].crc)2255# endif2256{2257if (png_sRGB_checks[i].is_broken != 0)2258{2259/* These profiles are known to have bad data that may cause2260* problems if they are used, therefore attempt to2261* discourage their use, skip the 'have_md5' warning below,2262* which is made irrelevant by this error.2263*/2264png_chunk_report(png_ptr, "known incorrect sRGB profile",2265PNG_CHUNK_ERROR);2266}22672268/* Warn that this being done; this isn't even an error since2269* the profile is perfectly valid, but it would be nice if2270* people used the up-to-date ones.2271*/2272else if (png_sRGB_checks[i].have_md5 == 0)2273{2274png_chunk_report(png_ptr,2275"out-of-date sRGB profile with no signature",2276PNG_CHUNK_WARNING);2277}22782279return 1+png_sRGB_checks[i].is_broken;2280}2281}22822283# if PNG_sRGB_PROFILE_CHECKS > 02284/* The signature matched, but the profile had been changed in some2285* way. This probably indicates a data error or uninformed hacking.2286* Fall through to "no match".2287*/2288png_chunk_report(png_ptr,2289"Not recognizing known sRGB profile that has been edited",2290PNG_CHUNK_WARNING);2291break;2292# endif2293}2294}2295}22962297return 0; /* no match */2298}22992300void /* PRIVATE */2301png_icc_set_sRGB(png_const_structrp png_ptr,2302png_colorspacerp colorspace, png_const_bytep profile, uLong adler)2303{2304/* Is this profile one of the known ICC sRGB profiles? If it is, just set2305* the sRGB information.2306*/2307if (png_compare_ICC_profile_with_sRGB(png_ptr, profile, adler) != 0)2308(void)png_colorspace_set_sRGB(png_ptr, colorspace,2309(int)/*already checked*/png_get_uint_32(profile+64));2310}2311#endif /* PNG_sRGB_PROFILE_CHECKS >= 0 */2312#endif /* sRGB */23132314int /* PRIVATE */2315png_colorspace_set_ICC(png_const_structrp png_ptr, png_colorspacerp colorspace,2316png_const_charp name, png_uint_32 profile_length, png_const_bytep profile,2317int is_color)2318{2319if ((colorspace->flags & PNG_COLORSPACE_INVALID) != 0)2320return 0;23212322if (png_icc_check_length(png_ptr, colorspace, name, profile_length) != 0 &&2323png_icc_check_header(png_ptr, colorspace, name, profile_length, profile,2324is_color) != 0 &&2325png_icc_check_tag_table(png_ptr, colorspace, name, profile_length,2326profile) != 0)2327{2328# if defined(PNG_sRGB_SUPPORTED) && PNG_sRGB_PROFILE_CHECKS >= 02329/* If no sRGB support, don't try storing sRGB information */2330png_icc_set_sRGB(png_ptr, colorspace, profile, 0);2331# endif2332return 1;2333}23342335/* Failure case */2336return 0;2337}2338#endif /* iCCP */2339#endif /* COLORSPACE */23402341png_alloc_size_t /* PRIVATE */2342png_calc_rowbytes(png_const_structrp png_ptr, unsigned int pixel_depth,2343png_uint_32 row_width)2344{2345png_alloc_size_t rowbytes = row_width;23462347/* Carefully calculate the row buffer size. */2348if (pixel_depth > 8)2349{2350if ((pixel_depth & 7) != 0)2351png_error(png_ptr, "unsupported pixel byte size");23522353pixel_depth >>= 3; /* Now in bytes */23542355if (rowbytes > PNG_SIZE_MAX/pixel_depth)2356png_error(png_ptr, "image row exceeds system limits");23572358rowbytes *= pixel_depth;2359}23602361else /* Less than 1 byte per pixel */ switch (pixel_depth)2362{2363case 1: rowbytes += 7; rowbytes >>= 3; break;2364case 2: rowbytes += 3; rowbytes >>= 2; break;2365case 4: rowbytes += 1; rowbytes >>= 1; break;2366case 8: break;2367default:2368png_error(png_ptr, "unsupported pixel bit size");2369}23702371return rowbytes;2372}23732374unsigned int /*PRIVATE*/2375png_max_pixel_block(png_const_structrp png_ptr)2376{2377/* Need the *smallest* pixel size that must occur in alignment units. On2378* read this is the PNG pixel depth because the read transforms cannot reduce2379* the pixel size below the input size or 8-bits, whichever is smaller.2380*2381* On write the 'pack' transform can pack 8-bit pixels back to a lower bit2382* depth, but the lowest bit depth is still given by the PNG pixel size.2383*/2384const unsigned int pixel_depth = PNG_PIXEL_DEPTH(*png_ptr);2385const unsigned int pixel_block = /* count of pixels in a block */2386pixel_depth < 8U ?2387PNG_ROW_BUFFER_BYTE_ALIGN * (8U/pixel_depth) :2388PNG_ROW_BUFFER_BYTE_ALIGN; /* pixels may be any whole byte size */2389/* The maximum block size in bits is MAX_PIXEL_DEPTH*pixel_block so work out2390* the minimum number of pixel blocks that can fit in PNG_ROW_BUFFER_SIZE2391* bytes and use this to calculate the maximum number of pixels:2392*/2393return pixel_block *2394((8U*PNG_ROW_BUFFER_SIZE) / (png_ptr->row_max_pixel_depth*pixel_block));2395}23962397void /* PRIVATE */2398png_copy_row(png_const_structrp png_ptr, png_bytep dp, png_const_bytep sp,2399png_uint_32 x/*in INPUT*/, png_uint_32 width/*of INPUT*/,2400unsigned int pixel_depth, int clear/*clear the final byte*/, int x_in_dest)2401/* Copy the row in row_buffer; this is the non-interlaced copy used in both2402* the read and write code. 'x_in_dest' specifies whether the 'x' applies to2403* the destination (sp->dp[x], x_in_dest tru) or the source (sp[x]->dp,2404* x_in_dest false).2405*/2406{2407png_alloc_size_t cb, offset;2408unsigned int remaining; /* remaining bits in a partial byte */24092410/* Copy 'cb' pixels, but take care with the last byte because it may2411* be partially written. 'x' must correspond to the start of a byte, check2412* that too:2413*/2414switch (pixel_depth)2415{2416case 1U: remaining = width & 7U;2417debug((x & 7U) == 0U);2418cb = width >> 3;2419offset = x >> 3;2420break;2421case 2U: remaining = (width << 1) & 6U;2422debug((x & 3U) == 0U);2423cb = width >> 2;2424offset = x >> 2;2425break;2426case 4U: remaining = (width << 2) & 4U;2427debug((x & 1U) == 0U);2428cb = width >> 1;2429offset = x >> 1;2430break;2431case 8U: remaining = 0U;2432cb = width;2433offset = x;2434break;2435default: remaining = 0U;2436cb = png_calc_rowbytes(png_ptr, pixel_depth, width);2437offset = png_calc_rowbytes(png_ptr, pixel_depth, x);2438break;2439}24402441if (x_in_dest)2442dp += offset;24432444else2445sp += offset;24462447memcpy(dp, sp, cb);24482449if (remaining > 0U)2450{2451/* 'remaining' is the number of bits still to be copied. Format may be2452* little endian; bits to copy in the bottom of 's'. Make 'remaining'2453* into a mask of the bits to *preserve* in dp.2454*/2455# ifdef PNG_TRANSFORM_MECH_SUPPORTED2456if ((png_ptr->row_format & PNG_FORMAT_FLAG_SWAPPED) == 0U)2457remaining = 0xffU >> remaining;24582459else2460# endif /* TRANSFORM_MECH */2461remaining = 0xffU << remaining;24622463/* remaining is now the bits to *keep* from the destination byte, if2464* 'clear' is true the source bytes aren't copied - this is for security2465* reasons to avoid copying undefined bits at the end of a row. If2466* 'clear' is set the destination bits are not preserved, they are just2467* set to 0.2468*/2469if (clear)2470dp[cb] = PNG_BYTE(sp[cb] & ~remaining);24712472else2473dp[cb] = PNG_BYTE((sp[cb] & ~remaining) | (dp[cb] & remaining));2474}2475}24762477void /* PRIVATE */2478png_check_IHDR(png_const_structrp png_ptr,2479png_uint_32 width, png_uint_32 height, int bit_depth,2480int color_type, int interlace_type, int compression_type,2481int filter_type)2482{2483int error = 0;24842485/* Check for width and height valid values */2486if (width == 0)2487{2488png_warning(png_ptr, "Image width is zero in IHDR");2489error = 1;2490}24912492if (width > PNG_UINT_31_MAX)2493{2494png_warning(png_ptr, "Invalid image width in IHDR");2495error = 1;2496}24972498#ifdef PNG_SET_USER_LIMITS_SUPPORTED2499if (width > png_ptr->user_width_max)2500{2501png_warning(png_ptr, "Image width exceeds user limit in IHDR");2502error = 1;2503}2504#else2505if (width > PNG_USER_WIDTH_MAX)2506{2507png_warning(png_ptr, "Image width exceeds WIDTH_MAX in IHDR");2508error = 1;2509}2510#endif25112512if (height == 0)2513{2514png_warning(png_ptr, "Image height is zero in IHDR");2515error = 1;2516}25172518if (height > PNG_UINT_31_MAX)2519{2520png_warning(png_ptr, "Invalid image height in IHDR");2521error = 1;2522}25232524#ifdef PNG_SET_USER_LIMITS_SUPPORTED2525if (height > png_ptr->user_height_max)2526{2527png_warning(png_ptr, "Image height exceeds user limit in IHDR");2528error = 1;2529}2530#else2531if (height > PNG_USER_HEIGHT_MAX)2532{2533png_warning(png_ptr, "Image height exceeds HEIGHT_MAX in IHDR");2534error = 1;2535}2536#endif25372538/* Check other values */2539if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&2540bit_depth != 8 && bit_depth != 16)2541{2542png_warning(png_ptr, "Invalid bit depth in IHDR");2543error = 1;2544}25452546if (color_type < 0 || color_type == 1 ||2547color_type == 5 || color_type > 6)2548{2549png_warning(png_ptr, "Invalid color type in IHDR");2550error = 1;2551}25522553if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||2554((color_type == PNG_COLOR_TYPE_RGB ||2555color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||2556color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))2557{2558png_warning(png_ptr, "Invalid color type/bit depth combination in IHDR");2559error = 1;2560}25612562if (interlace_type >= PNG_INTERLACE_LAST)2563{2564png_warning(png_ptr, "Unknown interlace method in IHDR");2565error = 1;2566}25672568if (compression_type != PNG_COMPRESSION_TYPE_BASE)2569{2570png_warning(png_ptr, "Unknown compression method in IHDR");2571error = 1;2572}25732574#ifdef PNG_MNG_FEATURES_SUPPORTED2575/* Accept filter_method 64 (intrapixel differencing) only if2576* 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and2577* 2. Libpng did not read a PNG signature (this filter_method is only2578* used in PNG datastreams that are embedded in MNG datastreams) and2579* 3. The application called png_permit_mng_features with a mask that2580* included PNG_FLAG_MNG_FILTER_64 and2581* 4. The filter_method is 64 and2582* 5. The color_type is RGB or RGBA2583*/2584if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 &&2585png_ptr->mng_features_permitted != 0)2586png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");25872588if (filter_type != PNG_FILTER_TYPE_BASE)2589{2590if (!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&2591(filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&2592((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) == 0) &&2593(color_type == PNG_COLOR_TYPE_RGB ||2594color_type == PNG_COLOR_TYPE_RGB_ALPHA)))2595{2596png_warning(png_ptr, "Invalid filter method in IHDR");2597error = 1;2598}25992600if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0)2601{2602png_warning(png_ptr, "Invalid filter method in IHDR");2603error = 1;2604}2605}26062607#else /* !MNG_FEATURES */2608if (filter_type != PNG_FILTER_TYPE_BASE)2609{2610png_warning(png_ptr, "Unknown filter method in IHDR");2611error = 1;2612}2613#endif /* !MNG_FEATURES */26142615if (error == 1)2616png_error(png_ptr, "Invalid IHDR data");26172618/* Finally, if the IHDR data is correct, check it against the system2619* limits (NOTE: this need not be done; the IDAT handling code repeats the2620* check in both read and write.)2621*/2622(void)png_calc_rowbytes(png_ptr,2623PNG_COLOR_TYPE_CHANNELS(color_type) * bit_depth, width);2624}26252626#if defined(PNG_sCAL_SUPPORTED) || defined(PNG_pCAL_SUPPORTED)2627/* ASCII to fp functions */2628/* Check an ASCII formated floating point value, see the more detailed2629* comments in pngpriv.h2630*/2631/* The following is used internally to preserve the sticky flags */2632#define png_fp_add(state, flags) ((state) |= (flags))2633#define png_fp_set(state, value) ((state) = (value) | ((state) & PNG_FP_STICKY))26342635int /* PRIVATE */2636png_check_fp_number(png_const_charp string, png_size_t size, int *statep,2637png_size_tp whereami)2638{2639int state = *statep;2640png_size_t i = *whereami;26412642while (i < size)2643{2644int type;2645/* First find the type of the next character */2646switch (string[i])2647{2648case 43: type = PNG_FP_SAW_SIGN; break;2649case 45: type = PNG_FP_SAW_SIGN + PNG_FP_NEGATIVE; break;2650case 46: type = PNG_FP_SAW_DOT; break;2651case 48: type = PNG_FP_SAW_DIGIT; break;2652case 49: case 50: case 51: case 52:2653case 53: case 54: case 55: case 56:2654case 57: type = PNG_FP_SAW_DIGIT + PNG_FP_NONZERO; break;2655case 69:2656case 101: type = PNG_FP_SAW_E; break;2657default: goto PNG_FP_End;2658}26592660/* Now deal with this type according to the current2661* state, the type is arranged to not overlap the2662* bits of the PNG_FP_STATE.2663*/2664switch ((state & PNG_FP_STATE) + (type & PNG_FP_SAW_ANY))2665{2666case PNG_FP_INTEGER + PNG_FP_SAW_SIGN:2667if ((state & PNG_FP_SAW_ANY) != 0)2668goto PNG_FP_End; /* not a part of the number */26692670png_fp_add(state, type);2671break;26722673case PNG_FP_INTEGER + PNG_FP_SAW_DOT:2674/* Ok as trailer, ok as lead of fraction. */2675if ((state & PNG_FP_SAW_DOT) != 0) /* two dots */2676goto PNG_FP_End;26772678else if ((state & PNG_FP_SAW_DIGIT) != 0) /* trailing dot? */2679png_fp_add(state, type);26802681else2682png_fp_set(state, PNG_FP_FRACTION | type);26832684break;26852686case PNG_FP_INTEGER + PNG_FP_SAW_DIGIT:2687if ((state & PNG_FP_SAW_DOT) != 0) /* delayed fraction */2688png_fp_set(state, PNG_FP_FRACTION | PNG_FP_SAW_DOT);26892690png_fp_add(state, type | PNG_FP_WAS_VALID);26912692break;26932694case PNG_FP_INTEGER + PNG_FP_SAW_E:2695if ((state & PNG_FP_SAW_DIGIT) == 0)2696goto PNG_FP_End;26972698png_fp_set(state, PNG_FP_EXPONENT);26992700break;27012702/* case PNG_FP_FRACTION + PNG_FP_SAW_SIGN:2703goto PNG_FP_End; ** no sign in fraction */27042705/* case PNG_FP_FRACTION + PNG_FP_SAW_DOT:2706goto PNG_FP_End; ** Because SAW_DOT is always set */27072708case PNG_FP_FRACTION + PNG_FP_SAW_DIGIT:2709png_fp_add(state, type | PNG_FP_WAS_VALID);2710break;27112712case PNG_FP_FRACTION + PNG_FP_SAW_E:2713/* This is correct because the trailing '.' on an2714* integer is handled above - so we can only get here2715* with the sequence ".E" (with no preceding digits).2716*/2717if ((state & PNG_FP_SAW_DIGIT) == 0)2718goto PNG_FP_End;27192720png_fp_set(state, PNG_FP_EXPONENT);27212722break;27232724case PNG_FP_EXPONENT + PNG_FP_SAW_SIGN:2725if ((state & PNG_FP_SAW_ANY) != 0)2726goto PNG_FP_End; /* not a part of the number */27272728png_fp_add(state, PNG_FP_SAW_SIGN);27292730break;27312732/* case PNG_FP_EXPONENT + PNG_FP_SAW_DOT:2733goto PNG_FP_End; */27342735case PNG_FP_EXPONENT + PNG_FP_SAW_DIGIT:2736png_fp_add(state, PNG_FP_SAW_DIGIT | PNG_FP_WAS_VALID);27372738break;27392740/* case PNG_FP_EXPONEXT + PNG_FP_SAW_E:2741goto PNG_FP_End; */27422743default: goto PNG_FP_End; /* I.e. break 2 */2744}27452746/* The character seems ok, continue. */2747++i;2748}27492750PNG_FP_End:2751/* Here at the end, update the state and return the correct2752* return code.2753*/2754*statep = state;2755*whereami = i;27562757return (state & PNG_FP_SAW_DIGIT) != 0;2758}275927602761/* The same but for a complete string. */2762int2763png_check_fp_string(png_const_charp string, png_size_t size)2764{2765int state=0;2766png_size_t char_index=0;27672768if (png_check_fp_number(string, size, &state, &char_index) != 0 &&2769(char_index == size || string[char_index] == 0))2770return state /* must be non-zero - see above */;27712772return 0; /* i.e. fail */2773}2774#endif /* pCAL || sCAL */27752776#ifdef PNG_sCAL_SUPPORTED2777# ifdef PNG_FLOATING_POINT_SUPPORTED2778/* Utility used below - a simple accurate power of ten from an integral2779* exponent.2780*/2781static double2782png_pow10(int power)2783{2784int recip = 0;2785double d = 1;27862787/* Handle negative exponent with a reciprocal at the end because2788* 10 is exact whereas .1 is inexact in base 22789*/2790if (power < 0)2791{2792if (power < DBL_MIN_10_EXP) return 0;2793recip = 1; power = -power;2794}27952796if (power > 0)2797{2798/* Decompose power bitwise. */2799double mult = 10;2800do2801{2802if (power & 1) d *= mult;2803mult *= mult;2804power >>= 1;2805}2806while (power > 0);28072808if (recip != 0) d = 1/d;2809}2810/* else power is 0 and d is 1 */28112812return d;2813}28142815/* Function to format a floating point value in ASCII with a given2816* precision.2817*/2818void /* PRIVATE */2819png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, png_size_t size,2820double fp, unsigned int precision)2821{2822/* We use standard functions from math.h, but not printf because2823* that would require stdio. The caller must supply a buffer of2824* sufficient size or we will png_error. The tests on size and2825* the space in ascii[] consumed are indicated below.2826*/2827if (precision < 1)2828precision = DBL_DIG;28292830/* Enforce the limit of the implementation precision too. */2831if (precision > DBL_DIG+1)2832precision = DBL_DIG+1;28332834/* Basic sanity checks */2835if (size >= precision+5) /* See the requirements below. */2836{2837if (fp < 0)2838{2839fp = -fp;2840*ascii++ = 45; /* '-' PLUS 1 TOTAL 1 */2841--size;2842}28432844if (fp >= DBL_MIN && fp <= DBL_MAX)2845{2846int exp_b10; /* A base 10 exponent */2847double base; /* 10^exp_b10 */28482849/* First extract a base 10 exponent of the number,2850* the calculation below rounds down when converting2851* from base 2 to base 10 (multiply by log10(2) -2852* 0.3010, but 77/256 is 0.3008, so exp_b10 needs to2853* be increased. Note that the arithmetic shift2854* performs a floor() unlike C arithmetic - using a2855* C multiply would break the following for negative2856* exponents.2857*/2858(void)frexp(fp, &exp_b10); /* exponent to base 2 */28592860exp_b10 = (exp_b10 * 77) >> 8; /* <= exponent to base 10 */28612862/* Avoid underflow here. */2863base = png_pow10(exp_b10); /* May underflow */28642865while (base < DBL_MIN || base < fp)2866{2867/* And this may overflow. */2868double test = png_pow10(exp_b10+1);28692870if (test <= DBL_MAX)2871{2872++exp_b10; base = test;2873}28742875else2876break;2877}28782879/* Normalize fp and correct exp_b10, after this fp is in the2880* range [.1,1) and exp_b10 is both the exponent and the digit2881* *before* which the decimal point should be inserted2882* (starting with 0 for the first digit). Note that this2883* works even if 10^exp_b10 is out of range because of the2884* test on DBL_MAX above.2885*/2886fp /= base;2887while (fp >= 1)2888{2889fp /= 10; ++exp_b10;2890}28912892/* Because of the code above fp may, at this point, be2893* less than .1, this is ok because the code below can2894* handle the leading zeros this generates, so no attempt2895* is made to correct that here.2896*/28972898{2899unsigned int czero, clead, cdigits;2900char exponent[10];29012902/* Allow up to two leading zeros - this will not lengthen2903* the number compared to using E-n.2904*/2905if (exp_b10 < 0 && exp_b10 > -3) /* PLUS 3 TOTAL 4 */2906{2907czero = -exp_b10; /* PLUS 2 digits: TOTAL 3 */2908exp_b10 = 0; /* Dot added below before first output. */2909}2910else2911czero = 0; /* No zeros to add */29122913/* Generate the digit list, stripping trailing zeros and2914* inserting a '.' before a digit if the exponent is 0.2915*/2916clead = czero; /* Count of leading zeros */2917cdigits = 0; /* Count of digits in list. */29182919do2920{2921double d;29222923fp *= 10;2924/* Use modf here, not floor and subtract, so that2925* the separation is done in one step. At the end2926* of the loop don't break the number into parts so2927* that the final digit is rounded.2928*/2929if (cdigits+czero+1 < precision+clead)2930fp = modf(fp, &d);29312932else2933{2934d = floor(fp + .5);29352936if (d > 9)2937{2938/* Rounding up to 10, handle that here. */2939if (czero > 0)2940{2941--czero; d = 1;2942if (cdigits == 0) --clead;2943}2944else2945{2946while (cdigits > 0 && d > 9)2947{2948int ch = *--ascii;29492950if (exp_b10 != (-1))2951++exp_b10;29522953else if (ch == 46)2954{2955ch = *--ascii; ++size;2956/* Advance exp_b10 to '1', so that the2957* decimal point happens after the2958* previous digit.2959*/2960exp_b10 = 1;2961}29622963--cdigits;2964d = ch - 47; /* I.e. 1+(ch-48) */2965}29662967/* Did we reach the beginning? If so adjust the2968* exponent but take into account the leading2969* decimal point.2970*/2971if (d > 9) /* cdigits == 0 */2972{2973if (exp_b10 == (-1))2974{2975/* Leading decimal point (plus zeros?), if2976* we lose the decimal point here it must2977* be reentered below.2978*/2979int ch = *--ascii;29802981if (ch == 46)2982{2983++size; exp_b10 = 1;2984}29852986/* Else lost a leading zero, so 'exp_b10' is2987* still ok at (-1)2988*/2989}2990else2991++exp_b10;29922993/* In all cases we output a '1' */2994d = 1;2995}2996}2997}2998fp = 0; /* Guarantees termination below. */2999}30003001if (d == 0)3002{3003++czero;3004if (cdigits == 0) ++clead;3005}3006else3007{3008/* Included embedded zeros in the digit count. */3009cdigits += czero - clead;3010clead = 0;30113012while (czero > 0)3013{3014/* exp_b10 == (-1) means we just output the decimal3015* place - after the DP don't adjust 'exp_b10' any3016* more!3017*/3018if (exp_b10 != (-1))3019{3020if (exp_b10 == 0) *ascii++ = 46, --size;3021/* PLUS 1: TOTAL 4 */3022--exp_b10;3023}3024*ascii++ = 48, --czero;3025}30263027if (exp_b10 != (-1))3028{3029if (exp_b10 == 0)3030*ascii++ = 46, --size; /* counted above */30313032--exp_b10;3033}3034*ascii++ = png_check_char(png_ptr, 48 + (int)d), ++cdigits;3035}3036}3037while (cdigits+czero < precision+clead && fp > DBL_MIN);30383039/* The total output count (max) is now 4+precision */30403041/* Check for an exponent, if we don't need one we are3042* done and just need to terminate the string. At3043* this point exp_b10==(-1) is effectively if flag - it got3044* to '-1' because of the decrement after outputting3045* the decimal point above (the exponent required is3046* *not* -1!)3047*/3048if (exp_b10 >= (-1) && exp_b10 <= 2)3049{3050/* The following only happens if we didn't output the3051* leading zeros above for negative exponent, so this3052* doesn't add to the digit requirement. Note that the3053* two zeros here can only be output if the two leading3054* zeros were *not* output, so this doesn't increase3055* the output count.3056*/3057while (--exp_b10 >= 0) *ascii++ = 48;30583059*ascii = 0;30603061/* Total buffer requirement (including the '\0') is3062* 5+precision - see check at the start.3063*/3064return;3065}30663067/* Here if an exponent is required, adjust size for3068* the digits we output but did not count. The total3069* digit output here so far is at most 1+precision - no3070* decimal point and no leading or trailing zeros have3071* been output.3072*/3073size -= cdigits;30743075*ascii++ = 69; --size; /* 'E': PLUS 1 TOTAL 2+precision */30763077/* The following use of an unsigned temporary avoids ambiguities in3078* the signed arithmetic on exp_b10 and permits GCC at least to do3079* better optimization.3080*/3081{3082unsigned int uexp_b10;30833084if (exp_b10 < 0)3085{3086*ascii++ = 45, --size; /* '-': PLUS 1 TOTAL 3+precision */3087uexp_b10 = -exp_b10;3088}30893090else3091uexp_b10 = exp_b10;30923093cdigits = 0;30943095while (uexp_b10 > 0)3096{3097exponent[cdigits++] = (char)/*SAFE*/(48 + uexp_b10 % 10);3098uexp_b10 /= 10;3099}3100}31013102/* Need another size check here for the exponent digits, so3103* this need not be considered above.3104*/3105if (size > cdigits)3106{3107while (cdigits > 0) *ascii++ = exponent[--cdigits];31083109*ascii = 0;31103111return;3112}3113}3114}3115else if (!(fp >= DBL_MIN))3116{3117*ascii++ = 48; /* '0' */3118*ascii = 0;3119return;3120}3121else3122{3123*ascii++ = 105; /* 'i' */3124*ascii++ = 110; /* 'n' */3125*ascii++ = 102; /* 'f' */3126*ascii = 0;3127return;3128}3129}31303131/* Here on buffer too small. */3132png_error(png_ptr, "ASCII conversion buffer too small");3133}31343135# endif /* FLOATING_POINT */31363137# ifdef PNG_FIXED_POINT_SUPPORTED3138/* Function to format a fixed point value in ASCII.3139*/3140void /* PRIVATE */3141png_ascii_from_fixed(png_const_structrp png_ptr, png_charp ascii,3142png_size_t size, png_fixed_point fp)3143{3144/* Require space for 10 decimal digits, a decimal point, a minus sign and a3145* trailing \0, 13 characters:3146*/3147if (size > 12)3148{3149png_uint_32 num;31503151/* Avoid overflow here on the minimum integer. */3152if (fp < 0)3153*ascii++ = 45, --size, num = -fp;3154else3155num = fp;31563157if (num <= 0x80000000) /* else overflowed */3158{3159unsigned int ndigits = 0, first = 16 /* flag value */;3160char digits[10];31613162while (num)3163{3164/* Split the low digit off num: */3165unsigned int tmp = num/10;3166num -= tmp*10;3167digits[ndigits++] = png_check_char(png_ptr, 48 + num);3168/* Record the first non-zero digit, note that this is a number3169* starting at 1, it's not actually the array index.3170*/3171if (first == 16 && num > 0)3172first = ndigits;3173num = tmp;3174}31753176if (ndigits > 0)3177{3178while (ndigits > 5) *ascii++ = digits[--ndigits];3179/* The remaining digits are fractional digits, ndigits is '5' or3180* smaller at this point. It is certainly not zero. Check for a3181* non-zero fractional digit:3182*/3183if (first <= 5)3184{3185unsigned int i;3186*ascii++ = 46; /* decimal point */3187/* ndigits may be <5 for small numbers, output leading zeros3188* then ndigits digits to first:3189*/3190i = 5;3191while (ndigits < i)3192{3193*ascii++ = 48; --i;3194}3195while (ndigits >= first) *ascii++ = digits[--ndigits];3196/* Don't output the trailing zeros! */3197}3198}3199else3200*ascii++ = 48;32013202/* And null terminate the string: */3203*ascii = 0;3204return;3205}3206}32073208/* Here on buffer too small. */3209png_error(png_ptr, "ASCII conversion buffer too small");3210}3211# endif /* FIXED_POINT */3212#endif /* SCAL */32133214#if !defined(PNG_FIXED_POINT_MACRO_SUPPORTED) && (\3215defined(PNG_FLOATING_POINT_SUPPORTED) && \3216(defined(PNG_gAMA_SUPPORTED) || defined(PNG_cHRM_SUPPORTED) || \3217defined(PNG_sCAL_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) || \3218defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)) || \3219(defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) &&\3220defined(PNG_sCAL_SUPPORTED)))3221png_fixed_point3222png_fixed(png_const_structrp png_ptr, double fp, png_const_charp text)3223{3224if (fp < 0)3225{3226if (fp > -21474.836485)3227return (png_fixed_point)(100000*fp - .5);3228}32293230else3231{3232if (fp < 21474.836475)3233return (png_fixed_point)(100000*fp + .5);3234}32353236/* Overflow */3237png_fixed_error(png_ptr, text);32383239# ifndef PNG_ERROR_TEXT_SUPPORTED3240PNG_UNUSED(text)3241# endif3242}3243#endif32443245#if defined(PNG_GAMMA_SUPPORTED) || defined(PNG_COLORSPACE_SUPPORTED) ||\3246defined(PNG_INCH_CONVERSIONS_SUPPORTED) || defined(PNG_READ_pHYs_SUPPORTED)3247/* muldiv functions */3248/* This API takes signed arguments and rounds the result to the nearest3249* integer (or, for a fixed point number - the standard argument - to3250* the nearest .00001). Overflow and divide by zero are signalled in3251* the result, a boolean - true on success, false on overflow.3252*/3253int3254png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times,3255png_int_32 divisor)3256{3257/* Return a * times / divisor, rounded. */3258if (divisor != 0)3259{3260if (a == 0 || times == 0)3261{3262*res = 0;3263return 1;3264}3265else3266{3267#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED3268double r = a;3269r *= times;3270r /= divisor;3271r = floor(r+.5);32723273/* A png_fixed_point is a 32-bit integer. */3274if (r <= 2147483647. && r >= -2147483648.)3275{3276*res = (png_fixed_point)r;3277return 1;3278}3279#else3280int negative = 0;3281png_uint_32 A, T, D;3282png_uint_32 s16, s32, s00;32833284if (a < 0)3285negative = 1, A = -a;3286else3287A = a;32883289if (times < 0)3290negative = !negative, T = -times;3291else3292T = times;32933294if (divisor < 0)3295negative = !negative, D = -divisor;3296else3297D = divisor;32983299/* Following can't overflow because the arguments only3300* have 31 bits each, however the result may be 32 bits.3301*/3302s16 = (A >> 16) * (T & 0xffff) +3303(A & 0xffff) * (T >> 16);3304/* Can't overflow because the a*times bit is only 303305* bits at most.3306*/3307s32 = (A >> 16) * (T >> 16) + (s16 >> 16);3308s00 = (A & 0xffff) * (T & 0xffff);33093310s16 = (s16 & 0xffff) << 16;3311s00 += s16;33123313if (s00 < s16)3314++s32; /* carry */33153316if (s32 < D) /* else overflow */3317{3318/* s32.s00 is now the 64-bit product, do a standard3319* division, we know that s32 < D, so the maximum3320* required shift is 31.3321*/3322int bitshift = 32;3323png_fixed_point result = 0; /* NOTE: signed */33243325while (--bitshift >= 0)3326{3327png_uint_32 d32, d00;33283329if (bitshift > 0)3330d32 = D >> (32-bitshift), d00 = D << bitshift;33313332else3333d32 = 0, d00 = D;33343335if (s32 > d32)3336{3337if (s00 < d00) --s32; /* carry */3338s32 -= d32, s00 -= d00, result += 1<<bitshift;3339}33403341else3342if (s32 == d32 && s00 >= d00)3343s32 = 0, s00 -= d00, result += 1<<bitshift;3344}33453346/* Handle the rounding. */3347if (s00 >= (D >> 1))3348++result;33493350if (negative != 0)3351result = -result;33523353/* Check for overflow. */3354if ((negative != 0 && result <= 0) ||3355(negative == 0 && result >= 0))3356{3357*res = result;3358return 1;3359}3360}3361#endif3362}3363}33643365return 0;3366}3367#endif /* GAMMA || INCH_CONVERSIONS */33683369/* SOFTWARE SETTING SUPPORT */3370png_int_32 PNGAPI3371png_setting(png_structrp png_ptr, png_uint_32 setting, png_uint_32 parameter,3372png_int_32 value)3373{3374png_int_32 result;33753376if (png_ptr != NULL)3377{3378int handle_error = (setting & PNG_SF_ERROR) != 0U;33793380setting &= ~PNG_SF_ERROR; /* because it is handled below. */33813382switch (setting & (PNG_SF_READ|PNG_SF_WRITE))3383{3384# ifdef PNG_READ_SUPPORTED3385case PNG_SF_READ:3386if (png_ptr->read_struct)3387result = png_read_setting(png_ptr, setting, parameter, value);33883389else3390result = PNG_EINVAL; /* read setting on write struct */3391break;3392# endif /* READ */33933394# ifdef PNG_WRITE_SUPPORTED3395case PNG_SF_WRITE:3396if (!png_ptr->read_struct)3397result = png_write_setting(png_ptr, setting, parameter,3398value);33993400else3401result = PNG_EINVAL; /* write setting on read struct */3402break;3403# endif /* WRITE */34043405default:3406/* Handle everything else here. This includes the error of not3407* having either read or write set; that error will cause a3408* PNG_ENOSYS return code.3409*/3410switch (setting)3411{3412# ifdef PNG_SET_OPTION_SUPPORTED3413case PNG_SRW_OPTION:3414if (parameter >= PNG_OPTION_NEXT)3415return PNG_OPTION_INVALID;34163417if (parameter == PNG_SKIP_sRGB_CHECK_PROFILE)3418{3419if (png_ptr->skip_sRGB_profile_check)3420{3421if (!value)3422png_ptr->skip_sRGB_profile_check = 0U;3423result = PNG_OPTION_ON;3424}34253426else3427{3428if (value)3429png_ptr->skip_sRGB_profile_check = 1U;3430result = PNG_OPTION_OFF;3431}34323433break;3434}34353436# ifdef PNG_READ_SUPPORTED3437if (png_ptr->read_struct)3438{3439result = png_read_setting(png_ptr, setting,3440parameter, value);3441break;3442}3443# endif /* READ */34443445/* No write options at present */3446result = PNG_OPTION_UNSET; /* i.e. ignore it */3447break;3448# endif /* SET_OPTION */34493450default:3451/* Any other option; handle in the appropriate setting: */3452# ifdef PNG_READ_SUPPORTED3453if (png_ptr->read_struct)3454{3455result = png_read_setting(png_ptr, setting,3456parameter, value);3457break;3458}3459# endif /* READ */34603461# ifdef PNG_WRITE_SUPPORTED3462if (!png_ptr->read_struct)3463{3464result = png_write_setting(png_ptr, setting,3465parameter, value);3466break;3467}3468# endif /* WRITE */34693470NOT_REACHED;3471result= PNG_ENOSYS;3472break;3473}3474break;3475} /* switch */34763477/* Handle error returns here.3478* TODO: this is crude, should use a formatted warning style message and3479* output result/setting/parameter/value.3480*/3481if (handle_error && PNG_FAILED(result))3482png_error(png_ptr, "png_setting");3483}34843485else /* png_ptr is NULL */3486result = PNG_EINVAL;34873488return result;3489PNG_UNUSED(parameter)3490PNG_UNUSED(value)3491}34923493/* sRGB support */3494#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\3495defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)3496/* sRGB conversion tables; these are machine generated with the code in3497* contrib/tools/makesRGB.c. The actual sRGB transfer curve defined in the3498* specification (see the article at https://en.wikipedia.org/wiki/SRGB)3499* is used, not the gamma=1/2.2 approximation use elsewhere in libpng.3500* The sRGB to linear table is exact (to the nearest 16-bit linear fraction).3501* The inverse (linear to sRGB) table has accuracies as follows:3502*3503* For all possible (255*65535+1) input values:3504*3505* error: -0.515566 - 0.625971, 79441 (0.475369%) of readings inexact3506*3507* For the input values corresponding to the 65536 16-bit values:3508*3509* error: -0.513727 - 0.607759, 308 (0.469978%) of readings inexact3510*3511* In all cases the inexact readings are only off by one.3512*/35133514#ifdef PNG_SIMPLIFIED_READ_SUPPORTED3515/* The convert-to-sRGB table is only currently required for read. */3516const png_uint_16 png_sRGB_table[256] =3517{35180,20,40,60,80,99,119,139,3519159,179,199,219,241,264,288,313,3520340,367,396,427,458,491,526,562,3521599,637,677,718,761,805,851,898,3522947,997,1048,1101,1156,1212,1270,1330,35231391,1453,1517,1583,1651,1720,1790,1863,35241937,2013,2090,2170,2250,2333,2418,2504,35252592,2681,2773,2866,2961,3058,3157,3258,35263360,3464,3570,3678,3788,3900,4014,4129,35274247,4366,4488,4611,4736,4864,4993,5124,35285257,5392,5530,5669,5810,5953,6099,6246,35296395,6547,6700,6856,7014,7174,7335,7500,35307666,7834,8004,8177,8352,8528,8708,8889,35319072,9258,9445,9635,9828,10022,10219,10417,353210619,10822,11028,11235,11446,11658,11873,12090,353312309,12530,12754,12980,13209,13440,13673,13909,353414146,14387,14629,14874,15122,15371,15623,15878,353516135,16394,16656,16920,17187,17456,17727,18001,353618277,18556,18837,19121,19407,19696,19987,20281,353720577,20876,21177,21481,21787,22096,22407,22721,353823038,23357,23678,24002,24329,24658,24990,25325,353925662,26001,26344,26688,27036,27386,27739,28094,354028452,28813,29176,29542,29911,30282,30656,31033,354131412,31794,32179,32567,32957,33350,33745,34143,354234544,34948,35355,35764,36176,36591,37008,37429,354337852,38278,38706,39138,39572,40009,40449,40891,354441337,41785,42236,42690,43147,43606,44069,44534,354545002,45473,45947,46423,46903,47385,47871,48359,354648850,49344,49841,50341,50844,51349,51858,52369,354752884,53401,53921,54445,54971,55500,56032,56567,354857105,57646,58190,58737,59287,59840,60396,60955,354961517,62082,62650,63221,63795,64372,64952,655353550};35513552#endif /* SIMPLIFIED_READ */35533554/* The base/delta tables are required for both read and write (but currently3555* only the simplified versions.)3556*/3557const png_uint_16 png_sRGB_base[512] =3558{3559128,1782,3383,4644,5675,6564,7357,8074,35608732,9346,9921,10463,10977,11466,11935,12384,356112816,13233,13634,14024,14402,14769,15125,15473,356215812,16142,16466,16781,17090,17393,17690,17981,356318266,18546,18822,19093,19359,19621,19879,20133,356420383,20630,20873,21113,21349,21583,21813,22041,356522265,22487,22707,22923,23138,23350,23559,23767,356623972,24175,24376,24575,24772,24967,25160,25352,356725542,25730,25916,26101,26284,26465,26645,26823,356827000,27176,27350,27523,27695,27865,28034,28201,356928368,28533,28697,28860,29021,29182,29341,29500,357029657,29813,29969,30123,30276,30429,30580,30730,357130880,31028,31176,31323,31469,31614,31758,31902,357232045,32186,32327,32468,32607,32746,32884,33021,357333158,33294,33429,33564,33697,33831,33963,34095,357434226,34357,34486,34616,34744,34873,35000,35127,357535253,35379,35504,35629,35753,35876,35999,36122,357636244,36365,36486,36606,36726,36845,36964,37083,357737201,37318,37435,37551,37668,37783,37898,38013,357838127,38241,38354,38467,38580,38692,38803,38915,357939026,39136,39246,39356,39465,39574,39682,39790,358039898,40005,40112,40219,40325,40431,40537,40642,358140747,40851,40955,41059,41163,41266,41369,41471,358241573,41675,41777,41878,41979,42079,42179,42279,358342379,42478,42577,42676,42775,42873,42971,43068,358443165,43262,43359,43456,43552,43648,43743,43839,358543934,44028,44123,44217,44311,44405,44499,44592,358644685,44778,44870,44962,45054,45146,45238,45329,358745420,45511,45601,45692,45782,45872,45961,46051,358846140,46229,46318,46406,46494,46583,46670,46758,358946846,46933,47020,47107,47193,47280,47366,47452,359047538,47623,47709,47794,47879,47964,48048,48133,359148217,48301,48385,48468,48552,48635,48718,48801,359248884,48966,49048,49131,49213,49294,49376,49458,359349539,49620,49701,49782,49862,49943,50023,50103,359450183,50263,50342,50422,50501,50580,50659,50738,359550816,50895,50973,51051,51129,51207,51285,51362,359651439,51517,51594,51671,51747,51824,51900,51977,359752053,52129,52205,52280,52356,52432,52507,52582,359852657,52732,52807,52881,52956,53030,53104,53178,359953252,53326,53400,53473,53546,53620,53693,53766,360053839,53911,53984,54056,54129,54201,54273,54345,360154417,54489,54560,54632,54703,54774,54845,54916,360254987,55058,55129,55199,55269,55340,55410,55480,360355550,55620,55689,55759,55828,55898,55967,56036,360456105,56174,56243,56311,56380,56448,56517,56585,360556653,56721,56789,56857,56924,56992,57059,57127,360657194,57261,57328,57395,57462,57529,57595,57662,360757728,57795,57861,57927,57993,58059,58125,58191,360858256,58322,58387,58453,58518,58583,58648,58713,360958778,58843,58908,58972,59037,59101,59165,59230,361059294,59358,59422,59486,59549,59613,59677,59740,361159804,59867,59930,59993,60056,60119,60182,60245,361260308,60370,60433,60495,60558,60620,60682,60744,361360806,60868,60930,60992,61054,61115,61177,61238,361461300,61361,61422,61483,61544,61605,61666,61727,361561788,61848,61909,61969,62030,62090,62150,62211,361662271,62331,62391,62450,62510,62570,62630,62689,361762749,62808,62867,62927,62986,63045,63104,63163,361863222,63281,63340,63398,63457,63515,63574,63632,361963691,63749,63807,63865,63923,63981,64039,64097,362064155,64212,64270,64328,64385,64443,64500,64557,362164614,64672,64729,64786,64843,64900,64956,65013,362265070,65126,65183,65239,65296,65352,65409,654653623};36243625const png_byte png_sRGB_delta[512] =3626{3627207,201,158,129,113,100,90,82,77,72,68,64,61,59,56,54,362852,50,49,47,46,45,43,42,41,40,39,39,38,37,36,36,362935,34,34,33,33,32,32,31,31,30,30,30,29,29,28,28,363028,27,27,27,27,26,26,26,25,25,25,25,24,24,24,24,363123,23,23,23,23,22,22,22,22,22,22,21,21,21,21,21,363221,20,20,20,20,20,20,20,20,19,19,19,19,19,19,19,363319,18,18,18,18,18,18,18,18,18,18,17,17,17,17,17,363417,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,363516,16,16,16,15,15,15,15,15,15,15,15,15,15,15,15,363615,15,15,15,14,14,14,14,14,14,14,14,14,14,14,14,363714,14,14,14,14,14,14,13,13,13,13,13,13,13,13,13,363813,13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,363912,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,364012,12,12,12,12,12,12,12,12,12,12,12,11,11,11,11,364111,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,364211,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,364311,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,364410,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,364510,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,364610,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,36479,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,36489,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,36499,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,36509,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,36518,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,36528,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,36538,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,36548,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,36558,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,36567,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,36577,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,36587,7,7,7,7,7,7,7,7,7,7,7,7,7,7,73659};3660#endif /* SIMPLIFIED READ/WRITE sRGB support */36613662/* SIMPLIFIED READ/WRITE SUPPORT */3663#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\3664defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)3665static int3666png_image_free_function(png_voidp argument)3667{3668png_imagep image = png_voidcast(png_imagep, argument);3669png_controlp cp = image->opaque;3670png_control c;36713672/* Double check that we have a png_ptr - it should be impossible to get here3673* without one.3674*/3675if (cp->png_ptr == NULL)3676return 0;36773678/* First free any data held in the control structure. */3679# ifdef PNG_STDIO_SUPPORTED3680if (cp->owned_file != 0)3681{3682FILE *fp = png_voidcast(FILE*, png_get_io_ptr(cp->png_ptr));3683cp->owned_file = 0;36843685/* Ignore errors here. */3686if (fp != NULL)3687{3688png_init_io(cp->png_ptr, NULL);3689(void)fclose(fp);3690}3691}3692# endif36933694/* Copy the control structure so that the original, allocated, version can be3695* safely freed. Notice that a png_error here stops the remainder of the3696* cleanup, but this is probably fine because that would indicate bad memory3697* problems anyway.3698*/3699c = *cp;3700image->opaque = &c;3701png_free(c.png_ptr, cp);37023703/* Then the structures, calling the correct API. */3704if (c.for_write != 0)3705{3706# ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED3707png_destroy_write_struct(&c.png_ptr, &c.info_ptr);3708# else3709png_error(c.png_ptr, "simplified write not supported");3710# endif3711}3712else3713{3714# ifdef PNG_SIMPLIFIED_READ_SUPPORTED3715png_destroy_read_struct(&c.png_ptr, &c.info_ptr, NULL);3716# else3717png_error(c.png_ptr, "simplified read not supported");3718# endif3719}37203721/* Success. */3722return 1;3723}37243725void PNGAPI3726png_image_free(png_imagep image)3727{3728/* Safely call the real function, but only if doing so is safe at this point3729* (if not inside an error handling context). Otherwise assume3730* png_safe_execute will call this API after the return.3731*/3732if (image != NULL && image->opaque != NULL &&3733image->opaque->error_buf == NULL)3734{3735/* Ignore errors here: */3736(void)png_safe_execute(image, png_image_free_function, image);3737image->opaque = NULL;3738}3739}37403741int /* PRIVATE */3742png_image_error(png_imagep image, png_const_charp error_message)3743{3744/* Utility to log an error. */3745png_safecat(image->message, (sizeof image->message), 0, error_message);3746image->warning_or_error |= PNG_IMAGE_ERROR;3747png_image_free(image);3748return 0;3749}37503751#ifdef PNG_STDIO_SUPPORTED3752typedef struct3753{3754png_structrp png_ptr;3755png_FILE_p fp;3756}3757png_image_init_io_struct;37583759static int3760image_init_io(png_voidp display)3761{3762png_image_init_io_struct *p =3763png_voidcast(png_image_init_io_struct*, display);37643765png_init_io(p->png_ptr, p->fp);3766return 1;3767}37683769int /* PRIVATE */3770png_image_init_io(png_imagep image, png_FILE_p fp)3771{3772png_image_init_io_struct s;37733774s.png_ptr = image->opaque->png_ptr;3775s.fp = fp;37763777return png_safe_execute(image, image_init_io, &s);3778}3779#endif /* STDIO */3780#endif /* SIMPLIFIED READ/WRITE */3781#endif /* READ || WRITE */378237833784