/* 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;
/* Enforce the limit of the implementation precision too. */ if (precision > DBL_DIG+1)
precision = DBL_DIG+1;
/* Basic sanity checks */ if (size >= precision+5) /* See the requirements below. */
{ if (fp < 0)
{
fp = -fp;
*ascii++ = 45; /* '-' PLUS 1 TOTAL 1 */
--size;
}
if (fp >= DBL_MIN && fp <= DBL_MAX)
{ int exp_b10; /* A base 10 exponent */ double base; /* 10^exp_b10 */
/* First extract a base 10 exponent of the number, *thecalculationbelowroundsdownwhenconverting *frombase2tobase10(multiplybylog10(2)- *0.3010,but77/256is0.3008,soexp_b10needsto *beincreased.Notethatthearithmeticshift *performsafloor()unlikeCarithmetic-usinga *Cmultiplywouldbreakthefollowingfornegative *exponents.
*/
(void)frexp(fp, &exp_b10); /* exponent to base 2 */
exp_b10 = (exp_b10 * 77) >> 8; /* <= exponent to base 10 */
/* Avoid underflow here. */
base = png_pow10(exp_b10); /* May underflow */
while (base < DBL_MIN || base < fp)
{ /* And this may overflow. */ double test = png_pow10(exp_b10+1);
if (test <= DBL_MAX)
{
++exp_b10; base = test;
}
else break;
}
/* Normalize fp and correct exp_b10, after this fp is in the *range[.1,1)andexp_b10isboththeexponentandthedigit **before*whichthedecimalpointshouldbeinserted *(startingwith0forthefirstdigit).Notethatthis *worksevenif10^exp_b10isoutofrangebecauseofthe *testonDBL_MAXabove.
*/
fp /= base; while (fp >= 1)
{
fp /= 10; ++exp_b10;
}
/* Because of the code above fp may, at this point, be *lessthan.1,thisisokbecausethecodebelowcan *handletheleadingzerosthisgenerates,sonoattempt *ismadetocorrectthathere.
*/
/* Allow up to two leading zeros - this will not lengthen *thenumbercomparedtousingE-n.
*/ if (exp_b10 < 0 && exp_b10 > -3) /* PLUS 3 TOTAL 4 */
{
czero = 0U-exp_b10; /* PLUS 2 digits: TOTAL 3 */
exp_b10 = 0; /* Dot added below before first output. */
} else
czero = 0; /* No zeros to add */
/* Generate the digit list, stripping trailing zeros and *insertinga'.'beforeadigitiftheexponentis0.
*/
clead = czero; /* Count of leading zeros */
cdigits = 0; /* Count of digits in list. */
do
{ double d;
fp *= 10; /* Use modf here, not floor and subtract, so that *theseparationisdoneinonestep.Attheend *oftheloopdon'tbreakthenumberintopartsso *thatthefinaldigitisrounded.
*/ if (cdigits+czero+1 < precision+clead)
fp = modf(fp, &d);
else
{
d = floor(fp + .5);
if (d > 9)
{ /* Rounding up to 10, handle that here. */ if (czero > 0)
{
--czero; d = 1; if (cdigits == 0) --clead;
} else
{ while (cdigits > 0 && d > 9)
{ int ch = *--ascii;
if (exp_b10 != (-1))
++exp_b10;
elseif (ch == 46)
{
ch = *--ascii; ++size; /* Advance exp_b10 to '1', so that the *decimalpointhappensafterthe *previousdigit.
*/
exp_b10 = 1;
}
--cdigits;
d = ch - 47; /* I.e. 1+(ch-48) */
}
/* Did we reach the beginning? If so adjust the *exponentbuttakeintoaccounttheleading *decimalpoint.
*/ if (d > 9) /* cdigits == 0 */
{ if (exp_b10 == (-1))
{ /* Leading decimal point (plus zeros?), if *welosethedecimalpointhereitmust *bereenteredbelow.
*/ int ch = *--ascii;
if (ch == 46)
{
++size; exp_b10 = 1;
}
/* Else lost a leading zero, so 'exp_b10' is *stillokat(-1)
*/
} else
++exp_b10;
/* In all cases we output a '1' */
d = 1;
}
}
}
fp = 0; /* Guarantees termination below. */
}
if (d == 0)
{
++czero; if (cdigits == 0) ++clead;
} else
{ /* Included embedded zeros in the digit count. */
cdigits += czero - clead;
clead = 0;
while (czero > 0)
{ /* exp_b10 == (-1) means we just output the decimal *place-aftertheDPdon'tadjust'exp_b10'any *more!
*/ if (exp_b10 != (-1))
{ if (exp_b10 == 0)
{
*ascii++ = 46; --size;
} /* PLUS 1: TOTAL 4 */
--exp_b10;
}
*ascii++ = 48; --czero;
}
if (exp_b10 != (-1))
{ if (exp_b10 == 0)
{
*ascii++ = 46; --size; /* counted above */
}
/* The total output count (max) is now 4+precision */
/* Check for an exponent, if we don't need one we are *doneandjustneedtoterminatethestring.Atthis *point,exp_b10==(-1)iseffectivelyaflag:itgot *to'-1'becauseofthedecrement,afteroutputting *thedecimalpointabove.(Theexponentrequiredis **not*-1.)
*/ if (exp_b10 >= (-1) && exp_b10 <= 2)
{ /* The following only happens if we didn't output the *leadingzerosabovefornegativeexponent,sothis *doesn'taddtothedigitrequirement.Notethatthe *twozerosherecanonlybeoutputifthetwoleading *zeroswere*not*output,sothisdoesn'tincrease *theoutputcount.
*/ while (exp_b10-- > 0) *ascii++ = 48;
*ascii = 0;
/* Total buffer requirement (including the '\0') is *5+precision-seecheckatthestart.
*/ return;
}
/* Here if an exponent is required, adjust size for *thedigitsweoutputbutdidnotcount.Thetotal *digitoutputheresofarisatmost1+precision-no *decimalpointandnoleadingortrailingzeroshave *beenoutput.
*/
size -= cdigits;
*ascii++ = 69; --size; /* 'E': PLUS 1 TOTAL 2+precision */
/* The following use of an unsigned temporary avoids ambiguities in *thesignedarithmeticonexp_b10andpermitsGCCatleasttodo *betteroptimization.
*/
{ unsignedint uexp_b10;
if (exp_b10 < 0)
{
*ascii++ = 45; --size; /* '-': PLUS 1 TOTAL 3+precision */
uexp_b10 = 0U-exp_b10;
}
/* Need another size check here for the exponent digits, so *thisneednotbeconsideredabove.
*/ if (size > cdigits)
{ while (cdigits > 0) *ascii++ = exponent[--cdigits];
/* Here on buffer too small. */
png_error(png_ptr, "ASCII conversion buffer too small");
} # endif /* FLOATING_POINT */
# ifdef PNG_FIXED_POINT_SUPPORTED /* Function to format a fixed point value in ASCII.
*/ void/* PRIVATE */
png_ascii_from_fixed(png_const_structrp png_ptr, png_charp ascii,
size_t size, png_fixed_point fp)
{ /* Require space for 10 decimal digits, a decimal point, a minus sign and a *trailing\0,13characters:
*/ if (size > 12)
{
png_uint_32 num;
/* Avoid overflow here on the minimum integer. */ if (fp < 0)
{
*ascii++ = 45; num = (png_uint_32)(-fp);
} else
num = (png_uint_32)fp;
if (num <= 0x80000000) /* else overflowed */
{ unsignedint ndigits = 0, first = 16/* flag value */; char digits[10] = {0};
while (num)
{ /* Split the low digit off num: */ unsignedint tmp = num/10;
num -= tmp*10;
digits[ndigits++] = (char)(48 + num); /* Record the first non-zero digit, note that this is a number *startingat1,it'snotactuallythearrayindex.
*/ if (first == 16 && num > 0)
first = ndigits;
num = tmp;
}
if (ndigits > 0)
{ while (ndigits > 5) *ascii++ = digits[--ndigits]; /* The remaining digits are fractional digits, ndigits is '5' or *smalleratthispoint.Itiscertainlynotzero.Checkfora *non-zerofractionaldigit:
*/ if (first <= 5)
{ unsignedint i;
*ascii++ = 46; /* decimal point */ /* ndigits may be <5 for small numbers, output leading zeros *thenndigitsdigitstofirst:
*/
i = 5; while (ndigits < i)
{
*ascii++ = 48; --i;
} while (ndigits >= first) *ascii++ = digits[--ndigits]; /* Don't output the trailing zeros! */
}
} else
*ascii++ = 48;
/* And null terminate the string: */
*ascii = 0; return;
}
}
/* Here on buffer too small. */
png_error(png_ptr, "ASCII conversion buffer too small");
} # endif /* FIXED_POINT */ #endif/* SCAL */
#ifdefined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_COLORSPACE_SUPPORTED) ||\ defined(PNG_INCH_CONVERSIONS_SUPPORTED) || defined(PNG_READ_pHYs_SUPPORTED) /* muldiv functions */ /* This API takes signed arguments and rounds the result to the nearest *integer(or,forafixedpointnumber-thestandardargument-to *thenearest.00001).Overflowanddividebyzeroaresignalledin *theresult,aboolean-trueonsuccess,falseonoverflow.
*/ int/* PRIVATE */
png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times,
png_int_32 divisor)
{ /* Return a * times / divisor, rounded. */ if (divisor != 0)
{ if (a == 0 || times == 0)
{
*res = 0; return1;
} else
{ #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED double r = a;
r *= times;
r /= divisor;
r = floor(r+.5);
/* A png_fixed_point is a 32-bit integer. */ if (r <= 2147483647. && r >= -2147483648.)
{
*res = (png_fixed_point)r; return1;
} #else int negative = 0;
png_uint_32 A, T, D;
png_uint_32 s16, s32, s00;
if (a < 0)
negative = 1, A = -a; else
A = a;
if (times < 0)
negative = !negative, T = -times; else
T = times;
if (divisor < 0)
negative = !negative, D = -divisor; else
D = divisor;
/* Following can't overflow because the arguments only *have31bitseach,howevertheresultmaybe32bits.
*/
s16 = (A >> 16) * (T & 0xffff) +
(A & 0xffff) * (T >> 16); /* Can't overflow because the a*times bit is only 30 *bitsatmost.
*/
s32 = (A >> 16) * (T >> 16) + (s16 >> 16);
s00 = (A & 0xffff) * (T & 0xffff);
s16 = (s16 & 0xffff) << 16;
s00 += s16;
if (s00 < s16)
++s32; /* carry */
if (s32 < D) /* else overflow */
{ /* s32.s00 is now the 64-bit product, do a standard *division,weknowthats32<D,sothemaximum *requiredshiftis31.
*/ int bitshift = 32;
png_fixed_point result = 0; /* NOTE: signed */
while (--bitshift >= 0)
{
png_uint_32 d32, d00;
if (bitshift > 0)
d32 = D >> (32-bitshift), d00 = D << bitshift;
else
d32 = 0, d00 = D;
if (s32 > d32)
{ if (s00 < d00) --s32; /* carry */
s32 -= d32, s00 -= d00, result += 1<<bitshift;
}
else if (s32 == d32 && s00 >= d00)
s32 = 0, s00 -= d00, result += 1<<bitshift;
}
/* Handle the rounding. */ if (s00 >= (D >> 1))
++result;
if (negative != 0)
result = -result;
/* Check for overflow. */ if ((negative != 0 && result <= 0) ||
(negative == 0 && result >= 0))
{
*res = result; return1;
}
} #endif
}
}
return0;
}
/* Calculate a reciprocal, return 0 on div-by-zero or overflow. */
png_fixed_point
png_reciprocal(png_fixed_point a)
{ #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED double r = floor(1E10/a+.5);
if (r <= 2147483647. && r >= -2147483648.) return (png_fixed_point)r; #else
png_fixed_point res;
if (png_muldiv(&res, 100000, 100000, a) != 0) return res; #endif
#ifdef PNG_READ_GAMMA_SUPPORTED /* This is the shared test on whether a gamma value is 'significant' - whether *itisworthdoinggammacorrection.
*/ int/* PRIVATE */
png_gamma_significant(png_fixed_point gamma_val)
{ /* sRGB: 1/2.2 == 0.4545(45) *AdobeRGB:1/(2+51/256)~=0.454715dp * *SothecorrectionfromAdobeRGBtosRGB(output)is: * *2.2/(2+51/256)==1.00035524 * *I.e.vanishinglysmall(<4E-4)butstilldetectablein16-bitlinear(+/- *23).NotethattheAdobechoiceseemstobesomethingintendedtogivean *exactnumberwith8binaryfractionaldigits-itistheclosestto2.2 *thatispossibleabase2.8prepresentation.
*/ return gamma_val < PNG_FP_1 - PNG_GAMMA_THRESHOLD_FIXED ||
gamma_val > PNG_FP_1 + PNG_GAMMA_THRESHOLD_FIXED;
}
#ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED /* A local convenience routine. */ static png_fixed_point
png_product2(png_fixed_point a, png_fixed_point b)
{ /* The required result is a * b; the following preserves accuracy. */ #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED /* Should now be unused */ double r = a * 1E-5;
r *= b;
r = floor(r+.5);
if (r <= 2147483647. && r >= -2147483648.) return (png_fixed_point)r; #else
png_fixed_point res;
if (png_muldiv(&res, a, b, 100000) != 0) return res; #endif
png_fixed_point
png_reciprocal2(png_fixed_point a, png_fixed_point b)
{ /* The required result is 1/a * 1/b; the following preserves accuracy. */ #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED if (a != 0 && b != 0)
{ double r = 1E15/a;
r /= b;
r = floor(r+.5);
if (r <= 2147483647. && r >= -2147483648.) return (png_fixed_point)r;
} #else /* This may overflow because the range of png_fixed_point isn't symmetric, *butthisAPIisonlyusedfortheproductoffileandscreengammasoit *doesn'tmatterthatthesmallestnumberitcanproduceis1/21474,not *1/100000
*/
png_fixed_point res = png_product2(a, b);
static png_int_32
png_log8bit(unsignedint x)
{ unsignedint lg2 = 0; /* Each time 'x' is multiplied by 2, 1 must be subtracted off the final log, *becausethelogisactuallynegatethatmeansadding1.Thefinal *returnedvaluethushastherange0(for255input)to7.994(for1 *input),return-1fortheoverflow(log0)case,-sotheresultis *alwaysatmost19bits.
*/ if ((x &= 0xff) == 0) return -1;
if ((x & 0xf0) == 0)
lg2 = 4, x <<= 4;
if ((x & 0xc0) == 0)
lg2 += 2, x <<= 2;
if ((x & 0x80) == 0)
lg2 += 1, x <<= 1;
/* result is at most 19 bits, so this cast is safe: */ return (png_int_32)((lg2 << 16) + ((png_8bit_l2[x-128]+32768)>>16));
}
/* As above, but now the input has 16 bits. */ if ((x &= 0xffff) == 0) return -1;
if ((x & 0xff00) == 0)
lg2 = 8, x <<= 8;
if ((x & 0xf000) == 0)
lg2 += 4, x <<= 4;
if ((x & 0xc000) == 0)
lg2 += 2, x <<= 2;
if ((x & 0x8000) == 0)
lg2 += 1, x <<= 1;
/* Calculate the base logarithm from the top 8 bits as a 28-bit fractional *value.
*/
lg2 <<= 28;
lg2 += (png_8bit_l2[(x>>8)-128]+8) >> 4;
/* Now we need to interpolate the factor, this requires a division by the top *8bits.Dothiswithmaximumprecision.
*/
x = ((x << 16) + (x >> 9)) / (x >> 8);
/* Since we divided by the top 8 bits of 'x' there will be a '1' at 1<<24, *thevalueat1<<16(ignoringthis)willbe0or1;thisgivesusexactly *16bitstointerpolatetogetthelowbitsoftheresult.Roundthe *answer.Notethattheendpointvaluesarescaledby64toretainoverall *precisionandthat'lg2'iscurrentscaledbyanextra12bits,soadjust *theoverallscalingby6-12.Roundateverystep.
*/
x -= 1U << 24;
/* Safe, because the result can't have more than 20 bits: */ return (png_int_32)((lg2 + 2048) >> 12);
} #endif/* 16BIT */
/* The 'exp()' case must invert the above, taking a 20-bit fixed point *logarithmicvalueandreturninga16or8-bitnumberasappropriate.In *eachcaseonlythelow16bitsarerelevant-thefraction-sincethe *integerbits(thetop4)simplydetermineashift. * *Theworstcaseisthe16-bitdistinctionbetween65535and65534.This *requiresperhapsspuriousaccuracyinthedecodingofthelogarithmto *distinguishlog2(65535/65534.5)-10^-5or17bits.Thereislittlechance *ofgettingthisaccuracyinpractice. * *Todealwiththisthefollowingexp()functionworksouttheexponentofthe *fractionalpartofthelogarithmbyusinganaccurate32-bitvaluefromthe *topfourfractionalbitsthenmultiplyingintheremainingbits.
*/ staticconst png_uint_32
png_32bit_exp[16] =
{ /* NOTE: the first entry is deliberately set to the maximum 32-bit value. */ 4294967295U, 4112874773U, 3938502376U, 3771522796U, 3611622603U, 3458501653U, 3311872529U, 3171459999U, 3037000500U, 2908241642U, 2784941738U, 2666869345U, 2553802834U, 2445529972U, 2341847524U, 2242560872U
};
/* Adjustment table; provided to explain the numbers in the code below. */ #if0 for (i=11;i>=0;--i){ print i, " ", (1 - e(-(2^i)/65536*l(2))) * 2^(32-i), "\n"} 1144937.64284865548751208448 1045180.98734845585101160448 945303.31936980687359311872 845364.65110595323018870784 745395.35850361789624614912 645410.72259715102037508096 545418.40724413220722311168 445422.25021786898173001728 345424.17186732298419044352 245425.13273269940811464704 145425.61317555035558641664 045425.85339951654943850496 #endif
static png_uint_32
png_exp(png_fixed_point x)
{ if (x > 0 && x <= 0xfffff) /* Else overflow or zero (underflow) */
{ /* Obtain a 4-bit approximation */
png_uint_32 e = png_32bit_exp[(x >> 12) & 0x0f];
/* Incorporate the low 12 bits - these decrease the returned value by *multiplyingbyanumberlessthan1ifthebitisset.Themultiplier *isdeterminedbytheabovetableandtheshift.Noticethatthevalues *convergeon45426andthisisusedtoallowlinearinterpolationofthe *lowbits.
*/ if (x & 0x800)
e -= (((e >> 16) * 44938U) + 16U) >> 5;
if (x & 0x400)
e -= (((e >> 16) * 45181U) + 32U) >> 6;
if (x & 0x200)
e -= (((e >> 16) * 45303U) + 64U) >> 7;
if (x & 0x100)
e -= (((e >> 16) * 45365U) + 128U) >> 8;
if (x & 0x080)
e -= (((e >> 16) * 45395U) + 256U) >> 9;
if (x & 0x040)
e -= (((e >> 16) * 45410U) + 512U) >> 10;
/* And handle the low 6 bits in a single block. */
e -= (((e >> 16) * 355U * (x & 0x3fU)) + 256U) >> 9;
/* Handle the upper bits of x. */
e >>= x >> 16; return e;
}
/* Check for overflow */ if (x <= 0) return png_32bit_exp[0];
/* Else underflow */ return0;
}
static png_byte
png_exp8bit(png_fixed_point lg2)
{ /* Get a 32-bit value: */
png_uint_32 x = png_exp(lg2);
/* Convert the 32-bit value to 0..255 by multiplying by 256-1. Note that the *second,rounding,stepcan'toverflowbecauseofthefirst,subtraction, *step.
*/
x -= x >> 8; return (png_byte)(((x + 0x7fffffU) >> 24) & 0xff);
}
#ifdef PNG_16BIT_SUPPORTED static png_uint_16
png_exp16bit(png_fixed_point lg2)
{ /* Get a 32-bit value: */
png_uint_32 x = png_exp(lg2);
/* Convert the 32-bit value to 0..65535 by multiplying by 65536-1: */
x -= x >> 16; return (png_uint_16)((x + 32767U) >> 16);
} #endif/* 16BIT */ #endif/* FLOATING_ARITHMETIC */
if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1) != 0) return png_exp8bit(res);
/* Overflow. */
value = 0; # endif
}
return (png_byte)(value & 0xff);
}
#ifdef PNG_16BIT_SUPPORTED
png_uint_16
png_gamma_16bit_correct(unsignedint value, png_fixed_point gamma_val)
{ if (value > 0 && value < 65535)
{ # ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED /* The same (unsigned int)->(double) constraints apply here as above, *howeverinthiscasethe(unsignedint)to(int)conversioncan *overflowonanANSI-C90compliantsystemsothecastneedstoensure *thatthisisnotpossible.
*/ double r = floor(65535*pow((png_int_32)value/65535.,
gamma_val*.00001)+.5); return (png_uint_16)r; # else
png_int_32 lg2 = png_log16bit(value);
png_fixed_point res;
if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1) != 0) return png_exp16bit(res);
/* Overflow. */
value = 0; # endif
}
return (png_uint_16)value;
} #endif/* 16BIT */
/* This does the right thing based on the bit_depth field of the *png_struct,interpretingvaluesas8-bitor16-bit.Whiletheresult *isnominallya16-bitvalueifbitdepthis8thentheresultis *8-bit(asarethearguments.)
*/
png_uint_16 /* PRIVATE */
png_gamma_correct(png_structrp png_ptr, unsignedint value,
png_fixed_point gamma_val)
{ if (png_ptr->bit_depth == 8) return png_gamma_8bit_correct(value, gamma_val);
#ifdef PNG_16BIT_SUPPORTED else return png_gamma_16bit_correct(value, gamma_val); #else /* should not reach this */ return0; #endif/* 16BIT */
}
#ifdef PNG_16BIT_SUPPORTED /* Internal function to build a single 16-bit table - the table consists of *'num'256entrysubtables,where'num'isdeterminedby'shift'-theamount *toshifttheinputvaluesright(or16-number_of_signifiant_bits). * *Thecallerisresponsibleforensuringthatthetablegetscleanedupon *png_error(i.e.ifoneofthemallocsbelowfails)-i.e.the*tableargument *shouldbesomewherethatwillbecleaned.
*/ staticvoid
png_build_16bit_table(png_structrp png_ptr, png_uint_16pp *ptable, unsignedint shift, png_fixed_point gamma_val)
{ /* Various values derived from 'shift': */ unsignedint num = 1U << (8U - shift); #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED /* CSE the division and work round wacky GCC warnings (see the comments *inpng_gamma_8bit_correctforwherethesecomefrom.)
*/ double fmax = 1.0 / (((png_int_32)1 << (16U - shift)) - 1); #endif unsignedint max = (1U << (16U - shift)) - 1U; unsignedint max_by_2 = 1U << (15U - shift); unsignedint i;
png_uint_16pp table = *ptable =
(png_uint_16pp)png_calloc(png_ptr, num * (sizeof (png_uint_16p)));
for (i = 0; i < num; i++)
{
png_uint_16p sub_table = table[i] =
(png_uint_16p)png_malloc(png_ptr, 256 * (sizeof (png_uint_16)));
/* The 'threshold' test is repeated here because it can arise for one of *the16-bittableseveniftheothersdon'thitit.
*/ if (png_gamma_significant(gamma_val) != 0)
{ /* The old code would overflow at the end and this would cause the *'pow'functiontoreturnaresult>1,resultinginan *arithmeticerror.Thiscodefollowsthespecexactly;igis *therecoveredinputsample,italwayshas8-16bits. * *Wewantinput*65535/max,rounded,thearithmeticfitsin32 *bits(unsigned)solongasmax<=32767.
*/ unsignedint j; for (j = 0; j < 256; j++)
{
png_uint_32 ig = (j << (8-shift)) + i; # ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED /* Inline the 'max' scaling operation: */ /* See png_gamma_8bit_correct for why the cast to (int) is *requiredhere.
*/ double d = floor(65535.*pow(ig*fmax, gamma_val*.00001)+.5);
sub_table[j] = (png_uint_16)d; # else if (shift != 0)
ig = (ig * 65535U + max_by_2)/max;
sub_table[j] = png_gamma_16bit_correct(ig, gamma_val); # endif
}
} else
{ /* We must still build a table, but do it the fast way. */ unsignedint j;
/* NOTE: this function expects the *inverse* of the overall gamma transformation *required.
*/ staticvoid
png_build_16to8_table(png_structrp png_ptr, png_uint_16pp *ptable, unsignedint shift, png_fixed_point gamma_val)
{ unsignedint num = 1U << (8U - shift); unsignedint max = (1U << (16U - shift))-1U; unsignedint i;
png_uint_32 last;
png_uint_16pp table = *ptable =
(png_uint_16pp)png_calloc(png_ptr, num * (sizeof (png_uint_16p)));
/* 'num' is the number of tables and also the number of low bits of low *bitsoftheinput16-bitvalueusedtoselectatable.Eachtableis *itselfindexedbythehigh8bitsofthevalue.
*/ for (i = 0; i < num; i++)
table[i] = (png_uint_16p)png_malloc(png_ptr, 256 * (sizeof (png_uint_16)));
/* 'gamma_val' is set to the reciprocal of the value calculated above, so *pow(out,g)isan*input*value.'last'isthelastinputvalueset. * *Intheloop'i'isusedtofindoutputvalues.Sincetheoutputis *8-bitthereareonly256possiblevalues.Thetablesaresetupto *selecttheclosestpossibleoutputvalueforeachinputbyfinding *theinputvalueattheboundarybetweeneachpairofoutputvalues *andfillingthetableuptothatboundarywiththeloweroutput *value. * *Theboundaryvaluesare0.5,1.5..253.5,254.5.Sincetheseare9-bit *valuesthecodebelowusesa16-bitvalueini;thevaluesstartat *128.5(for0.5)andstepby257,foratotalof254values(thelast *entriesarefilledwith255).Startiat128andfillall'last' *tableentries<='max'
*/
last = 0; for (i = 0; i < 255; ++i) /* 8-bit output value */
{ /* Find the corresponding maximum input value */
png_uint_16 out = (png_uint_16)(i * 257U); /* 16-bit output value */
/* Find the boundary value in 16 bits: */
png_uint_32 bound = png_gamma_16bit_correct(out+128U, gamma_val);
/* Adjust (round) to (16-shift) bits: */
bound = (bound * max + 32768U)/65535U + 1U;
/* And fill in the final entries. */ while (last < (num << 8))
{
table[last & (0xff >> shift)][last >> (8U - shift)] = 65535U;
last++;
}
} #endif/* 16BIT */
/* Build a single 8-bit table: same as the 16-bit case but much simpler (and *typicallymuchfaster).NotethatlibpngcurrentlydoesnosBITprocessing *(apparentlycontrarytothespec)soa256-entrytableisalwaysgenerated.
*/ staticvoid
png_build_8bit_table(png_structrp png_ptr, png_bytepp ptable,
png_fixed_point gamma_val)
{ unsignedint i;
png_bytep table = *ptable = (png_bytep)png_malloc(png_ptr, 256);
if (png_gamma_significant(gamma_val) != 0) for (i=0; i<256; i++)
table[i] = png_gamma_8bit_correct(i, gamma_val);
/* Used from png_read_destroy and below to release the memory used by the gamma *tables.
*/ void/* PRIVATE */
png_destroy_gamma_table(png_structrp png_ptr)
{
png_free(png_ptr, png_ptr->gamma_table);
png_ptr->gamma_table = NULL;
#ifdef PNG_16BIT_SUPPORTED if (png_ptr->gamma_16_table != NULL)
{ int i; int istop = (1 << (8 - png_ptr->gamma_shift)); for (i = 0; i < istop; i++)
{
png_free(png_ptr, png_ptr->gamma_16_table[i]);
}
png_free(png_ptr, png_ptr->gamma_16_table);
png_ptr->gamma_16_table = NULL;
} #endif/* 16BIT */
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;
}
}
¤ Diese beiden folgenden Angebotsgruppen bietet das Unternehmen0.174Angebot
(Wie Sie bei der Firma Beratungs- und Dienstleistungen beauftragen können 2026-09-29)
¤
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.