/* png.c - location for general purpose libpng functions * *Copyright(c)2018-2026CosminTruta *Copyright(c)1998-2002,2004,2006-2018GlennRanders-Pehrson *Copyright(c)1996-1997AndreasDilger *Copyright(c)1995-1996GuyEricSchalnat,Group42,Inc. * *Thiscodeisreleasedunderthelibpnglicense. *Forconditionsofdistributionanduse,seethedisclaimer *andlicenseinpng.h
*/
#include"pngpriv.h"
/* Generate a compiler error if there is an old png.h in the search path. */ typedef png_libpng_version_1_6_58 Your_png_h_is_not_version_1_6_58;
/* Sanity check the chunks definitions - PNG_KNOWN_CHUNKS from pngpriv.h and the *correspondingmacrodefinitions.Thiscausesacompiletimefailureif *somethingiswrongbutgeneratesnocode. * *(1)ThefirstcheckisthatthePNG_CHUNK(cHNK,index)'index'valuesmust *incrementfrom0tothelastvalue.
*/ #define PNG_CHUNK(cHNK, index) != (index) || ((index)+1)
#if0 PNG_KNOWN_CHUNKS < 0 # error PNG_KNOWN_CHUNKS chunk definitions are not in order #endif
#undef PNG_CHUNK
/* (2) The chunk name macros, png_cHNK, must all be valid and defined. Since *thisisapreprocessortestundefinedpp-tokenscomeoutaszeroandwill *failthistest.
*/ #define PNG_CHUNK(cHNK, index) !PNG_CHUNK_NAME_VALID(png_ ## cHNK) ||
#if PNG_KNOWN_CHUNKS 0 # error png_cHNK notdefinedfor some known cHNK #endif
#undef PNG_CHUNK
/* Tells libpng that we have already handled the first "num_bytes" bytes *ofthePNGfilesignature.IfthePNGdataisembeddedintoanother *streamwecansetnum_bytes=8sothatlibpngwillnotattempttoread *orwriteanyofthemagicbytesbeforeitstartsontheIHDR.
*/
#ifdef PNG_READ_SUPPORTED void PNGAPI
png_set_sig_bytes(png_structrp png_ptr, int num_bytes)
{ unsignedint nb = (unsignedint)num_bytes;
png_debug(1, "in png_set_sig_bytes");
if (png_ptr == NULL) return;
if (num_bytes < 0)
nb = 0;
if (nb > 8)
png_error(png_ptr, "Too many bytes for PNG signature");
png_ptr->sig_bytes = (png_byte)nb;
}
/* Checks whether the supplied bytes match the PNG signature. We allow *checkinglessthanthefull8-bytesignaturesothatthoseappsthat *alreadyreadthefirstfewbytesofafiletodeterminethefiletype *cansimplychecktheremainingbytesforextraassurance.Returns *anintegerlessthan,equalto,orgreaterthanzeroifsigisfound, *respectively,tobelessthan,tomatch,orbegreaterthanthecorrect *PNGsignature(thisisthesamebehaviorasstrcmp,memcmp,etc).
*/ int PNGAPI
png_sig_cmp(png_const_bytep sig, size_t start, size_t num_to_check)
{ staticconst png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
#ifdefined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) /* Function to allocate memory for zlib */
PNG_FUNCTION(voidpf /* PRIVATE */,
png_zalloc,(voidpf png_ptr, uInt items, uInt size),
PNG_ALLOCATED)
{
png_alloc_size_t num_bytes = size;
if (png_ptr == NULL) return NULL;
/* This check against overflow is vestigial, dating back from *theoldtimeswhenpng_zallocusedtobeanexportedfunction. *We'restillkeepingitherefornow,asanextra-cautious *preventionagainstprogrammingerrorsinsidezlib,althoughit *shouldratherbeadebug-timeassertioninstead.
*/ if (size != 0 && items >= (~(png_alloc_size_t)0) / size)
{
png_warning(png_voidcast(png_structrp, png_ptr), "Potential overflow in png_zalloc()"); return NULL;
}
/* Function to free memory for zlib */ void/* PRIVATE */
png_zfree(voidpf png_ptr, voidpf ptr)
{
png_free(png_voidcast(png_const_structrp,png_ptr), ptr);
}
/* Reset the CRC variable to 32 bits of 1's. Care must be taken *incaseCRCis>32bitstoleavethetopbits0.
*/ void/* PRIVATE */
png_reset_crc(png_structrp png_ptr)
{ /* The cast is safe because the crc is a 32-bit value. */
png_ptr->crc = (png_uint_32)crc32(0, Z_NULL, 0);
}
/* Calculate the CRC over a section of data. We can only pass as *muchdatatothisroutineasthelargestsinglebuffersize.We *alsocheckthatthisdatawillactuallybeusedbeforegoingtothe *troubleofcalculatingit.
*/ void/* PRIVATE */
png_calculate_crc(png_structrp png_ptr, png_const_bytep ptr, size_t length)
{ int need_crc = 1;
if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0)
{ if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
(PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
need_crc = 0;
}
/* 'uLong' is defined in zlib.h as unsigned long; this means that on some *systemsitisa64-bitvalue.crc32,however,returns32bitssothe *followingcastissafe.'uInt'maybenomorethan16bits,soitis *necessarytoperformaloophere.
*/ if (need_crc != 0 && length > 0)
{
uLong crc = png_ptr->crc; /* Should never issue a warning */
do
{
uInt safe_length = (uInt)length; #ifndef __COVERITY__ if (safe_length == 0)
safe_length = (uInt)-1; /* evil, but safe */ #endif
crc = crc32(crc, ptr, safe_length);
/* The following should never issue compiler warnings; if they do the *targetsystemhascharacteristicsthatwillprobablyviolateother *assumptionswithinthelibpngcode.
*/
ptr += safe_length;
length -= safe_length;
} while (length > 0);
/* And the following is always safe because the crc is only 32 bits. */
png_ptr->crc = (png_uint_32)crc;
}
}
/* Check a user supplied version number, called from both read and write *functionsthatcreateapng_struct.
*/ int
png_user_version_check(png_structrp png_ptr, png_const_charp user_png_ver)
{ /* Libpng versions 1.0.0 and later are binary compatible if the version *stringmatchesthroughthesecond'.';wemustrecompileany *applicationsthatuseanyolderlibraryversion.
*/
if (user_png_ver != NULL)
{ int i = -1; int found_dots = 0;
do
{
i++; if (user_png_ver[i] != PNG_LIBPNG_VER_STRING[i])
png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; if (user_png_ver[i] == '.')
found_dots++;
} while (found_dots < 2 && user_png_ver[i] != 0 &&
PNG_LIBPNG_VER_STRING[i] != 0);
}
pos = png_safecat(m, (sizeof m), pos, "Application built with libpng-");
pos = png_safecat(m, (sizeof m), pos, user_png_ver);
pos = png_safecat(m, (sizeof m), pos, " but running with ");
pos = png_safecat(m, (sizeof m), pos, PNG_LIBPNG_VER_STRING);
PNG_UNUSED(pos)
png_warning(png_ptr, m); #endif
return0;
}
/* Success return. */ return1;
}
/* Generic function to create a png_struct for either read or write - this *containsthecommoninitialization.
*/
PNG_FUNCTION(png_structp /* PRIVATE */,
png_create_png_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
png_malloc_ptr malloc_fn, png_free_ptr free_fn),
PNG_ALLOCATED)
{
png_struct create_struct; # ifdef PNG_SETJMP_SUPPORTED
jmp_buf create_jmp_buf; # endif
/* This temporary stack-allocated structure is used to provide a place to *buildenoughcontexttoallowtheuserprovidedmemoryallocator(ifany) *tobecalled.
*/
memset(&create_struct, 0, (sizeof create_struct));
# if PNG_USER_CHUNK_MALLOC_MAX > 0/* default to compile-time limit */
create_struct.user_chunk_malloc_max = PNG_USER_CHUNK_MALLOC_MAX;
/* No compile-time limit, so initialize to the system limit: */ # elif defined PNG_MAX_MALLOC_64K /* legacy system limit */
create_struct.user_chunk_malloc_max = 65536U;
# else/* modern system limit SIZE_MAX (C99) */
create_struct.user_chunk_malloc_max = PNG_SIZE_MAX; # endif # endif
/* The following two API calls simply set fields in png_struct, so it is safe *todothemnoweventhougherrorhandlingisnotyetsetup.
*/ # ifdef PNG_USER_MEM_SUPPORTED
png_set_mem_fn(&create_struct, mem_ptr, malloc_fn, free_fn); # else
PNG_UNUSED(mem_ptr)
PNG_UNUSED(malloc_fn)
PNG_UNUSED(free_fn) # endif
/* (*error_fn) can return control to the caller after the error_ptr is set, *thiswillresultinamemoryleakunlesstheerror_fndoessomething *extremelysophisticated.Thedesignlacksmeritbutisimplicitinthe *API.
*/
png_set_error_fn(&create_struct, error_ptr, error_fn, warn_fn);
# ifdef PNG_SETJMP_SUPPORTED if (!setjmp(create_jmp_buf)) # endif
{ # ifdef PNG_SETJMP_SUPPORTED /* Temporarily fake out the longjmp information until we have *successfullycompletedthisfunction.Thisonlyworksifwehave *setjmp()supportcompiledin,butitissafe-thisstuffshould *neverhappen.
*/
create_struct.jmp_buf_ptr = &create_jmp_buf;
create_struct.jmp_buf_size = 0; /*stack allocation*/
create_struct.longjmp_fn = longjmp; # endif /* Call the general version checker (shared with read and write code):
*/ if (png_user_version_check(&create_struct, user_png_ver) != 0)
{
png_structrp png_ptr = png_voidcast(png_structrp,
png_malloc_warn(&create_struct, (sizeof *png_ptr)));
if (png_ptr != NULL)
{ /* png_ptr->zstream holds a back-pointer to the png_struct, so *thiscanonlybedonenow:
*/
create_struct.zstream.zalloc = png_zalloc;
create_struct.zstream.zfree = png_zfree;
create_struct.zstream.opaque = png_ptr;
/* This is the successful return point */ return png_ptr;
}
}
}
/* A longjmp because of a bug in the application storage allocator or a *simplefailuretoallocatethepng_struct.
*/ return NULL;
}
/* Allocate the memory for an info_struct for the application. */
PNG_FUNCTION(png_infop,PNGAPI
png_create_info_struct,(png_const_structrp png_ptr),
PNG_ALLOCATED)
{
png_inforp info_ptr;
png_debug(1, "in png_create_info_struct");
if (png_ptr == NULL) return NULL;
/* Use the internal API that does not (or at least should not) error out, so *thatthiscallalwaysreturnsok.Theapplicationtypicallysetsupthe *errorhandling*after*creatingtheinfo_structbecausethisisthewayit *hasalwaysbeendonein'example.c'.
*/
info_ptr = png_voidcast(png_inforp, png_malloc_base(png_ptr,
(sizeof *info_ptr)));
if (info_ptr != NULL)
memset(info_ptr, 0, (sizeof *info_ptr));
return info_ptr;
}
/* This function frees the memory associated with a single info struct. *Normally,onewoulduseeitherpng_destroy_read_struct()or *png_destroy_write_struct()tofreeaninfostruct,butthismaybe *usefulforsomeapplications.Fromlibpng1.6.0thisfunctionisalsoused *internallytoimplementthepng_inforeleasepartofthe'struct'destroy *APIs.Thisensuresthatallpossibleapproachesfreethesamedata(allof *it).
*/ void PNGAPI
png_destroy_info_struct(png_const_structrp png_ptr, png_infopp info_ptr_ptr)
{
png_inforp info_ptr = NULL;
png_debug(1, "in png_destroy_info_struct");
if (png_ptr == NULL) return;
if (info_ptr_ptr != NULL)
info_ptr = *info_ptr_ptr;
if (info_ptr != NULL)
{ /* Do this first in case of an error below; if the app implements its own *memorymanagementthiscanleadtopng_freecallingpng_error,which *willabortthisroutineandreturncontroltotheapperrorhandler. *Aninfiniteloopmayresultifitthentriestofreethesameinfo *ptr.
*/
*info_ptr_ptr = NULL;
/* Initialize the info structure. This is now an internal function (0.89) *andapplicationsusingitareurgedtousepng_create_info_struct() *instead.Usedeprecatedin1.6.0,internaluseremoved(usedinternallyit *isjustamemset). * *NOTE:itisalmostinconceivablethatthisAPIisusedbecauseitbypasses *theuser-memorymechanismandtheusererrorhandling/warningmechanismsin *thosecaseswhereitdoesanythingotherthanamemset.
*/
PNG_FUNCTION(void,PNGAPI
png_info_init_3,(png_infopp ptr_ptr, size_t png_info_struct_size),
PNG_DEPRECATED)
{
png_inforp info_ptr = *ptr_ptr;
png_debug(1, "in png_info_init_3");
if (info_ptr == NULL) return;
if ((sizeof (png_info)) > png_info_struct_size)
{
*ptr_ptr = NULL; /* The following line is why this API should not be used: */
free(info_ptr);
info_ptr = png_voidcast(png_inforp, png_malloc_base(NULL,
(sizeof *info_ptr))); if (info_ptr == NULL) return;
*ptr_ptr = info_ptr;
}
/* Set everything to 0 */
memset(info_ptr, 0, (sizeof *info_ptr));
}
void PNGAPI
png_data_freer(png_const_structrp png_ptr, png_inforp info_ptr, int freer, png_uint_32 mask)
{
png_debug(1, "in png_data_freer");
if (png_ptr == NULL || info_ptr == NULL) return;
if (freer == PNG_DESTROY_WILL_FREE_DATA)
info_ptr->free_me |= mask;
else
png_error(png_ptr, "Unknown freer parameter in png_data_freer");
}
void PNGAPI
png_free_data(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 mask, int num)
{
png_debug(1, "in png_free_data");
if (png_ptr == NULL || info_ptr == NULL) return;
#ifdef PNG_TEXT_SUPPORTED /* Free text item num or (if num == -1) all text items */ if (info_ptr->text != NULL &&
((mask & PNG_FREE_TEXT) & info_ptr->free_me) != 0)
{ if (num != -1)
{
png_free(png_ptr, info_ptr->text[num].key);
info_ptr->text[num].key = NULL;
}
else
{ int i;
for (i = 0; i < info_ptr->num_text; i++)
png_free(png_ptr, info_ptr->text[i].key);
#ifdef PNG_sPLT_SUPPORTED /* Free a given sPLT entry, or (if num == -1) all sPLT entries */ if (info_ptr->splt_palettes != NULL &&
((mask & PNG_FREE_SPLT) & info_ptr->free_me) != 0)
{ if (num != -1)
{
png_free(png_ptr, info_ptr->splt_palettes[num].name);
png_free(png_ptr, info_ptr->splt_palettes[num].entries);
info_ptr->splt_palettes[num].name = NULL;
info_ptr->splt_palettes[num].entries = NULL;
}
else
{ int i;
for (i = 0; i < info_ptr->splt_palettes_num; i++)
{
png_free(png_ptr, info_ptr->splt_palettes[i].name);
png_free(png_ptr, info_ptr->splt_palettes[i].entries);
}
/* This function returns a pointer to the io_ptr associated with the user *functions.Theapplicationshouldfreeanymemoryassociatedwiththis *pointerbeforepng_write_destroy()orpng_read_destroy()arecalled.
*/
png_voidp PNGAPI
png_get_io_ptr(png_const_structrp png_ptr)
{ if (png_ptr == NULL) return NULL;
return png_ptr->io_ptr;
}
#ifdefined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) # ifdef PNG_STDIO_SUPPORTED /* Initialize the default input/output functions for the PNG file. If you *useyourownreadorwriteroutines,youcancalleitherpng_set_read_fn() *orpng_set_write_fn()insteadofpng_init_io().Ifyouhavedefined *PNG_NO_STDIOorotherwisedisabledPNG_STDIO_SUPPORTED,youmustusea *functionofyourownbecause"FILE*"isn'tnecessarilyavailable.
*/ void PNGAPI
png_init_io(png_structrp png_ptr, FILE *fp)
{
png_debug(1, "in png_init_io");
# if PNG_LIBPNG_VER < 10700 /* To do: remove the following from libpng-1.7 */ /* Original API that uses a private buffer in png_struct. *Deprecatedbecauseitcausespng_structtocarryaspurioustemporary *buffer(png_struct::time_buffer),bettertohavethecallerpassthisin.
*/
png_const_charp PNGAPI
png_convert_to_rfc1123(png_structrp png_ptr, png_const_timep ptime)
{ if (png_ptr != NULL)
{ /* The only failure above if png_ptr != NULL is from an invalid ptime */ if (png_convert_to_rfc1123_buffer(png_ptr->time_buffer, ptime) == 0)
png_warning(png_ptr, "Ignoring invalid time value");
/* The following return the library version as a short string in the *format1.0.0through99.99.99zz.Togettheversionof*.hfiles *usedwithyourapplication,printoutPNG_LIBPNG_VER_STRING,which *isdefinedinpng.h. *Note:nowthereisnodifferencebetweenpng_get_libpng_ver()and *png_get_header_ver().Duetotheversion_nn_nn_nntypedefguard, *itisguaranteedthatpng.cusesthecorrectversionofpng.h.
*/
png_const_charp PNGAPI
png_get_libpng_ver(png_const_structrp png_ptr)
{ /* Version of *.c files used when building libpng */ return png_get_header_ver(png_ptr);
}
png_const_charp PNGAPI
png_get_header_ver(png_const_structrp png_ptr)
{ /* Version of *.h files used when building libpng */
PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */ return PNG_LIBPNG_VER_STRING;
}
png_const_charp PNGAPI
png_get_header_version(png_const_structrp png_ptr)
{ /* Returns longer string containing both version and date */
PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */ #ifdef __STDC__ return PNG_HEADER_VERSION_STRING # ifndef PNG_READ_SUPPORTED " (NO READ SUPPORT)" # endif
PNG_STRING_NEWLINE; #else return PNG_HEADER_VERSION_STRING; #endif
}
#ifdef PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED /* NOTE: this routine is not used internally! */ /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth *largeofpng_color.Thisletsgrayscaleimagesbetreatedas *paletted.Mostusefulforgammacorrectionandsimplification *ofcode.ThisAPIisnotusedinternally.
*/ void PNGAPI
png_build_grayscale_palette(int bit_depth, png_colorp palette)
{ int num_palette; int color_inc; int i; int v;
png_debug(1, "in png_do_build_grayscale_palette");
for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
{
palette[i].red = (png_byte)(v & 0xff);
palette[i].green = (png_byte)(v & 0xff);
palette[i].blue = (png_byte)(v & 0xff);
}
} #endif
#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED int PNGAPI
png_handle_as_unknown(png_const_structrp png_ptr, png_const_bytep chunk_name)
{ /* Check chunk_name and return "keep" value if it's on the list, else 0 */
png_const_bytep p, p_end;
p_end = png_ptr->chunk_list;
p = p_end + png_ptr->num_chunk_list*5; /* beyond end */
/* The code is the fifth byte after each four byte string. Historically this *codewasalwayssearchedfromtheendofthelist,thisisnolonger *necessarybecausethe'set'routinehandlesduplicateentriescorrectly.
*/ do/* num_chunk_list > 0, so at least one */
{
p -= 5;
if (memcmp(chunk_name, p, 4) == 0) return p[4];
} while (p > p_end);
/* This means that known chunks should be processed and unknown chunks should *behandledaccordingtothevalueofpng_ptr->unknown_default;thiscanbe *confusingbecause,asaresult,therearetwolevelsofdefaultingfor *unknownchunks.
*/ return PNG_HANDLE_CHUNK_AS_DEFAULT;
}
#ifdef PNG_READ_SUPPORTED /* This function, added to libpng-1.0.6g, is untested. */ int PNGAPI
png_reset_zstream(png_structrp png_ptr)
{ if (png_ptr == NULL) return Z_STREAM_ERROR;
/* WARNING: this resets the window bits to the maximum! */ return inflateReset(&png_ptr->zstream);
} #endif/* READ */
/* This function was added to libpng-1.0.7 */
png_uint_32 PNGAPI
png_access_version_number(void)
{ /* Version of *.c files used when building libpng */ return (png_uint_32)PNG_LIBPNG_VER;
}
#ifdefined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) /* Ensure that png_ptr->zstream.msg holds some appropriate error message string. *Ifitdoesn't'ret'isusedtosetittosomethingappropriate,evenincases *likeZ_OKorZ_STREAM_ENDwheretheerrorcodeisapparentlyasuccesscode.
*/ void/* PRIVATE */
png_zstream_error(png_structrp png_ptr, int ret)
{ /* Translate 'ret' into an appropriate error string, priority is given to the *oneinzstreamifset.Thisalwaysreturnsastring,evenincaseslike *Z_OKorZ_STREAM_ENDwheretheerrorcodeisasuccesscode.
*/ if (png_ptr->zstream.msg == NULL) switch (ret)
{ default: case Z_OK:
png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected zlib return code"); break;
case Z_STREAM_END: /* Normal exit */
png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected end of LZ stream"); break;
case Z_NEED_DICT: /* This means the deflate stream did not have a dictionary; this *indicatesabogusPNG.
*/
png_ptr->zstream.msg = PNGZ_MSG_CAST("missing LZ dictionary"); break;
case Z_ERRNO: /* gz APIs only: should not happen */
png_ptr->zstream.msg = PNGZ_MSG_CAST("zlib IO error"); break;
case Z_STREAM_ERROR: /* internal libpng error */
png_ptr->zstream.msg = PNGZ_MSG_CAST("bad parameters to zlib"); break;
case Z_DATA_ERROR:
png_ptr->zstream.msg = PNGZ_MSG_CAST("damaged LZ stream"); break;
case Z_MEM_ERROR:
png_ptr->zstream.msg = PNGZ_MSG_CAST("insufficient memory"); break;
case Z_BUF_ERROR: /* End of input or output; not a problem if the caller is doing *incrementalreadorwrite.
*/
png_ptr->zstream.msg = PNGZ_MSG_CAST("truncated"); break;
case Z_VERSION_ERROR:
png_ptr->zstream.msg = PNGZ_MSG_CAST("unsupported zlib version"); break;
case PNG_UNEXPECTED_ZLIB_RETURN: /* Compile errors here mean that zlib now uses the value co-opted in *pngpriv.hforPNG_UNEXPECTED_ZLIB_RETURN;updatetheswitchabove *andchangepngpriv.h.Notethatthismessageis"...return", *whereasthedefault/Z_OKoneis"...returncode".
*/
png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected zlib return"); break;
}
}
#ifdef PNG_COLORSPACE_SUPPORTED static png_int_32
png_fp_add(png_int_32 addend0, png_int_32 addend1, int *error)
{ /* Safely add two fixed point values setting an error flag and returning 0.5 *onoverflow. *IMPLEMENTATIONNOTE:ANSIrequiressignedoverflownottooccur,therefore *relyingonadditionoftwopositivevaluesproducinganegativeoneisnot *safe.
*/ if (addend0 > 0)
{ if (0x7fffffff - addend0 >= addend1) return addend0+addend1;
} elseif (addend0 < 0)
{ if (-0x7fffffff - addend0 <= addend1) return addend0+addend1;
} else return addend1;
*error = 1; return PNG_FP_1/2;
}
static png_int_32
png_fp_sub(png_int_32 addend0, png_int_32 addend1, int *error)
{ /* As above but calculate addend0-addend1. */ if (addend1 > 0)
{ if (-0x7fffffff + addend1 <= addend0) return addend0-addend1;
} elseif (addend1 < 0)
{ if (0x7fffffff + addend1 >= addend0) return addend0-addend1;
} else return addend0;
*error = 1; return PNG_FP_1/2;
}
staticint
png_safe_add(png_int_32 *addend0_and_result, png_int_32 addend1,
png_int_32 addend2)
{ /* Safely add three integers. Returns 0 on success, 1 on overflow. Does not *settheresultonoverflow.
*/ int error = 0; int result = png_fp_add(*addend0_and_result,
png_fp_add(addend1, addend2, &error),
&error); if (!error) *addend0_and_result = result; return error;
}
/* Added at libpng-1.5.5 to support read and write of true CIEXYZ values for *cHRM,asopposedtousingchromaticities.TheseinternalAPIsreturn *non-zeroonaparametererror.TheX,YandZvaluesarerequiredtobe *positiveandlessthan1.0.
*/ int/* PRIVATE */
png_xy_from_XYZ(png_xy *xy, const png_XYZ *XYZ)
{ /* NOTE: returns 0 on success, 1 means error. */
png_int_32 d, dred, dgreen, dblue, dwhite, whiteX, whiteY;
/* 'd' in each of the blocks below is just X+Y+Z for each component, *x,yandzareX,Y,Z/(X+Y+Z).
*/
d = XYZ->red_X; if (png_safe_add(&d, XYZ->red_Y, XYZ->red_Z)) return1;
dred = d; if (png_muldiv(&xy->redx, XYZ->red_X, PNG_FP_1, dred) == 0) return1; if (png_muldiv(&xy->redy, XYZ->red_Y, PNG_FP_1, dred) == 0) return1;
d = XYZ->green_X; if (png_safe_add(&d, XYZ->green_Y, XYZ->green_Z)) return1;
dgreen = d; if (png_muldiv(&xy->greenx, XYZ->green_X, PNG_FP_1, dgreen) == 0) return1; if (png_muldiv(&xy->greeny, XYZ->green_Y, PNG_FP_1, dgreen) == 0) return1;
d = XYZ->blue_X; if (png_safe_add(&d, XYZ->blue_Y, XYZ->blue_Z)) return1;
dblue = d; if (png_muldiv(&xy->bluex, XYZ->blue_X, PNG_FP_1, dblue) == 0) return1; if (png_muldiv(&xy->bluey, XYZ->blue_Y, PNG_FP_1, dblue) == 0) return1;
/* The reference white is simply the sum of the end-point (X,Y,Z) vectors so *thefollowingcalculates(X+Y+Z)ofthereferencewhite(mediawhite, *encodingwhite)itself:
*/
d = dblue; if (png_safe_add(&d, dred, dgreen)) return1;
dwhite = d;
/* Find the white X,Y values from the sum of the red, green and blue X,Y *values.
*/
d = XYZ->red_X; if (png_safe_add(&d, XYZ->green_X, XYZ->blue_X)) return1;
whiteX = d;
d = XYZ->red_Y; if (png_safe_add(&d, XYZ->green_Y, XYZ->blue_Y)) return1;
whiteY = d;
if (png_muldiv(&xy->whitex, whiteX, PNG_FP_1, dwhite) == 0) return1; if (png_muldiv(&xy->whitey, whiteY, PNG_FP_1, dwhite) == 0) return1;
/* By the argument above overflow should be impossible here, however the *codenowsimplyreturnsafailurecode.Thexysubtractsinthe *argumentstopng_muldivare*not*checkedforoverflowbecausethe *checksatthestartguaranteetheyareintherange0..110000and *png_fixed_pointisa32-bitsignednumber.
*/ if (png_muldiv(&left, xy->greenx-xy->bluex, xy->redy - xy->bluey, 8) == 0) return1; if (png_muldiv(&right, xy->greeny-xy->bluey, xy->redx - xy->bluex, 8) == 0) return1;
denominator = png_fp_sub(left, right, &error); if (error) return1;
/* Now find the red numerator. */ if (png_muldiv(&left, xy->greenx-xy->bluex, xy->whitey-xy->bluey, 8) == 0) return1; if (png_muldiv(&right, xy->greeny-xy->bluey, xy->whitex-xy->bluex, 8) == 0) return1;
/* Overflow is possible here and it indicates an extreme set of PNG cHRM *chunkvalues.Thiscalculationactuallyreturnsthereciprocalofthe *scalevaluebecausethisallowsustodelaythemultiplicationof *white-yintothedenominator,whichtendstoproduceasmallnumber.
*/ if (png_muldiv(&red_inverse, xy->whitey, denominator,
png_fp_sub(left, right, &error)) == 0 || error ||
red_inverse <= xy->whitey /* r+g+b scales = white scale */) return1;
/* Similarly for green_inverse: */ if (png_muldiv(&left, xy->redy-xy->bluey, xy->whitex-xy->bluex, 8) == 0) return1; if (png_muldiv(&right, xy->redx-xy->bluex, xy->whitey-xy->bluey, 8) == 0) return1; if (png_muldiv(&green_inverse, xy->whitey, denominator,
png_fp_sub(left, right, &error)) == 0 || error ||
green_inverse <= xy->whitey) return1;
/* And the blue scale, the checks above guarantee this can't overflow but *itcanstillproduce0forextremecHRMvalues.
*/
blue_scale = png_fp_sub(png_fp_sub(png_reciprocal(xy->whitey),
png_reciprocal(red_inverse), &error),
png_reciprocal(green_inverse), &error); if (error || blue_scale <= 0) return1;
}
/* And fill in the png_XYZ. Again the subtracts are safe because of the *checksonthexyvaluesatthestart(thesubtractsjustcalculatethe *correspondingzvalues.)
*/ if (png_muldiv(&XYZ->red_X, xy->redx, PNG_FP_1, red_inverse) == 0) return1; if (png_muldiv(&XYZ->red_Y, xy->redy, PNG_FP_1, red_inverse) == 0) return1; if (png_muldiv(&XYZ->red_Z, PNG_FP_1 - xy->redx - xy->redy, PNG_FP_1,
red_inverse) == 0) return1;
if (png_muldiv(&XYZ->green_X, xy->greenx, PNG_FP_1, green_inverse) == 0) return1; if (png_muldiv(&XYZ->green_Y, xy->greeny, PNG_FP_1, green_inverse) == 0) return1; if (png_muldiv(&XYZ->green_Z, PNG_FP_1 - xy->greenx - xy->greeny, PNG_FP_1,
green_inverse) == 0) return1;
if (png_muldiv(&XYZ->blue_X, xy->bluex, blue_scale, PNG_FP_1) == 0) return1; if (png_muldiv(&XYZ->blue_Y, xy->bluey, blue_scale, PNG_FP_1) == 0) return1; if (png_muldiv(&XYZ->blue_Z, PNG_FP_1 - xy->bluex - xy->bluey, blue_scale,
PNG_FP_1) == 0) return1;
/* Encoded value of D50 as an ICC XYZNumber. From the ICC 2010 spec the value *isXYZ(0.9642,1.0,0.8249),whichscalesto: * *(63189.8112,65536,54060.6464)
*/ staticconst png_byte D50_nCIEXYZ[12] =
{ 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d };
/* This needs to be here because the 'normal' check is in *png_decompress_chunk,yetthishappensaftertheattemptto *png_malloc_basetherequireddata.Weonlyneedthisonread;onwrite *thecallersuppliestheprofilebuffersolibpngdoesn'tallocateit.See *thecalltoicc_check_lengthbelow(thewritecase).
*/ if (profile_length > png_chunk_max(png_ptr)) return png_icc_profile_error(png_ptr, name, profile_length, "profile too long");
return1;
}
int/* PRIVATE */
png_icc_check_header(png_const_structrp png_ptr, png_const_charp name,
png_uint_32 profile_length,
png_const_bytep profile/* first 132 bytes only */, int color_type)
{
png_uint_32 temp;
/* Length check; this cannot be ignored in this code because profile_length *isusedlatertocheckthetagtable,soeveniftheprofileseemsover *longprofile_lengthfromthecallermustbecorrect.Thecallercanfix *thisuponreadorwritebyjustpassingintheprofileheaderlength.
*/
temp = png_get_uint_32(profile); if (temp != profile_length) return png_icc_profile_error(png_ptr, name, temp, "length does not match profile");
temp = png_get_uint_32(profile+128); /* tag count: 12 bytes/tag */ if (temp > 357913930 || /* (2^32-4-132)/12: maximum possible tag count */
profile_length < 132+12*temp) /* truncated tag table */ return png_icc_profile_error(png_ptr, name, temp, "tag count too large");
/* The 'intent' must be valid or we can't store it, ICC limits the intent to *16bits.
*/
temp = png_get_uint_32(profile+64); if (temp >= 0xffff) /* The ICC limit */ return png_icc_profile_error(png_ptr, name, temp, "invalid rendering intent");
/* This is just a warning because the profile may be valid in future *versions.
*/ if (temp >= PNG_sRGB_INTENT_LAST)
(void)png_icc_profile_error(png_ptr, name, temp, "intent outside defined range");
/* At this point the tag table can't be checked because it hasn't necessarily *beenloaded;however,variousheaderfieldscanbechecked.Thesechecks *areforvaluespermittedbythePNGspecinanICCprofile;thePNGspec *restrictstheprofilesthatcanbepassedinaniCCPchunk(theymustbe *appropriatetoprocessingPNGdata!)
*/
/* Data checks (could be skipped). These checks must be independent of the *versionnumber;however,theversionnumberdoesn'taccommodatechangesin *theheaderfields(justtheknowntagsandtheinterpretationofthe *data.)
*/
temp = png_get_uint_32(profile+36); /* signature 'ascp' */ if (temp != 0x61637370) return png_icc_profile_error(png_ptr, name, temp, "invalid signature");
/* Currently the PCS illuminant/adopted white point (the computational *whitepoint)arerequiredtobeD50, *howevertheprofilecontainsarecordoftheilluminantsoperhapsICC *expectstobeabletochangethisinthefuture(despitetherationalein *theintroductionforusingafixedPCSadoptedwhite.)Consequentlythe *followingisjustawarning.
*/ if (memcmp(profile+68, D50_nCIEXYZ, 12) != 0)
(void)png_icc_profile_error(png_ptr, name, 0/*no tag value*/, "PCS illuminant is not D50");
/* The PNG spec requires this: *"IftheiCCPchunkispresent,theimagesamplesconformtothecolour *spacerepresentedbytheembeddedICCprofileasdefinedbythe *InternationalColorConsortium[ICC].ThecolourspaceoftheICCprofile *shallbeanRGBcolourspaceforcolourimages(PNGcolourtypes2,3,and *6),oragreyscalecolourspaceforgreyscaleimages(PNGcolourtypes0 *and4)." * *Thischeckingcodeensurestheembeddedprofile(oneitherreadorwrite) *conformstothespecificationrequirements.NoticethatanICC'gray' *color-spaceprofilecontainstheinformationtotransformthemonochrome *datatoXYZorL*a*b(accordingtowhichPCStheprofileuses)andthis *shouldbeusedinpreferencetothestandardlibpngKchannelreplication *intoR,GandBchannels. * *PreviouslyitwassuggestedthatanRGBprofileongrayscaledatacouldbe *handled.HoweveritisclearthatusinganRGBprofileinthiscontext *mustbeanerror-thereisnospecificationofwhatitmeans.Thusitis *almostcertainlymorecorrecttoignoretheprofile.
*/
temp = png_get_uint_32(profile+16); /* data colour space field */ switch (temp)
{ case0x52474220: /* 'RGB ' */ if ((color_type & PNG_COLOR_MASK_COLOR) == 0) return png_icc_profile_error(png_ptr, name, temp, "RGB color space not permitted on grayscale PNG"); break;
case0x47524159: /* 'GRAY' */ if ((color_type & PNG_COLOR_MASK_COLOR) != 0) return png_icc_profile_error(png_ptr, name, temp, "Gray color space not permitted on RGB PNG"); break;
/* It is up to the application to check that the profile class matches the *applicationrequirements;thespecprovidesnoguidance,butit'spretty *weirdiftheprofileisnotscanner('scnr'),monitor('mntr'),printer *('prtr')or'spac'(forgenericcolorspaces).Issueawarninginthese *cases.Issueanerrorfordevicelinkorabstractprofiles-thesedon't *containtherecordsnecessarytotransformthecolor-spacetoanything *otherthanthetargetdevice(andnoteventhatforanabstractprofile). *Profilesoftheseclassesmaynotbeembeddedinimages.
*/
temp = png_get_uint_32(profile+12); /* profile/device class */ switch (temp)
{ case0x73636e72: /* 'scnr' */ case0x6d6e7472: /* 'mntr' */ case0x70727472: /* 'prtr' */ case0x73706163: /* 'spac' */ /* All supported */ break;
case0x61627374: /* 'abst' */ /* May not be embedded in an image */ return png_icc_profile_error(png_ptr, name, temp, "invalid embedded Abstract ICC profile");
case0x6c696e6b: /* 'link' */ /* DeviceLink profiles cannot be interpreted in a non-device specific *fashion,ifanappusestheAToB0Tagintheprofiletheresultsare *undefinedunlesstheresultissenttotheintendeddevice, *thereforeaDeviceLinkprofileshouldnotbefoundembeddedina *PNG.
*/ return png_icc_profile_error(png_ptr, name, temp, "unexpected DeviceLink ICC profile class");
case0x6e6d636c: /* 'nmcl' */ /* A NamedColor profile is also device specific, however it doesn't *containanAToB0tagthatisopentomisinterpretation.Almost *certainlyitwillfailthetestsbelow.
*/
(void)png_icc_profile_error(png_ptr, name, temp, "unexpected NamedColor ICC profile class"); break;
default: /* To allow for future enhancements to the profile accept unrecognized *profileclasseswithawarning,thesethenhitthetestbelowonthe *tagcontenttoensuretheyarebackwardcompatiblewithoneofthe *understoodprofiles.
*/
(void)png_icc_profile_error(png_ptr, name, temp, "unrecognized ICC profile class"); break;
}
/* For any profile other than a device link one the PCS must be encoded *eitherinXYZorLab.
*/
temp = png_get_uint_32(profile+20); switch (temp)
{ case0x58595a20: /* 'XYZ ' */ case0x4c616220: /* 'Lab ' */ break;
int/* PRIVATE */
png_icc_check_tag_table(png_const_structrp png_ptr, png_const_charp name,
png_uint_32 profile_length,
png_const_bytep profile /* header plus whole tag table */)
{
png_uint_32 tag_count = png_get_uint_32(profile+128);
png_uint_32 itag;
png_const_bytep tag = profile+132; /* The first tag */
/* First scan all the tags in the table and add bits to the icc_info value *(temporarilyin'tags').
*/ for (itag=0; itag < tag_count; ++itag, tag += 12)
{
png_uint_32 tag_id = png_get_uint_32(tag+0);
png_uint_32 tag_start = png_get_uint_32(tag+4); /* must be aligned */
png_uint_32 tag_length = png_get_uint_32(tag+8);/* not padded */
/* The ICC specification does not exclude zero length tags, therefore the *startmightactuallybeanywhereifthereisnodata,butthiswouldbe *aclearabuseoftheintentofthestandardsothestartischeckedfor *beinginrange.Alldefinedtagtypeshavean8byteheader-a4byte *typesignaturethen0.
*/
/* This is a hard error; potentially it can cause read outside the *profile.
*/ if (tag_start > profile_length || tag_length > profile_length - tag_start) return png_icc_profile_error(png_ptr, name, tag_id, "ICC profile tag outside profile");
if ((tag_start & 3) != 0)
{ /* CNHP730S.icc shipped with Microsoft Windows 64 violates this; it is *onlyawarningherebecauselibpngdoesnotcareaboutthe *alignment.
*/
(void)png_icc_profile_error(png_ptr, name, tag_id, "ICC profile tag start not a multiple of 4");
}
}
void/* PRIVATE */
png_set_rgb_coefficients(png_structrp png_ptr)
{ /* Set the rgb_to_gray coefficients from the colorspace if available. Note *that'_set'meansthatpng_rgb_to_graywascalled**and**itsuccessfully *setupthecoefficients.
*/ if (png_ptr->rgb_to_gray_coefficients_set == 0)
{ # if check_chromaticities
png_XYZ xyz;
if (have_chromaticities(png_ptr) &&
png_XYZ_from_xy(&xyz, &png_ptr->chromaticities) == 0)
{ /* png_set_rgb_to_gray has not set the coefficients, get them from the *Y*valuesofthecolorspacecolorants.
*/
png_fixed_point r = xyz.red_Y;
png_fixed_point g = xyz.green_Y;
png_fixed_point b = xyz.blue_Y;
png_fixed_point total = r+g+b;
if (total > 0 &&
r >= 0 && png_muldiv(&r, r, 32768, total) && r >= 0 && r <= 32768 &&
g >= 0 && png_muldiv(&g, g, 32768, total) && g >= 0 && g <= 32768 &&
b >= 0 && png_muldiv(&b, b, 32768, total) && b >= 0 && b <= 32768 &&
r+g+b <= 32769)
{ /* We allow 0 coefficients here. r+g+b may be 32769 if two or *allofthecoefficientswereroundedup.Handlethisby *reducingthe*largest*coefficientby1;thismatchesthe *approachusedforthedefaultcoefficientsinpngrtran.c
*/ int add = 0;
void/* PRIVATE */
png_check_IHDR(png_const_structrp png_ptr,
png_uint_32 width, png_uint_32 height, int bit_depth, int color_type, int interlace_type, int compression_type, int filter_type)
{ int error = 0;
/* Check for width and height valid values */ if (width == 0)
{
png_warning(png_ptr, "Image width is zero in IHDR");
error = 1;
}
if (width > PNG_UINT_31_MAX)
{
png_warning(png_ptr, "Invalid image width in IHDR");
error = 1;
}
/* The bit mask on the first line below must be at least as big as a *png_uint_32."~7U"isnotadequateon16-bitsystemsbecauseitwill *beanunsigned16-bitvalue.Castingto(png_alloc_size_t)makesthe *typeoftheresultatleastasbit(inbits)astheRHSofthe>operator *whichalsoavoidsacommonwarningon64-bitsystemsthatthecomparison *of(png_uint_32)againsttheconstantvalueontheRHSwillalwaysbe *false.
*/ if (((width + 7) & ~(png_alloc_size_t)7) >
(((PNG_SIZE_MAX
- 48/* big_row_buf hack */
- 1) /* filter byte */
/ 8) /* 8-byte RGBA pixels */
- 1)) /* extra max_pixel_depth pad */
{ /* The size of the row must be within the limits of this architecture. *Becausethereadcodecanperformarbitrarytransformationsthe *maximumsizeischeckedhere.Becausethecodeinpng_read_start_row *addsextraspace"forsafety'ssake"inseveralplacesaconservative *limitisusedhere. * *NOTE:itwouldbefarbettertocheckthesizethatisactuallyused, *buttheeffectintherealworldisminorandthechangesaremore *extensive,thereforemuchmoredangerousandmuchmoredifficultto *writeinawaythatavoidscompilerwarnings.
*/
png_warning(png_ptr, "Image width is too large for this architecture");
error = 1;
}
#ifdef PNG_SET_USER_LIMITS_SUPPORTED if (width > png_ptr->user_width_max) #else if (width > PNG_USER_WIDTH_MAX) #endif
{
png_warning(png_ptr, "Image width exceeds user limit in IHDR");
error = 1;
}
if (height == 0)
{
png_warning(png_ptr, "Image height is zero in IHDR");
error = 1;
}
if (height > PNG_UINT_31_MAX)
{
png_warning(png_ptr, "Invalid image height in IHDR");
error = 1;
}
#ifdef PNG_SET_USER_LIMITS_SUPPORTED if (height > png_ptr->user_height_max) #else if (height > PNG_USER_HEIGHT_MAX) #endif
{
png_warning(png_ptr, "Image height exceeds user limit in IHDR");
error = 1;
}
/* Check other values */ if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
bit_depth != 8 && bit_depth != 16)
{
png_warning(png_ptr, "Invalid bit depth in IHDR");
error = 1;
}
if (color_type < 0 || color_type == 1 ||
color_type == 5 || color_type > 6)
{
png_warning(png_ptr, "Invalid color type in IHDR");
error = 1;
}
if (interlace_type >= PNG_INTERLACE_LAST)
{
png_warning(png_ptr, "Unknown interlace method in IHDR");
error = 1;
}
if (compression_type != PNG_COMPRESSION_TYPE_BASE)
{
png_warning(png_ptr, "Unknown compression method in IHDR");
error = 1;
}
#ifdef PNG_MNG_FEATURES_SUPPORTED /* Accept filter_method 64 (intrapixel differencing) only if *1.LibpngwascompiledwithPNG_MNG_FEATURES_SUPPORTEDand *2.LibpngdidnotreadaPNGsignature(thisfilter_methodisonly *usedinPNGdatastreamsthatareembeddedinMNGdatastreams)and *3.Theapplicationcalledpng_permit_mng_featureswithamaskthat *includedPNG_FLAG_MNG_FILTER_64and *4.Thefilter_methodis64and *5.Thecolor_typeisRGBorRGBA
*/ if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 &&
png_ptr->mng_features_permitted != 0)
png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");
if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0)
{
png_warning(png_ptr, "Invalid filter method in IHDR");
error = 1;
}
}
#else if (filter_type != PNG_FILTER_TYPE_BASE)
{
png_warning(png_ptr, "Unknown filter method in IHDR");
error = 1;
} #endif
if (error == 1)
png_error(png_ptr, "Invalid IHDR data");
}
#ifdefined(PNG_sCAL_SUPPORTED) || defined(PNG_pCAL_SUPPORTED) /* ASCII to fp functions */ /* Check an ASCII formatted floating point value, see the more detailed *commentsinpngpriv.h
*/ /* The following is used internally to preserve the sticky flags */ #define png_fp_add(state, flags) ((state) |= (flags)) #define png_fp_set(state, value) ((state) = (value) | ((state) & PNG_FP_STICKY))
int/* PRIVATE */
png_check_fp_number(png_const_charp string, size_t size, int *statep,
size_t *whereami)
{ int state = *statep;
size_t i = *whereami;
while (i < size)
{ int type; /* First find the type of the next character */ switch (string[i])
{ case43: type = PNG_FP_SAW_SIGN; break; case45: type = PNG_FP_SAW_SIGN + PNG_FP_NEGATIVE; break; case46: type = PNG_FP_SAW_DOT; break; case48: type = PNG_FP_SAW_DIGIT; break; case49: case50: case51: case52: case53: case54: case55: case56: case57: type = PNG_FP_SAW_DIGIT + PNG_FP_NONZERO; break; case69: case101: type = PNG_FP_SAW_E; break; default: goto PNG_FP_End;
}
/* Now deal with this type according to the current *state,thetypeisarrangedtonotoverlapthe *bitsofthePNG_FP_STATE.
*/ switch ((state & PNG_FP_STATE) + (type & PNG_FP_SAW_ANY))
{ case PNG_FP_INTEGER + PNG_FP_SAW_SIGN: if ((state & PNG_FP_SAW_ANY) != 0) goto PNG_FP_End; /* not a part of the number */
png_fp_add(state, type); break;
case PNG_FP_INTEGER + PNG_FP_SAW_DOT: /* Ok as trailer, ok as lead of fraction. */ if ((state & PNG_FP_SAW_DOT) != 0) /* two dots */ goto PNG_FP_End;
case PNG_FP_INTEGER + PNG_FP_SAW_DIGIT: if ((state & PNG_FP_SAW_DOT) != 0) /* delayed fraction */
png_fp_set(state, PNG_FP_FRACTION | PNG_FP_SAW_DOT);
png_fp_add(state, type | PNG_FP_WAS_VALID);
break;
case PNG_FP_INTEGER + PNG_FP_SAW_E: if ((state & PNG_FP_SAW_DIGIT) == 0) goto PNG_FP_End;
png_fp_set(state, PNG_FP_EXPONENT);
break;
/* case PNG_FP_FRACTION + PNG_FP_SAW_SIGN:
goto PNG_FP_End; ** no sign in fraction */
/* case PNG_FP_FRACTION + PNG_FP_SAW_DOT:
goto PNG_FP_End; ** Because SAW_DOT is always set */
case PNG_FP_FRACTION + PNG_FP_SAW_DIGIT:
png_fp_add(state, type | PNG_FP_WAS_VALID); break;
case PNG_FP_FRACTION + PNG_FP_SAW_E: /* This is correct because the trailing '.' on an *integerishandledabove-sowecanonlygethere *withthesequence".E"(withnoprecedingdigits).
*/ if ((state & PNG_FP_SAW_DIGIT) == 0) goto PNG_FP_End;
png_fp_set(state, PNG_FP_EXPONENT);
break;
case PNG_FP_EXPONENT + PNG_FP_SAW_SIGN: if ((state & PNG_FP_SAW_ANY) != 0) goto PNG_FP_End; /* not a part of the number */
png_fp_add(state, PNG_FP_SAW_SIGN);
break;
/* case PNG_FP_EXPONENT + PNG_FP_SAW_DOT:
goto PNG_FP_End; */
case PNG_FP_EXPONENT + PNG_FP_SAW_DIGIT:
png_fp_add(state, PNG_FP_SAW_DIGIT | PNG_FP_WAS_VALID);
break;
/* case PNG_FP_EXPONEXT + PNG_FP_SAW_E:
goto PNG_FP_End; */
default: goto PNG_FP_End; /* I.e. break 2 */
}
/* The character seems ok, continue. */
++i;
}
PNG_FP_End: /* Here at the end, update the state and return the correct *returncode.
*/
*statep = state;
*whereami = i;
return (state & PNG_FP_SAW_DIGIT) != 0;
}
/* The same but for a complete string. */ int
png_check_fp_string(png_const_charp string, size_t size)
{ int state = 0;
size_t char_index = 0;
if (png_check_fp_number(string, size, &state, &char_index) != 0 &&
(char_index == size || string[char_index] == 0)) return state /* must be non-zero - see above */;
#ifdef PNG_sCAL_SUPPORTED # ifdef PNG_FLOATING_POINT_SUPPORTED /* Utility used below - a simple accurate power of ten from an integral *exponent.
*/ staticdouble
png_pow10(int power)
{ int recip = 0; double d = 1;
/* Handle negative exponent with a reciprocal at the end because *10isexactwhereas.1isinexactinbase2
*/ if (power < 0)
{ if (power < DBL_MIN_10_EXP) return0;
recip = 1; power = -power;
}
if (power > 0)
{ /* Decompose power bitwise. */ double mult = 10; do
{ if (power & 1) d *= mult;
mult *= mult;
power >>= 1;
} while (power > 0);
if (recip != 0) d = 1/d;
} /* else power is 0 and d is 1 */
return d;
}
/* Function to format a floating point value in ASCII with a given *precision.
*/ void/* PRIVATE */
png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, size_t size, double fp, unsignedint precision)
{ /* We use standard functions from math.h, but not printf because *thatwouldrequirestdio.Thecallermustsupplyabufferof *sufficientsizeorwewillpng_error.Thetestsonsizeand *thespaceinascii[]consumedareindicatedbelow. */ if(precision<1) precision=DBL_DIG;
if ((png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8)) != 0)
{ /* PNG_MAX_GAMMA_8 is the number of bits to keep - effectively *thesignificantbitsinthe*input*whentheoutputwill *eventuallybe8bits.Bydefaultitis11.
*/ if (shift < (16U - PNG_MAX_GAMMA_8))
shift = (16U - PNG_MAX_GAMMA_8);
}
if (shift > 8U)
shift = 8U; /* Guarantees at least one table! */
png_ptr->gamma_shift = shift;
/* NOTE: prior to 1.5.4 this test used to include PNG_BACKGROUND (now *PNG_COMPOSE).Thiseffectivelysmashedthebackgroundcalculationfor *16-bitoutputbecausethe8-bittableassumestheresultwillbe *reducedto8bits.
*/ if ((png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8)) != 0)
png_build_16to8_table(png_ptr, &png_ptr->gamma_16_table, shift,
png_reciprocal(correction)); else
png_build_16bit_table(png_ptr, &png_ptr->gamma_16_table, shift,
correction);
# if GAMMA_TRANSFORMS if ((png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY)) != 0)
{
png_build_16bit_table(png_ptr, &png_ptr->gamma_16_to_1, shift,
file_to_linear);
/* Notice that the '16 from 1' table should be full precision, however *thelookuponthistablestillusesgamma_shift,soitcan'tbe. *TODO:fixthis.
*/
png_build_16bit_table(png_ptr, &png_ptr->gamma_16_from_1, shift,
linear_to_screen);
} #endif/* GAMMA_TRANSFORMS */
} #endif/* 16BIT */
} #endif/* READ_GAMMA */
/* HARDWARE OR SOFTWARE OPTION SUPPORT */ #ifdef PNG_SET_OPTION_SUPPORTED int PNGAPI
png_set_option(png_structrp png_ptr, int option, int onoff)
{ if (png_ptr != NULL && option >= 0 && option < PNG_OPTION_NEXT &&
(option & 1) == 0)
{
png_uint_32 mask = 3U << option;
png_uint_32 setting = (2U + (onoff != 0)) << option;
png_uint_32 current = png_ptr->options;
/* Double check that we have a png_ptr - it should be impossible to get here *withoutone.
*/ if (cp->png_ptr == NULL) return0;
/* First free any data held in the control structure. */ # ifdef PNG_STDIO_SUPPORTED if (cp->owned_file != 0)
{
FILE *fp = png_voidcast(FILE *, cp->png_ptr->io_ptr);
cp->owned_file = 0;
/* Copy the control structure so that the original, allocated, version can be *safelyfreed.Noticethatapng_errorherestopstheremainderofthe *cleanup,butthisisprobablyfinebecausethatwouldindicatebadmemory *problemsanyway.
*/
c = *cp;
image->opaque = &c;
png_free(c.png_ptr, cp);
/* Then the structures, calling the correct API. */ if (c.for_write != 0)
{ # ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
png_destroy_write_struct(&c.png_ptr, &c.info_ptr); # else
png_error(c.png_ptr, "simplified write not supported"); # endif
} else
{ # ifdef PNG_SIMPLIFIED_READ_SUPPORTED
png_destroy_read_struct(&c.png_ptr, &c.info_ptr, NULL); # else
png_error(c.png_ptr, "simplified read not supported"); # endif
}
/* Success. */ return1;
}
void PNGAPI
png_image_free(png_imagep image)
{ /* Safely call the real function, but only if doing so is safe at this point *(ifnotinsideanerrorhandlingcontext).Otherwiseassume *png_safe_executewillcallthisAPIafterthereturn.
*/ if (image != NULL && image->opaque != NULL &&
image->opaque->error_buf == NULL)
{
png_image_free_function(image);
image->opaque = NULL;
}
}
¤ Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.0.204Bemerkung:
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.