png.c 132 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039
  1. /* png.c - location for general purpose libpng functions
  2. *
  3. * Copyright (c) 2018-2025 Cosmin Truta
  4. * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
  5. * Copyright (c) 1996-1997 Andreas Dilger
  6. * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
  7. *
  8. * This code is released under the libpng license.
  9. * For conditions of distribution and use, see the disclaimer
  10. * and license in png.h
  11. */
  12. #include "pngpriv.h"
  13. /* Generate a compiler error if there is an old png.h in the search path. */
  14. typedef png_libpng_version_1_6_48 Your_png_h_is_not_version_1_6_48;
  15. /* Sanity check the chunks definitions - PNG_KNOWN_CHUNKS from pngpriv.h and the
  16. * corresponding macro definitions. This causes a compile time failure if
  17. * something is wrong but generates no code.
  18. *
  19. * (1) The first check is that the PNG_CHUNK(cHNK, index) 'index' values must
  20. * increment from 0 to the last value.
  21. */
  22. #define PNG_CHUNK(cHNK, index) != (index) || ((index)+1)
  23. #if 0 PNG_KNOWN_CHUNKS < 0
  24. # error PNG_KNOWN_CHUNKS chunk definitions are not in order
  25. #endif
  26. #undef PNG_CHUNK
  27. /* (2) The chunk name macros, png_cHNK, must all be valid and defined. Since
  28. * this is a preprocessor test undefined pp-tokens come out as zero and will
  29. * fail this test.
  30. */
  31. #define PNG_CHUNK(cHNK, index) !PNG_CHUNK_NAME_VALID(png_ ## cHNK) ||
  32. #if PNG_KNOWN_CHUNKS 0
  33. # error png_cHNK not defined for some known cHNK
  34. #endif
  35. #undef PNG_CHUNK
  36. /* Tells libpng that we have already handled the first "num_bytes" bytes
  37. * of the PNG file signature. If the PNG data is embedded into another
  38. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  39. * or write any of the magic bytes before it starts on the IHDR.
  40. */
  41. #ifdef PNG_READ_SUPPORTED
  42. void PNGAPI
  43. png_set_sig_bytes(png_structrp png_ptr, int num_bytes)
  44. {
  45. unsigned int nb = (unsigned int)num_bytes;
  46. png_debug(1, "in png_set_sig_bytes");
  47. if (png_ptr == NULL)
  48. return;
  49. if (num_bytes < 0)
  50. nb = 0;
  51. if (nb > 8)
  52. png_error(png_ptr, "Too many bytes for PNG signature");
  53. png_ptr->sig_bytes = (png_byte)nb;
  54. }
  55. /* Checks whether the supplied bytes match the PNG signature. We allow
  56. * checking less than the full 8-byte signature so that those apps that
  57. * already read the first few bytes of a file to determine the file type
  58. * can simply check the remaining bytes for extra assurance. Returns
  59. * an integer less than, equal to, or greater than zero if sig is found,
  60. * respectively, to be less than, to match, or be greater than the correct
  61. * PNG signature (this is the same behavior as strcmp, memcmp, etc).
  62. */
  63. int PNGAPI
  64. png_sig_cmp(png_const_bytep sig, size_t start, size_t num_to_check)
  65. {
  66. static const png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  67. if (num_to_check > 8)
  68. num_to_check = 8;
  69. else if (num_to_check < 1)
  70. return -1;
  71. if (start > 7)
  72. return -1;
  73. if (start + num_to_check > 8)
  74. num_to_check = 8 - start;
  75. return memcmp(&sig[start], &png_signature[start], num_to_check);
  76. }
  77. #endif /* READ */
  78. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  79. /* Function to allocate memory for zlib */
  80. PNG_FUNCTION(voidpf /* PRIVATE */,
  81. png_zalloc,(voidpf png_ptr, uInt items, uInt size),PNG_ALLOCATED)
  82. {
  83. png_alloc_size_t num_bytes = size;
  84. if (png_ptr == NULL)
  85. return NULL;
  86. if (items >= (~(png_alloc_size_t)0)/size)
  87. {
  88. png_warning (png_voidcast(png_structrp, png_ptr),
  89. "Potential overflow in png_zalloc()");
  90. return NULL;
  91. }
  92. num_bytes *= items;
  93. return png_malloc_warn(png_voidcast(png_structrp, png_ptr), num_bytes);
  94. }
  95. /* Function to free memory for zlib */
  96. void /* PRIVATE */
  97. png_zfree(voidpf png_ptr, voidpf ptr)
  98. {
  99. png_free(png_voidcast(png_const_structrp,png_ptr), ptr);
  100. }
  101. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  102. * in case CRC is > 32 bits to leave the top bits 0.
  103. */
  104. void /* PRIVATE */
  105. png_reset_crc(png_structrp png_ptr)
  106. {
  107. /* The cast is safe because the crc is a 32-bit value. */
  108. png_ptr->crc = (png_uint_32)crc32(0, Z_NULL, 0);
  109. }
  110. /* Calculate the CRC over a section of data. We can only pass as
  111. * much data to this routine as the largest single buffer size. We
  112. * also check that this data will actually be used before going to the
  113. * trouble of calculating it.
  114. */
  115. void /* PRIVATE */
  116. png_calculate_crc(png_structrp png_ptr, png_const_bytep ptr, size_t length)
  117. {
  118. int need_crc = 1;
  119. if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0)
  120. {
  121. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  122. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  123. need_crc = 0;
  124. }
  125. else /* critical */
  126. {
  127. if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0)
  128. need_crc = 0;
  129. }
  130. /* 'uLong' is defined in zlib.h as unsigned long; this means that on some
  131. * systems it is a 64-bit value. crc32, however, returns 32 bits so the
  132. * following cast is safe. 'uInt' may be no more than 16 bits, so it is
  133. * necessary to perform a loop here.
  134. */
  135. if (need_crc != 0 && length > 0)
  136. {
  137. uLong crc = png_ptr->crc; /* Should never issue a warning */
  138. do
  139. {
  140. uInt safe_length = (uInt)length;
  141. #ifndef __COVERITY__
  142. if (safe_length == 0)
  143. safe_length = (uInt)-1; /* evil, but safe */
  144. #endif
  145. crc = crc32(crc, ptr, safe_length);
  146. /* The following should never issue compiler warnings; if they do the
  147. * target system has characteristics that will probably violate other
  148. * assumptions within the libpng code.
  149. */
  150. ptr += safe_length;
  151. length -= safe_length;
  152. }
  153. while (length > 0);
  154. /* And the following is always safe because the crc is only 32 bits. */
  155. png_ptr->crc = (png_uint_32)crc;
  156. }
  157. }
  158. /* Check a user supplied version number, called from both read and write
  159. * functions that create a png_struct.
  160. */
  161. int
  162. png_user_version_check(png_structrp png_ptr, png_const_charp user_png_ver)
  163. {
  164. /* Libpng versions 1.0.0 and later are binary compatible if the version
  165. * string matches through the second '.'; we must recompile any
  166. * applications that use any older library version.
  167. */
  168. if (user_png_ver != NULL)
  169. {
  170. int i = -1;
  171. int found_dots = 0;
  172. do
  173. {
  174. i++;
  175. if (user_png_ver[i] != PNG_LIBPNG_VER_STRING[i])
  176. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  177. if (user_png_ver[i] == '.')
  178. found_dots++;
  179. } while (found_dots < 2 && user_png_ver[i] != 0 &&
  180. PNG_LIBPNG_VER_STRING[i] != 0);
  181. }
  182. else
  183. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  184. if ((png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH) != 0)
  185. {
  186. #ifdef PNG_WARNINGS_SUPPORTED
  187. size_t pos = 0;
  188. char m[128];
  189. pos = png_safecat(m, (sizeof m), pos,
  190. "Application built with libpng-");
  191. pos = png_safecat(m, (sizeof m), pos, user_png_ver);
  192. pos = png_safecat(m, (sizeof m), pos, " but running with ");
  193. pos = png_safecat(m, (sizeof m), pos, PNG_LIBPNG_VER_STRING);
  194. PNG_UNUSED(pos)
  195. png_warning(png_ptr, m);
  196. #endif
  197. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198. png_ptr->flags = 0;
  199. #endif
  200. return 0;
  201. }
  202. /* Success return. */
  203. return 1;
  204. }
  205. /* Generic function to create a png_struct for either read or write - this
  206. * contains the common initialization.
  207. */
  208. PNG_FUNCTION(png_structp /* PRIVATE */,
  209. png_create_png_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
  210. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  211. png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
  212. {
  213. png_struct create_struct;
  214. # ifdef PNG_SETJMP_SUPPORTED
  215. jmp_buf create_jmp_buf;
  216. # endif
  217. /* This temporary stack-allocated structure is used to provide a place to
  218. * build enough context to allow the user provided memory allocator (if any)
  219. * to be called.
  220. */
  221. memset(&create_struct, 0, (sizeof create_struct));
  222. # ifdef PNG_USER_LIMITS_SUPPORTED
  223. create_struct.user_width_max = PNG_USER_WIDTH_MAX;
  224. create_struct.user_height_max = PNG_USER_HEIGHT_MAX;
  225. # ifdef PNG_USER_CHUNK_CACHE_MAX
  226. create_struct.user_chunk_cache_max = PNG_USER_CHUNK_CACHE_MAX;
  227. # endif
  228. # if PNG_USER_CHUNK_MALLOC_MAX > 0 /* default to compile-time limit */
  229. create_struct.user_chunk_malloc_max = PNG_USER_CHUNK_MALLOC_MAX;
  230. /* No compile-time limit, so initialize to the system limit: */
  231. # elif defined PNG_MAX_MALLOC_64K /* legacy system limit */
  232. create_struct.user_chunk_malloc_max = 65536U;
  233. # else /* modern system limit SIZE_MAX (C99) */
  234. create_struct.user_chunk_malloc_max = PNG_SIZE_MAX;
  235. # endif
  236. # endif
  237. /* The following two API calls simply set fields in png_struct, so it is safe
  238. * to do them now even though error handling is not yet set up.
  239. */
  240. # ifdef PNG_USER_MEM_SUPPORTED
  241. png_set_mem_fn(&create_struct, mem_ptr, malloc_fn, free_fn);
  242. # else
  243. PNG_UNUSED(mem_ptr)
  244. PNG_UNUSED(malloc_fn)
  245. PNG_UNUSED(free_fn)
  246. # endif
  247. /* (*error_fn) can return control to the caller after the error_ptr is set,
  248. * this will result in a memory leak unless the error_fn does something
  249. * extremely sophisticated. The design lacks merit but is implicit in the
  250. * API.
  251. */
  252. png_set_error_fn(&create_struct, error_ptr, error_fn, warn_fn);
  253. # ifdef PNG_SETJMP_SUPPORTED
  254. if (!setjmp(create_jmp_buf))
  255. # endif
  256. {
  257. # ifdef PNG_SETJMP_SUPPORTED
  258. /* Temporarily fake out the longjmp information until we have
  259. * successfully completed this function. This only works if we have
  260. * setjmp() support compiled in, but it is safe - this stuff should
  261. * never happen.
  262. */
  263. create_struct.jmp_buf_ptr = &create_jmp_buf;
  264. create_struct.jmp_buf_size = 0; /*stack allocation*/
  265. create_struct.longjmp_fn = longjmp;
  266. # endif
  267. /* Call the general version checker (shared with read and write code):
  268. */
  269. if (png_user_version_check(&create_struct, user_png_ver) != 0)
  270. {
  271. png_structrp png_ptr = png_voidcast(png_structrp,
  272. png_malloc_warn(&create_struct, (sizeof *png_ptr)));
  273. if (png_ptr != NULL)
  274. {
  275. /* png_ptr->zstream holds a back-pointer to the png_struct, so
  276. * this can only be done now:
  277. */
  278. create_struct.zstream.zalloc = png_zalloc;
  279. create_struct.zstream.zfree = png_zfree;
  280. create_struct.zstream.opaque = png_ptr;
  281. # ifdef PNG_SETJMP_SUPPORTED
  282. /* Eliminate the local error handling: */
  283. create_struct.jmp_buf_ptr = NULL;
  284. create_struct.jmp_buf_size = 0;
  285. create_struct.longjmp_fn = 0;
  286. # endif
  287. *png_ptr = create_struct;
  288. /* This is the successful return point */
  289. return png_ptr;
  290. }
  291. }
  292. }
  293. /* A longjmp because of a bug in the application storage allocator or a
  294. * simple failure to allocate the png_struct.
  295. */
  296. return NULL;
  297. }
  298. /* Allocate the memory for an info_struct for the application. */
  299. PNG_FUNCTION(png_infop,PNGAPI
  300. png_create_info_struct,(png_const_structrp png_ptr),PNG_ALLOCATED)
  301. {
  302. png_inforp info_ptr;
  303. png_debug(1, "in png_create_info_struct");
  304. if (png_ptr == NULL)
  305. return NULL;
  306. /* Use the internal API that does not (or at least should not) error out, so
  307. * that this call always returns ok. The application typically sets up the
  308. * error handling *after* creating the info_struct because this is the way it
  309. * has always been done in 'example.c'.
  310. */
  311. info_ptr = png_voidcast(png_inforp, png_malloc_base(png_ptr,
  312. (sizeof *info_ptr)));
  313. if (info_ptr != NULL)
  314. memset(info_ptr, 0, (sizeof *info_ptr));
  315. return info_ptr;
  316. }
  317. /* This function frees the memory associated with a single info struct.
  318. * Normally, one would use either png_destroy_read_struct() or
  319. * png_destroy_write_struct() to free an info struct, but this may be
  320. * useful for some applications. From libpng 1.6.0 this function is also used
  321. * internally to implement the png_info release part of the 'struct' destroy
  322. * APIs. This ensures that all possible approaches free the same data (all of
  323. * it).
  324. */
  325. void PNGAPI
  326. png_destroy_info_struct(png_const_structrp png_ptr, png_infopp info_ptr_ptr)
  327. {
  328. png_inforp info_ptr = NULL;
  329. png_debug(1, "in png_destroy_info_struct");
  330. if (png_ptr == NULL)
  331. return;
  332. if (info_ptr_ptr != NULL)
  333. info_ptr = *info_ptr_ptr;
  334. if (info_ptr != NULL)
  335. {
  336. /* Do this first in case of an error below; if the app implements its own
  337. * memory management this can lead to png_free calling png_error, which
  338. * will abort this routine and return control to the app error handler.
  339. * An infinite loop may result if it then tries to free the same info
  340. * ptr.
  341. */
  342. *info_ptr_ptr = NULL;
  343. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  344. memset(info_ptr, 0, (sizeof *info_ptr));
  345. png_free(png_ptr, info_ptr);
  346. }
  347. }
  348. /* Initialize the info structure. This is now an internal function (0.89)
  349. * and applications using it are urged to use png_create_info_struct()
  350. * instead. Use deprecated in 1.6.0, internal use removed (used internally it
  351. * is just a memset).
  352. *
  353. * NOTE: it is almost inconceivable that this API is used because it bypasses
  354. * the user-memory mechanism and the user error handling/warning mechanisms in
  355. * those cases where it does anything other than a memset.
  356. */
  357. PNG_FUNCTION(void,PNGAPI
  358. png_info_init_3,(png_infopp ptr_ptr, size_t png_info_struct_size),
  359. PNG_DEPRECATED)
  360. {
  361. png_inforp info_ptr = *ptr_ptr;
  362. png_debug(1, "in png_info_init_3");
  363. if (info_ptr == NULL)
  364. return;
  365. if ((sizeof (png_info)) > png_info_struct_size)
  366. {
  367. *ptr_ptr = NULL;
  368. /* The following line is why this API should not be used: */
  369. free(info_ptr);
  370. info_ptr = png_voidcast(png_inforp, png_malloc_base(NULL,
  371. (sizeof *info_ptr)));
  372. if (info_ptr == NULL)
  373. return;
  374. *ptr_ptr = info_ptr;
  375. }
  376. /* Set everything to 0 */
  377. memset(info_ptr, 0, (sizeof *info_ptr));
  378. }
  379. void PNGAPI
  380. png_data_freer(png_const_structrp png_ptr, png_inforp info_ptr,
  381. int freer, png_uint_32 mask)
  382. {
  383. png_debug(1, "in png_data_freer");
  384. if (png_ptr == NULL || info_ptr == NULL)
  385. return;
  386. if (freer == PNG_DESTROY_WILL_FREE_DATA)
  387. info_ptr->free_me |= mask;
  388. else if (freer == PNG_USER_WILL_FREE_DATA)
  389. info_ptr->free_me &= ~mask;
  390. else
  391. png_error(png_ptr, "Unknown freer parameter in png_data_freer");
  392. }
  393. void PNGAPI
  394. png_free_data(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 mask,
  395. int num)
  396. {
  397. png_debug(1, "in png_free_data");
  398. if (png_ptr == NULL || info_ptr == NULL)
  399. return;
  400. #ifdef PNG_TEXT_SUPPORTED
  401. /* Free text item num or (if num == -1) all text items */
  402. if (info_ptr->text != NULL &&
  403. ((mask & PNG_FREE_TEXT) & info_ptr->free_me) != 0)
  404. {
  405. if (num != -1)
  406. {
  407. png_free(png_ptr, info_ptr->text[num].key);
  408. info_ptr->text[num].key = NULL;
  409. }
  410. else
  411. {
  412. int i;
  413. for (i = 0; i < info_ptr->num_text; i++)
  414. png_free(png_ptr, info_ptr->text[i].key);
  415. png_free(png_ptr, info_ptr->text);
  416. info_ptr->text = NULL;
  417. info_ptr->num_text = 0;
  418. info_ptr->max_text = 0;
  419. }
  420. }
  421. #endif
  422. #ifdef PNG_tRNS_SUPPORTED
  423. /* Free any tRNS entry */
  424. if (((mask & PNG_FREE_TRNS) & info_ptr->free_me) != 0)
  425. {
  426. info_ptr->valid &= ~PNG_INFO_tRNS;
  427. png_free(png_ptr, info_ptr->trans_alpha);
  428. info_ptr->trans_alpha = NULL;
  429. info_ptr->num_trans = 0;
  430. }
  431. #endif
  432. #ifdef PNG_sCAL_SUPPORTED
  433. /* Free any sCAL entry */
  434. if (((mask & PNG_FREE_SCAL) & info_ptr->free_me) != 0)
  435. {
  436. png_free(png_ptr, info_ptr->scal_s_width);
  437. png_free(png_ptr, info_ptr->scal_s_height);
  438. info_ptr->scal_s_width = NULL;
  439. info_ptr->scal_s_height = NULL;
  440. info_ptr->valid &= ~PNG_INFO_sCAL;
  441. }
  442. #endif
  443. #ifdef PNG_pCAL_SUPPORTED
  444. /* Free any pCAL entry */
  445. if (((mask & PNG_FREE_PCAL) & info_ptr->free_me) != 0)
  446. {
  447. png_free(png_ptr, info_ptr->pcal_purpose);
  448. png_free(png_ptr, info_ptr->pcal_units);
  449. info_ptr->pcal_purpose = NULL;
  450. info_ptr->pcal_units = NULL;
  451. if (info_ptr->pcal_params != NULL)
  452. {
  453. int i;
  454. for (i = 0; i < info_ptr->pcal_nparams; i++)
  455. png_free(png_ptr, info_ptr->pcal_params[i]);
  456. png_free(png_ptr, info_ptr->pcal_params);
  457. info_ptr->pcal_params = NULL;
  458. }
  459. info_ptr->valid &= ~PNG_INFO_pCAL;
  460. }
  461. #endif
  462. #ifdef PNG_iCCP_SUPPORTED
  463. /* Free any profile entry */
  464. if (((mask & PNG_FREE_ICCP) & info_ptr->free_me) != 0)
  465. {
  466. png_free(png_ptr, info_ptr->iccp_name);
  467. png_free(png_ptr, info_ptr->iccp_profile);
  468. info_ptr->iccp_name = NULL;
  469. info_ptr->iccp_profile = NULL;
  470. info_ptr->valid &= ~PNG_INFO_iCCP;
  471. }
  472. #endif
  473. #ifdef PNG_sPLT_SUPPORTED
  474. /* Free a given sPLT entry, or (if num == -1) all sPLT entries */
  475. if (info_ptr->splt_palettes != NULL &&
  476. ((mask & PNG_FREE_SPLT) & info_ptr->free_me) != 0)
  477. {
  478. if (num != -1)
  479. {
  480. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  481. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  482. info_ptr->splt_palettes[num].name = NULL;
  483. info_ptr->splt_palettes[num].entries = NULL;
  484. }
  485. else
  486. {
  487. int i;
  488. for (i = 0; i < info_ptr->splt_palettes_num; i++)
  489. {
  490. png_free(png_ptr, info_ptr->splt_palettes[i].name);
  491. png_free(png_ptr, info_ptr->splt_palettes[i].entries);
  492. }
  493. png_free(png_ptr, info_ptr->splt_palettes);
  494. info_ptr->splt_palettes = NULL;
  495. info_ptr->splt_palettes_num = 0;
  496. info_ptr->valid &= ~PNG_INFO_sPLT;
  497. }
  498. }
  499. #endif
  500. #ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
  501. if (info_ptr->unknown_chunks != NULL &&
  502. ((mask & PNG_FREE_UNKN) & info_ptr->free_me) != 0)
  503. {
  504. if (num != -1)
  505. {
  506. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  507. info_ptr->unknown_chunks[num].data = NULL;
  508. }
  509. else
  510. {
  511. int i;
  512. for (i = 0; i < info_ptr->unknown_chunks_num; i++)
  513. png_free(png_ptr, info_ptr->unknown_chunks[i].data);
  514. png_free(png_ptr, info_ptr->unknown_chunks);
  515. info_ptr->unknown_chunks = NULL;
  516. info_ptr->unknown_chunks_num = 0;
  517. }
  518. }
  519. #endif
  520. #ifdef PNG_eXIf_SUPPORTED
  521. /* Free any eXIf entry */
  522. if (((mask & PNG_FREE_EXIF) & info_ptr->free_me) != 0)
  523. {
  524. if (info_ptr->exif)
  525. {
  526. png_free(png_ptr, info_ptr->exif);
  527. info_ptr->exif = NULL;
  528. }
  529. info_ptr->valid &= ~PNG_INFO_eXIf;
  530. }
  531. #endif
  532. #ifdef PNG_hIST_SUPPORTED
  533. /* Free any hIST entry */
  534. if (((mask & PNG_FREE_HIST) & info_ptr->free_me) != 0)
  535. {
  536. png_free(png_ptr, info_ptr->hist);
  537. info_ptr->hist = NULL;
  538. info_ptr->valid &= ~PNG_INFO_hIST;
  539. }
  540. #endif
  541. /* Free any PLTE entry that was internally allocated */
  542. if (((mask & PNG_FREE_PLTE) & info_ptr->free_me) != 0)
  543. {
  544. png_free(png_ptr, info_ptr->palette);
  545. info_ptr->palette = NULL;
  546. info_ptr->valid &= ~PNG_INFO_PLTE;
  547. info_ptr->num_palette = 0;
  548. }
  549. #ifdef PNG_INFO_IMAGE_SUPPORTED
  550. /* Free any image bits attached to the info structure */
  551. if (((mask & PNG_FREE_ROWS) & info_ptr->free_me) != 0)
  552. {
  553. if (info_ptr->row_pointers != NULL)
  554. {
  555. png_uint_32 row;
  556. for (row = 0; row < info_ptr->height; row++)
  557. png_free(png_ptr, info_ptr->row_pointers[row]);
  558. png_free(png_ptr, info_ptr->row_pointers);
  559. info_ptr->row_pointers = NULL;
  560. }
  561. info_ptr->valid &= ~PNG_INFO_IDAT;
  562. }
  563. #endif
  564. if (num != -1)
  565. mask &= ~PNG_FREE_MUL;
  566. info_ptr->free_me &= ~mask;
  567. }
  568. #endif /* READ || WRITE */
  569. /* This function returns a pointer to the io_ptr associated with the user
  570. * functions. The application should free any memory associated with this
  571. * pointer before png_write_destroy() or png_read_destroy() are called.
  572. */
  573. png_voidp PNGAPI
  574. png_get_io_ptr(png_const_structrp png_ptr)
  575. {
  576. if (png_ptr == NULL)
  577. return NULL;
  578. return png_ptr->io_ptr;
  579. }
  580. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  581. # ifdef PNG_STDIO_SUPPORTED
  582. /* Initialize the default input/output functions for the PNG file. If you
  583. * use your own read or write routines, you can call either png_set_read_fn()
  584. * or png_set_write_fn() instead of png_init_io(). If you have defined
  585. * PNG_NO_STDIO or otherwise disabled PNG_STDIO_SUPPORTED, you must use a
  586. * function of your own because "FILE *" isn't necessarily available.
  587. */
  588. void PNGAPI
  589. png_init_io(png_structrp png_ptr, FILE *fp)
  590. {
  591. png_debug(1, "in png_init_io");
  592. if (png_ptr == NULL)
  593. return;
  594. png_ptr->io_ptr = (png_voidp)fp;
  595. }
  596. # endif
  597. # ifdef PNG_SAVE_INT_32_SUPPORTED
  598. /* PNG signed integers are saved in 32-bit 2's complement format. ANSI C-90
  599. * defines a cast of a signed integer to an unsigned integer either to preserve
  600. * the value, if it is positive, or to calculate:
  601. *
  602. * (UNSIGNED_MAX+1) + integer
  603. *
  604. * Where UNSIGNED_MAX is the appropriate maximum unsigned value, so when the
  605. * negative integral value is added the result will be an unsigned value
  606. * corresponding to the 2's complement representation.
  607. */
  608. void PNGAPI
  609. png_save_int_32(png_bytep buf, png_int_32 i)
  610. {
  611. png_save_uint_32(buf, (png_uint_32)i);
  612. }
  613. # endif
  614. # ifdef PNG_TIME_RFC1123_SUPPORTED
  615. /* Convert the supplied time into an RFC 1123 string suitable for use in
  616. * a "Creation Time" or other text-based time string.
  617. */
  618. int PNGAPI
  619. png_convert_to_rfc1123_buffer(char out[29], png_const_timep ptime)
  620. {
  621. static const char short_months[12][4] =
  622. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  623. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  624. if (out == NULL)
  625. return 0;
  626. if (ptime->year > 9999 /* RFC1123 limitation */ ||
  627. ptime->month == 0 || ptime->month > 12 ||
  628. ptime->day == 0 || ptime->day > 31 ||
  629. ptime->hour > 23 || ptime->minute > 59 ||
  630. ptime->second > 60)
  631. return 0;
  632. {
  633. size_t pos = 0;
  634. char number_buf[5] = {0, 0, 0, 0, 0}; /* enough for a four-digit year */
  635. # define APPEND_STRING(string) pos = png_safecat(out, 29, pos, (string))
  636. # define APPEND_NUMBER(format, value)\
  637. APPEND_STRING(PNG_FORMAT_NUMBER(number_buf, format, (value)))
  638. # define APPEND(ch) if (pos < 28) out[pos++] = (ch)
  639. APPEND_NUMBER(PNG_NUMBER_FORMAT_u, (unsigned)ptime->day);
  640. APPEND(' ');
  641. APPEND_STRING(short_months[(ptime->month - 1)]);
  642. APPEND(' ');
  643. APPEND_NUMBER(PNG_NUMBER_FORMAT_u, ptime->year);
  644. APPEND(' ');
  645. APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->hour);
  646. APPEND(':');
  647. APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->minute);
  648. APPEND(':');
  649. APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->second);
  650. APPEND_STRING(" +0000"); /* This reliably terminates the buffer */
  651. PNG_UNUSED (pos)
  652. # undef APPEND
  653. # undef APPEND_NUMBER
  654. # undef APPEND_STRING
  655. }
  656. return 1;
  657. }
  658. # if PNG_LIBPNG_VER < 10700
  659. /* To do: remove the following from libpng-1.7 */
  660. /* Original API that uses a private buffer in png_struct.
  661. * Deprecated because it causes png_struct to carry a spurious temporary
  662. * buffer (png_struct::time_buffer), better to have the caller pass this in.
  663. */
  664. png_const_charp PNGAPI
  665. png_convert_to_rfc1123(png_structrp png_ptr, png_const_timep ptime)
  666. {
  667. if (png_ptr != NULL)
  668. {
  669. /* The only failure above if png_ptr != NULL is from an invalid ptime */
  670. if (png_convert_to_rfc1123_buffer(png_ptr->time_buffer, ptime) == 0)
  671. png_warning(png_ptr, "Ignoring invalid time value");
  672. else
  673. return png_ptr->time_buffer;
  674. }
  675. return NULL;
  676. }
  677. # endif /* LIBPNG_VER < 10700 */
  678. # endif /* TIME_RFC1123 */
  679. #endif /* READ || WRITE */
  680. png_const_charp PNGAPI
  681. png_get_copyright(png_const_structrp png_ptr)
  682. {
  683. PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
  684. #ifdef PNG_STRING_COPYRIGHT
  685. return PNG_STRING_COPYRIGHT
  686. #else
  687. return PNG_STRING_NEWLINE \
  688. "libpng version 1.6.48" PNG_STRING_NEWLINE \
  689. "Copyright (c) 2018-2025 Cosmin Truta" PNG_STRING_NEWLINE \
  690. "Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson" \
  691. PNG_STRING_NEWLINE \
  692. "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
  693. "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
  694. PNG_STRING_NEWLINE;
  695. #endif
  696. }
  697. /* The following return the library version as a short string in the
  698. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  699. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  700. * is defined in png.h.
  701. * Note: now there is no difference between png_get_libpng_ver() and
  702. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  703. * it is guaranteed that png.c uses the correct version of png.h.
  704. */
  705. png_const_charp PNGAPI
  706. png_get_libpng_ver(png_const_structrp png_ptr)
  707. {
  708. /* Version of *.c files used when building libpng */
  709. return png_get_header_ver(png_ptr);
  710. }
  711. png_const_charp PNGAPI
  712. png_get_header_ver(png_const_structrp png_ptr)
  713. {
  714. /* Version of *.h files used when building libpng */
  715. PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
  716. return PNG_LIBPNG_VER_STRING;
  717. }
  718. png_const_charp PNGAPI
  719. png_get_header_version(png_const_structrp png_ptr)
  720. {
  721. /* Returns longer string containing both version and date */
  722. PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
  723. #ifdef __STDC__
  724. return PNG_HEADER_VERSION_STRING
  725. # ifndef PNG_READ_SUPPORTED
  726. " (NO READ SUPPORT)"
  727. # endif
  728. PNG_STRING_NEWLINE;
  729. #else
  730. return PNG_HEADER_VERSION_STRING;
  731. #endif
  732. }
  733. #ifdef PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED
  734. /* NOTE: this routine is not used internally! */
  735. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  736. * large of png_color. This lets grayscale images be treated as
  737. * paletted. Most useful for gamma correction and simplification
  738. * of code. This API is not used internally.
  739. */
  740. void PNGAPI
  741. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  742. {
  743. int num_palette;
  744. int color_inc;
  745. int i;
  746. int v;
  747. png_debug(1, "in png_do_build_grayscale_palette");
  748. if (palette == NULL)
  749. return;
  750. switch (bit_depth)
  751. {
  752. case 1:
  753. num_palette = 2;
  754. color_inc = 0xff;
  755. break;
  756. case 2:
  757. num_palette = 4;
  758. color_inc = 0x55;
  759. break;
  760. case 4:
  761. num_palette = 16;
  762. color_inc = 0x11;
  763. break;
  764. case 8:
  765. num_palette = 256;
  766. color_inc = 1;
  767. break;
  768. default:
  769. num_palette = 0;
  770. color_inc = 0;
  771. break;
  772. }
  773. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  774. {
  775. palette[i].red = (png_byte)(v & 0xff);
  776. palette[i].green = (png_byte)(v & 0xff);
  777. palette[i].blue = (png_byte)(v & 0xff);
  778. }
  779. }
  780. #endif
  781. #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
  782. int PNGAPI
  783. png_handle_as_unknown(png_const_structrp png_ptr, png_const_bytep chunk_name)
  784. {
  785. /* Check chunk_name and return "keep" value if it's on the list, else 0 */
  786. png_const_bytep p, p_end;
  787. if (png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list == 0)
  788. return PNG_HANDLE_CHUNK_AS_DEFAULT;
  789. p_end = png_ptr->chunk_list;
  790. p = p_end + png_ptr->num_chunk_list*5; /* beyond end */
  791. /* The code is the fifth byte after each four byte string. Historically this
  792. * code was always searched from the end of the list, this is no longer
  793. * necessary because the 'set' routine handles duplicate entries correctly.
  794. */
  795. do /* num_chunk_list > 0, so at least one */
  796. {
  797. p -= 5;
  798. if (memcmp(chunk_name, p, 4) == 0)
  799. return p[4];
  800. }
  801. while (p > p_end);
  802. /* This means that known chunks should be processed and unknown chunks should
  803. * be handled according to the value of png_ptr->unknown_default; this can be
  804. * confusing because, as a result, there are two levels of defaulting for
  805. * unknown chunks.
  806. */
  807. return PNG_HANDLE_CHUNK_AS_DEFAULT;
  808. }
  809. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) ||\
  810. defined(PNG_HANDLE_AS_UNKNOWN_SUPPORTED)
  811. int /* PRIVATE */
  812. png_chunk_unknown_handling(png_const_structrp png_ptr, png_uint_32 chunk_name)
  813. {
  814. png_byte chunk_string[5];
  815. PNG_CSTRING_FROM_CHUNK(chunk_string, chunk_name);
  816. return png_handle_as_unknown(png_ptr, chunk_string);
  817. }
  818. #endif /* READ_UNKNOWN_CHUNKS || HANDLE_AS_UNKNOWN */
  819. #endif /* SET_UNKNOWN_CHUNKS */
  820. #ifdef PNG_READ_SUPPORTED
  821. /* This function, added to libpng-1.0.6g, is untested. */
  822. int PNGAPI
  823. png_reset_zstream(png_structrp png_ptr)
  824. {
  825. if (png_ptr == NULL)
  826. return Z_STREAM_ERROR;
  827. /* WARNING: this resets the window bits to the maximum! */
  828. return inflateReset(&png_ptr->zstream);
  829. }
  830. #endif /* READ */
  831. /* This function was added to libpng-1.0.7 */
  832. png_uint_32 PNGAPI
  833. png_access_version_number(void)
  834. {
  835. /* Version of *.c files used when building libpng */
  836. return (png_uint_32)PNG_LIBPNG_VER;
  837. }
  838. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  839. /* Ensure that png_ptr->zstream.msg holds some appropriate error message string.
  840. * If it doesn't 'ret' is used to set it to something appropriate, even in cases
  841. * like Z_OK or Z_STREAM_END where the error code is apparently a success code.
  842. */
  843. void /* PRIVATE */
  844. png_zstream_error(png_structrp png_ptr, int ret)
  845. {
  846. /* Translate 'ret' into an appropriate error string, priority is given to the
  847. * one in zstream if set. This always returns a string, even in cases like
  848. * Z_OK or Z_STREAM_END where the error code is a success code.
  849. */
  850. if (png_ptr->zstream.msg == NULL) switch (ret)
  851. {
  852. default:
  853. case Z_OK:
  854. png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected zlib return code");
  855. break;
  856. case Z_STREAM_END:
  857. /* Normal exit */
  858. png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected end of LZ stream");
  859. break;
  860. case Z_NEED_DICT:
  861. /* This means the deflate stream did not have a dictionary; this
  862. * indicates a bogus PNG.
  863. */
  864. png_ptr->zstream.msg = PNGZ_MSG_CAST("missing LZ dictionary");
  865. break;
  866. case Z_ERRNO:
  867. /* gz APIs only: should not happen */
  868. png_ptr->zstream.msg = PNGZ_MSG_CAST("zlib IO error");
  869. break;
  870. case Z_STREAM_ERROR:
  871. /* internal libpng error */
  872. png_ptr->zstream.msg = PNGZ_MSG_CAST("bad parameters to zlib");
  873. break;
  874. case Z_DATA_ERROR:
  875. png_ptr->zstream.msg = PNGZ_MSG_CAST("damaged LZ stream");
  876. break;
  877. case Z_MEM_ERROR:
  878. png_ptr->zstream.msg = PNGZ_MSG_CAST("insufficient memory");
  879. break;
  880. case Z_BUF_ERROR:
  881. /* End of input or output; not a problem if the caller is doing
  882. * incremental read or write.
  883. */
  884. png_ptr->zstream.msg = PNGZ_MSG_CAST("truncated");
  885. break;
  886. case Z_VERSION_ERROR:
  887. png_ptr->zstream.msg = PNGZ_MSG_CAST("unsupported zlib version");
  888. break;
  889. case PNG_UNEXPECTED_ZLIB_RETURN:
  890. /* Compile errors here mean that zlib now uses the value co-opted in
  891. * pngpriv.h for PNG_UNEXPECTED_ZLIB_RETURN; update the switch above
  892. * and change pngpriv.h. Note that this message is "... return",
  893. * whereas the default/Z_OK one is "... return code".
  894. */
  895. png_ptr->zstream.msg = PNGZ_MSG_CAST("unexpected zlib return");
  896. break;
  897. }
  898. }
  899. #ifdef PNG_COLORSPACE_SUPPORTED
  900. static png_int_32
  901. png_fp_add(png_int_32 addend0, png_int_32 addend1, int *error)
  902. {
  903. /* Safely add two fixed point values setting an error flag and returning 0.5
  904. * on overflow.
  905. * IMPLEMENTATION NOTE: ANSI requires signed overflow not to occur, therefore
  906. * relying on addition of two positive values producing a negative one is not
  907. * safe.
  908. */
  909. if (addend0 > 0)
  910. {
  911. if (0x7fffffff - addend0 >= addend1)
  912. return addend0+addend1;
  913. }
  914. else if (addend0 < 0)
  915. {
  916. if (-0x7fffffff - addend0 <= addend1)
  917. return addend0+addend1;
  918. }
  919. else
  920. return addend1;
  921. *error = 1;
  922. return PNG_FP_1/2;
  923. }
  924. static png_int_32
  925. png_fp_sub(png_int_32 addend0, png_int_32 addend1, int *error)
  926. {
  927. /* As above but calculate addend0-addend1. */
  928. if (addend1 > 0)
  929. {
  930. if (-0x7fffffff + addend1 <= addend0)
  931. return addend0-addend1;
  932. }
  933. else if (addend1 < 0)
  934. {
  935. if (0x7fffffff + addend1 >= addend0)
  936. return addend0-addend1;
  937. }
  938. else
  939. return addend0;
  940. *error = 1;
  941. return PNG_FP_1/2;
  942. }
  943. static int
  944. png_safe_add(png_int_32 *addend0_and_result, png_int_32 addend1,
  945. png_int_32 addend2)
  946. {
  947. /* Safely add three integers. Returns 0 on success, 1 on overflow. Does not
  948. * set the result on overflow.
  949. */
  950. int error = 0;
  951. int result = png_fp_add(*addend0_and_result,
  952. png_fp_add(addend1, addend2, &error),
  953. &error);
  954. if (!error) *addend0_and_result = result;
  955. return error;
  956. }
  957. /* Added at libpng-1.5.5 to support read and write of true CIEXYZ values for
  958. * cHRM, as opposed to using chromaticities. These internal APIs return
  959. * non-zero on a parameter error. The X, Y and Z values are required to be
  960. * positive and less than 1.0.
  961. */
  962. int /* PRIVATE */
  963. png_xy_from_XYZ(png_xy *xy, const png_XYZ *XYZ)
  964. {
  965. /* NOTE: returns 0 on success, 1 means error. */
  966. png_int_32 d, dred, dgreen, dblue, dwhite, whiteX, whiteY;
  967. /* 'd' in each of the blocks below is just X+Y+Z for each component,
  968. * x, y and z are X,Y,Z/(X+Y+Z).
  969. */
  970. d = XYZ->red_X;
  971. if (png_safe_add(&d, XYZ->red_Y, XYZ->red_Z))
  972. return 1;
  973. dred = d;
  974. if (png_muldiv(&xy->redx, XYZ->red_X, PNG_FP_1, dred) == 0)
  975. return 1;
  976. if (png_muldiv(&xy->redy, XYZ->red_Y, PNG_FP_1, dred) == 0)
  977. return 1;
  978. d = XYZ->green_X;
  979. if (png_safe_add(&d, XYZ->green_Y, XYZ->green_Z))
  980. return 1;
  981. dgreen = d;
  982. if (png_muldiv(&xy->greenx, XYZ->green_X, PNG_FP_1, dgreen) == 0)
  983. return 1;
  984. if (png_muldiv(&xy->greeny, XYZ->green_Y, PNG_FP_1, dgreen) == 0)
  985. return 1;
  986. d = XYZ->blue_X;
  987. if (png_safe_add(&d, XYZ->blue_Y, XYZ->blue_Z))
  988. return 1;
  989. dblue = d;
  990. if (png_muldiv(&xy->bluex, XYZ->blue_X, PNG_FP_1, dblue) == 0)
  991. return 1;
  992. if (png_muldiv(&xy->bluey, XYZ->blue_Y, PNG_FP_1, dblue) == 0)
  993. return 1;
  994. /* The reference white is simply the sum of the end-point (X,Y,Z) vectors so
  995. * the fillowing calculates (X+Y+Z) of the reference white (media white,
  996. * encoding white) itself:
  997. */
  998. d = dblue;
  999. if (png_safe_add(&d, dred, dgreen))
  1000. return 1;
  1001. dwhite = d;
  1002. /* Find the white X,Y values from the sum of the red, green and blue X,Y
  1003. * values.
  1004. */
  1005. d = XYZ->red_X;
  1006. if (png_safe_add(&d, XYZ->green_X, XYZ->blue_X))
  1007. return 1;
  1008. whiteX = d;
  1009. d = XYZ->red_Y;
  1010. if (png_safe_add(&d, XYZ->green_Y, XYZ->blue_Y))
  1011. return 1;
  1012. whiteY = d;
  1013. if (png_muldiv(&xy->whitex, whiteX, PNG_FP_1, dwhite) == 0)
  1014. return 1;
  1015. if (png_muldiv(&xy->whitey, whiteY, PNG_FP_1, dwhite) == 0)
  1016. return 1;
  1017. return 0;
  1018. }
  1019. int /* PRIVATE */
  1020. png_XYZ_from_xy(png_XYZ *XYZ, const png_xy *xy)
  1021. {
  1022. /* NOTE: returns 0 on success, 1 means error. */
  1023. png_fixed_point red_inverse, green_inverse, blue_scale;
  1024. png_fixed_point left, right, denominator;
  1025. /* Check xy and, implicitly, z. Note that wide gamut color spaces typically
  1026. * have end points with 0 tristimulus values (these are impossible end
  1027. * points, but they are used to cover the possible colors). We check
  1028. * xy->whitey against 5, not 0, to avoid a possible integer overflow.
  1029. *
  1030. * The limits here will *not* accept ACES AP0, where bluey is -7700
  1031. * (-0.0770) because the PNG spec itself requires the xy values to be
  1032. * unsigned. whitey is also required to be 5 or more to avoid overflow.
  1033. *
  1034. * Instead the upper limits have been relaxed to accomodate ACES AP1 where
  1035. * redz ends up as -600 (-0.006). ProPhotoRGB was already "in range."
  1036. * The new limit accomodates the AP0 and AP1 ranges for z but not AP0 redy.
  1037. */
  1038. const png_fixed_point fpLimit = PNG_FP_1+(PNG_FP_1/10);
  1039. if (xy->redx < 0 || xy->redx > fpLimit) return 1;
  1040. if (xy->redy < 0 || xy->redy > fpLimit-xy->redx) return 1;
  1041. if (xy->greenx < 0 || xy->greenx > fpLimit) return 1;
  1042. if (xy->greeny < 0 || xy->greeny > fpLimit-xy->greenx) return 1;
  1043. if (xy->bluex < 0 || xy->bluex > fpLimit) return 1;
  1044. if (xy->bluey < 0 || xy->bluey > fpLimit-xy->bluex) return 1;
  1045. if (xy->whitex < 0 || xy->whitex > fpLimit) return 1;
  1046. if (xy->whitey < 5 || xy->whitey > fpLimit-xy->whitex) return 1;
  1047. /* The reverse calculation is more difficult because the original tristimulus
  1048. * value had 9 independent values (red,green,blue)x(X,Y,Z) however only 8
  1049. * derived values were recorded in the cHRM chunk;
  1050. * (red,green,blue,white)x(x,y). This loses one degree of freedom and
  1051. * therefore an arbitrary ninth value has to be introduced to undo the
  1052. * original transformations.
  1053. *
  1054. * Think of the original end-points as points in (X,Y,Z) space. The
  1055. * chromaticity values (c) have the property:
  1056. *
  1057. * C
  1058. * c = ---------
  1059. * X + Y + Z
  1060. *
  1061. * For each c (x,y,z) from the corresponding original C (X,Y,Z). Thus the
  1062. * three chromaticity values (x,y,z) for each end-point obey the
  1063. * relationship:
  1064. *
  1065. * x + y + z = 1
  1066. *
  1067. * This describes the plane in (X,Y,Z) space that intersects each axis at the
  1068. * value 1.0; call this the chromaticity plane. Thus the chromaticity
  1069. * calculation has scaled each end-point so that it is on the x+y+z=1 plane
  1070. * and chromaticity is the intersection of the vector from the origin to the
  1071. * (X,Y,Z) value with the chromaticity plane.
  1072. *
  1073. * To fully invert the chromaticity calculation we would need the three
  1074. * end-point scale factors, (red-scale, green-scale, blue-scale), but these
  1075. * were not recorded. Instead we calculated the reference white (X,Y,Z) and
  1076. * recorded the chromaticity of this. The reference white (X,Y,Z) would have
  1077. * given all three of the scale factors since:
  1078. *
  1079. * color-C = color-c * color-scale
  1080. * white-C = red-C + green-C + blue-C
  1081. * = red-c*red-scale + green-c*green-scale + blue-c*blue-scale
  1082. *
  1083. * But cHRM records only white-x and white-y, so we have lost the white scale
  1084. * factor:
  1085. *
  1086. * white-C = white-c*white-scale
  1087. *
  1088. * To handle this the inverse transformation makes an arbitrary assumption
  1089. * about white-scale:
  1090. *
  1091. * Assume: white-Y = 1.0
  1092. * Hence: white-scale = 1/white-y
  1093. * Or: red-Y + green-Y + blue-Y = 1.0
  1094. *
  1095. * Notice the last statement of the assumption gives an equation in three of
  1096. * the nine values we want to calculate. 8 more equations come from the
  1097. * above routine as summarised at the top above (the chromaticity
  1098. * calculation):
  1099. *
  1100. * Given: color-x = color-X / (color-X + color-Y + color-Z)
  1101. * Hence: (color-x - 1)*color-X + color.x*color-Y + color.x*color-Z = 0
  1102. *
  1103. * This is 9 simultaneous equations in the 9 variables "color-C" and can be
  1104. * solved by Cramer's rule. Cramer's rule requires calculating 10 9x9 matrix
  1105. * determinants, however this is not as bad as it seems because only 28 of
  1106. * the total of 90 terms in the various matrices are non-zero. Nevertheless
  1107. * Cramer's rule is notoriously numerically unstable because the determinant
  1108. * calculation involves the difference of large, but similar, numbers. It is
  1109. * difficult to be sure that the calculation is stable for real world values
  1110. * and it is certain that it becomes unstable where the end points are close
  1111. * together.
  1112. *
  1113. * So this code uses the perhaps slightly less optimal but more
  1114. * understandable and totally obvious approach of calculating color-scale.
  1115. *
  1116. * This algorithm depends on the precision in white-scale and that is
  1117. * (1/white-y), so we can immediately see that as white-y approaches 0 the
  1118. * accuracy inherent in the cHRM chunk drops off substantially.
  1119. *
  1120. * libpng arithmetic: a simple inversion of the above equations
  1121. * ------------------------------------------------------------
  1122. *
  1123. * white_scale = 1/white-y
  1124. * white-X = white-x * white-scale
  1125. * white-Y = 1.0
  1126. * white-Z = (1 - white-x - white-y) * white_scale
  1127. *
  1128. * white-C = red-C + green-C + blue-C
  1129. * = red-c*red-scale + green-c*green-scale + blue-c*blue-scale
  1130. *
  1131. * This gives us three equations in (red-scale,green-scale,blue-scale) where
  1132. * all the coefficients are now known:
  1133. *
  1134. * red-x*red-scale + green-x*green-scale + blue-x*blue-scale
  1135. * = white-x/white-y
  1136. * red-y*red-scale + green-y*green-scale + blue-y*blue-scale = 1
  1137. * red-z*red-scale + green-z*green-scale + blue-z*blue-scale
  1138. * = (1 - white-x - white-y)/white-y
  1139. *
  1140. * In the last equation color-z is (1 - color-x - color-y) so we can add all
  1141. * three equations together to get an alternative third:
  1142. *
  1143. * red-scale + green-scale + blue-scale = 1/white-y = white-scale
  1144. *
  1145. * So now we have a Cramer's rule solution where the determinants are just
  1146. * 3x3 - far more tractible. Unfortunately 3x3 determinants still involve
  1147. * multiplication of three coefficients so we can't guarantee to avoid
  1148. * overflow in the libpng fixed point representation. Using Cramer's rule in
  1149. * floating point is probably a good choice here, but it's not an option for
  1150. * fixed point. Instead proceed to simplify the first two equations by
  1151. * eliminating what is likely to be the largest value, blue-scale:
  1152. *
  1153. * blue-scale = white-scale - red-scale - green-scale
  1154. *
  1155. * Hence:
  1156. *
  1157. * (red-x - blue-x)*red-scale + (green-x - blue-x)*green-scale =
  1158. * (white-x - blue-x)*white-scale
  1159. *
  1160. * (red-y - blue-y)*red-scale + (green-y - blue-y)*green-scale =
  1161. * 1 - blue-y*white-scale
  1162. *
  1163. * And now we can trivially solve for (red-scale,green-scale):
  1164. *
  1165. * green-scale =
  1166. * (white-x - blue-x)*white-scale - (red-x - blue-x)*red-scale
  1167. * -----------------------------------------------------------
  1168. * green-x - blue-x
  1169. *
  1170. * red-scale =
  1171. * 1 - blue-y*white-scale - (green-y - blue-y) * green-scale
  1172. * ---------------------------------------------------------
  1173. * red-y - blue-y
  1174. *
  1175. * Hence:
  1176. *
  1177. * red-scale =
  1178. * ( (green-x - blue-x) * (white-y - blue-y) -
  1179. * (green-y - blue-y) * (white-x - blue-x) ) / white-y
  1180. * -------------------------------------------------------------------------
  1181. * (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)
  1182. *
  1183. * green-scale =
  1184. * ( (red-y - blue-y) * (white-x - blue-x) -
  1185. * (red-x - blue-x) * (white-y - blue-y) ) / white-y
  1186. * -------------------------------------------------------------------------
  1187. * (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)
  1188. *
  1189. * Accuracy:
  1190. * The input values have 5 decimal digits of accuracy.
  1191. *
  1192. * In the previous implementation the values were all in the range 0 < value
  1193. * < 1, so simple products are in the same range but may need up to 10
  1194. * decimal digits to preserve the original precision and avoid underflow.
  1195. * Because we are using a 32-bit signed representation we cannot match this;
  1196. * the best is a little over 9 decimal digits, less than 10.
  1197. *
  1198. * This range has now been extended to allow values up to 1.1, or 110,000 in
  1199. * fixed point.
  1200. *
  1201. * The approach used here is to preserve the maximum precision within the
  1202. * signed representation. Because the red-scale calculation above uses the
  1203. * difference between two products of values that must be in the range
  1204. * -1.1..+1.1 it is sufficient to divide the product by 8;
  1205. * ceil(121,000/32767*2). The factor is irrelevant in the calculation
  1206. * because it is applied to both numerator and denominator.
  1207. *
  1208. * Note that the values of the differences of the products of the
  1209. * chromaticities in the above equations tend to be small, for example for
  1210. * the sRGB chromaticities they are:
  1211. *
  1212. * red numerator: -0.04751
  1213. * green numerator: -0.08788
  1214. * denominator: -0.2241 (without white-y multiplication)
  1215. *
  1216. * The resultant Y coefficients from the chromaticities of some widely used
  1217. * color space definitions are (to 15 decimal places):
  1218. *
  1219. * sRGB
  1220. * 0.212639005871510 0.715168678767756 0.072192315360734
  1221. * Kodak ProPhoto
  1222. * 0.288071128229293 0.711843217810102 0.000085653960605
  1223. * Adobe RGB
  1224. * 0.297344975250536 0.627363566255466 0.075291458493998
  1225. * Adobe Wide Gamut RGB
  1226. * 0.258728243040113 0.724682314948566 0.016589442011321
  1227. */
  1228. {
  1229. int error = 0;
  1230. /* By the argument above overflow should be impossible here, however the
  1231. * code now simply returns a failure code. The xy subtracts in the
  1232. * arguments to png_muldiv are *not* checked for overflow because the
  1233. * checks at the start guarantee they are in the range 0..110000 and
  1234. * png_fixed_point is a 32-bit signed number.
  1235. */
  1236. if (png_muldiv(&left, xy->greenx-xy->bluex, xy->redy - xy->bluey, 8) == 0)
  1237. return 1;
  1238. if (png_muldiv(&right, xy->greeny-xy->bluey, xy->redx - xy->bluex, 8) ==
  1239. 0)
  1240. return 1;
  1241. denominator = png_fp_sub(left, right, &error);
  1242. if (error) return 1;
  1243. /* Now find the red numerator. */
  1244. if (png_muldiv(&left, xy->greenx-xy->bluex, xy->whitey-xy->bluey, 8) == 0)
  1245. return 1;
  1246. if (png_muldiv(&right, xy->greeny-xy->bluey, xy->whitex-xy->bluex, 8) ==
  1247. 0)
  1248. return 1;
  1249. /* Overflow is possible here and it indicates an extreme set of PNG cHRM
  1250. * chunk values. This calculation actually returns the reciprocal of the
  1251. * scale value because this allows us to delay the multiplication of
  1252. * white-y into the denominator, which tends to produce a small number.
  1253. */
  1254. if (png_muldiv(&red_inverse, xy->whitey, denominator,
  1255. png_fp_sub(left, right, &error)) == 0 || error ||
  1256. red_inverse <= xy->whitey /* r+g+b scales = white scale */)
  1257. return 1;
  1258. /* Similarly for green_inverse: */
  1259. if (png_muldiv(&left, xy->redy-xy->bluey, xy->whitex-xy->bluex, 8) == 0)
  1260. return 1;
  1261. if (png_muldiv(&right, xy->redx-xy->bluex, xy->whitey-xy->bluey, 8) == 0)
  1262. return 1;
  1263. if (png_muldiv(&green_inverse, xy->whitey, denominator,
  1264. png_fp_sub(left, right, &error)) == 0 || error ||
  1265. green_inverse <= xy->whitey)
  1266. return 1;
  1267. /* And the blue scale, the checks above guarantee this can't overflow but
  1268. * it can still produce 0 for extreme cHRM values.
  1269. */
  1270. blue_scale = png_fp_sub(png_fp_sub(png_reciprocal(xy->whitey),
  1271. png_reciprocal(red_inverse), &error),
  1272. png_reciprocal(green_inverse), &error);
  1273. if (error || blue_scale <= 0)
  1274. return 1;
  1275. }
  1276. /* And fill in the png_XYZ. Again the subtracts are safe because of the
  1277. * checks on the xy values at the start (the subtracts just calculate the
  1278. * corresponding z values.)
  1279. */
  1280. if (png_muldiv(&XYZ->red_X, xy->redx, PNG_FP_1, red_inverse) == 0)
  1281. return 1;
  1282. if (png_muldiv(&XYZ->red_Y, xy->redy, PNG_FP_1, red_inverse) == 0)
  1283. return 1;
  1284. if (png_muldiv(&XYZ->red_Z, PNG_FP_1 - xy->redx - xy->redy, PNG_FP_1,
  1285. red_inverse) == 0)
  1286. return 1;
  1287. if (png_muldiv(&XYZ->green_X, xy->greenx, PNG_FP_1, green_inverse) == 0)
  1288. return 1;
  1289. if (png_muldiv(&XYZ->green_Y, xy->greeny, PNG_FP_1, green_inverse) == 0)
  1290. return 1;
  1291. if (png_muldiv(&XYZ->green_Z, PNG_FP_1 - xy->greenx - xy->greeny, PNG_FP_1,
  1292. green_inverse) == 0)
  1293. return 1;
  1294. if (png_muldiv(&XYZ->blue_X, xy->bluex, blue_scale, PNG_FP_1) == 0)
  1295. return 1;
  1296. if (png_muldiv(&XYZ->blue_Y, xy->bluey, blue_scale, PNG_FP_1) == 0)
  1297. return 1;
  1298. if (png_muldiv(&XYZ->blue_Z, PNG_FP_1 - xy->bluex - xy->bluey, blue_scale,
  1299. PNG_FP_1) == 0)
  1300. return 1;
  1301. return 0; /*success*/
  1302. }
  1303. #endif /* COLORSPACE */
  1304. #ifdef PNG_READ_iCCP_SUPPORTED
  1305. /* Error message generation */
  1306. static char
  1307. png_icc_tag_char(png_uint_32 byte)
  1308. {
  1309. byte &= 0xff;
  1310. if (byte >= 32 && byte <= 126)
  1311. return (char)byte;
  1312. else
  1313. return '?';
  1314. }
  1315. static void
  1316. png_icc_tag_name(char *name, png_uint_32 tag)
  1317. {
  1318. name[0] = '\'';
  1319. name[1] = png_icc_tag_char(tag >> 24);
  1320. name[2] = png_icc_tag_char(tag >> 16);
  1321. name[3] = png_icc_tag_char(tag >> 8);
  1322. name[4] = png_icc_tag_char(tag );
  1323. name[5] = '\'';
  1324. }
  1325. static int
  1326. is_ICC_signature_char(png_alloc_size_t it)
  1327. {
  1328. return it == 32 || (it >= 48 && it <= 57) || (it >= 65 && it <= 90) ||
  1329. (it >= 97 && it <= 122);
  1330. }
  1331. static int
  1332. is_ICC_signature(png_alloc_size_t it)
  1333. {
  1334. return is_ICC_signature_char(it >> 24) /* checks all the top bits */ &&
  1335. is_ICC_signature_char((it >> 16) & 0xff) &&
  1336. is_ICC_signature_char((it >> 8) & 0xff) &&
  1337. is_ICC_signature_char(it & 0xff);
  1338. }
  1339. static int
  1340. png_icc_profile_error(png_const_structrp png_ptr, png_const_charp name,
  1341. png_alloc_size_t value, png_const_charp reason)
  1342. {
  1343. size_t pos;
  1344. char message[196]; /* see below for calculation */
  1345. pos = png_safecat(message, (sizeof message), 0, "profile '"); /* 9 chars */
  1346. pos = png_safecat(message, pos+79, pos, name); /* Truncate to 79 chars */
  1347. pos = png_safecat(message, (sizeof message), pos, "': "); /* +2 = 90 */
  1348. if (is_ICC_signature(value) != 0)
  1349. {
  1350. /* So 'value' is at most 4 bytes and the following cast is safe */
  1351. png_icc_tag_name(message+pos, (png_uint_32)value);
  1352. pos += 6; /* total +8; less than the else clause */
  1353. message[pos++] = ':';
  1354. message[pos++] = ' ';
  1355. }
  1356. # ifdef PNG_WARNINGS_SUPPORTED
  1357. else
  1358. {
  1359. char number[PNG_NUMBER_BUFFER_SIZE]; /* +24 = 114 */
  1360. pos = png_safecat(message, (sizeof message), pos,
  1361. png_format_number(number, number+(sizeof number),
  1362. PNG_NUMBER_FORMAT_x, value));
  1363. pos = png_safecat(message, (sizeof message), pos, "h: "); /* +2 = 116 */
  1364. }
  1365. # endif
  1366. /* The 'reason' is an arbitrary message, allow +79 maximum 195 */
  1367. pos = png_safecat(message, (sizeof message), pos, reason);
  1368. PNG_UNUSED(pos)
  1369. png_chunk_benign_error(png_ptr, message);
  1370. return 0;
  1371. }
  1372. /* Encoded value of D50 as an ICC XYZNumber. From the ICC 2010 spec the value
  1373. * is XYZ(0.9642,1.0,0.8249), which scales to:
  1374. *
  1375. * (63189.8112, 65536, 54060.6464)
  1376. */
  1377. static const png_byte D50_nCIEXYZ[12] =
  1378. { 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d };
  1379. static int /* bool */
  1380. icc_check_length(png_const_structrp png_ptr, png_const_charp name,
  1381. png_uint_32 profile_length)
  1382. {
  1383. if (profile_length < 132)
  1384. return png_icc_profile_error(png_ptr, name, profile_length, "too short");
  1385. return 1;
  1386. }
  1387. int /* PRIVATE */
  1388. png_icc_check_length(png_const_structrp png_ptr, png_const_charp name,
  1389. png_uint_32 profile_length)
  1390. {
  1391. if (!icc_check_length(png_ptr, name, profile_length))
  1392. return 0;
  1393. /* This needs to be here because the 'normal' check is in
  1394. * png_decompress_chunk, yet this happens after the attempt to
  1395. * png_malloc_base the required data. We only need this on read; on write
  1396. * the caller supplies the profile buffer so libpng doesn't allocate it. See
  1397. * the call to icc_check_length below (the write case).
  1398. */
  1399. if (profile_length > png_chunk_max(png_ptr))
  1400. return png_icc_profile_error(png_ptr, name, profile_length,
  1401. "profile too long");
  1402. return 1;
  1403. }
  1404. int /* PRIVATE */
  1405. png_icc_check_header(png_const_structrp png_ptr, png_const_charp name,
  1406. png_uint_32 profile_length,
  1407. png_const_bytep profile/* first 132 bytes only */, int color_type)
  1408. {
  1409. png_uint_32 temp;
  1410. /* Length check; this cannot be ignored in this code because profile_length
  1411. * is used later to check the tag table, so even if the profile seems over
  1412. * long profile_length from the caller must be correct. The caller can fix
  1413. * this up on read or write by just passing in the profile header length.
  1414. */
  1415. temp = png_get_uint_32(profile);
  1416. if (temp != profile_length)
  1417. return png_icc_profile_error(png_ptr, name, temp,
  1418. "length does not match profile");
  1419. temp = (png_uint_32) (*(profile+8));
  1420. if (temp > 3 && (profile_length & 3))
  1421. return png_icc_profile_error(png_ptr, name, profile_length,
  1422. "invalid length");
  1423. temp = png_get_uint_32(profile+128); /* tag count: 12 bytes/tag */
  1424. if (temp > 357913930 || /* (2^32-4-132)/12: maximum possible tag count */
  1425. profile_length < 132+12*temp) /* truncated tag table */
  1426. return png_icc_profile_error(png_ptr, name, temp,
  1427. "tag count too large");
  1428. /* The 'intent' must be valid or we can't store it, ICC limits the intent to
  1429. * 16 bits.
  1430. */
  1431. temp = png_get_uint_32(profile+64);
  1432. if (temp >= 0xffff) /* The ICC limit */
  1433. return png_icc_profile_error(png_ptr, name, temp,
  1434. "invalid rendering intent");
  1435. /* This is just a warning because the profile may be valid in future
  1436. * versions.
  1437. */
  1438. if (temp >= PNG_sRGB_INTENT_LAST)
  1439. (void)png_icc_profile_error(png_ptr, name, temp,
  1440. "intent outside defined range");
  1441. /* At this point the tag table can't be checked because it hasn't necessarily
  1442. * been loaded; however, various header fields can be checked. These checks
  1443. * are for values permitted by the PNG spec in an ICC profile; the PNG spec
  1444. * restricts the profiles that can be passed in an iCCP chunk (they must be
  1445. * appropriate to processing PNG data!)
  1446. */
  1447. /* Data checks (could be skipped). These checks must be independent of the
  1448. * version number; however, the version number doesn't accommodate changes in
  1449. * the header fields (just the known tags and the interpretation of the
  1450. * data.)
  1451. */
  1452. temp = png_get_uint_32(profile+36); /* signature 'ascp' */
  1453. if (temp != 0x61637370)
  1454. return png_icc_profile_error(png_ptr, name, temp,
  1455. "invalid signature");
  1456. /* Currently the PCS illuminant/adopted white point (the computational
  1457. * white point) are required to be D50,
  1458. * however the profile contains a record of the illuminant so perhaps ICC
  1459. * expects to be able to change this in the future (despite the rationale in
  1460. * the introduction for using a fixed PCS adopted white.) Consequently the
  1461. * following is just a warning.
  1462. */
  1463. if (memcmp(profile+68, D50_nCIEXYZ, 12) != 0)
  1464. (void)png_icc_profile_error(png_ptr, name, 0/*no tag value*/,
  1465. "PCS illuminant is not D50");
  1466. /* The PNG spec requires this:
  1467. * "If the iCCP chunk is present, the image samples conform to the colour
  1468. * space represented by the embedded ICC profile as defined by the
  1469. * International Color Consortium [ICC]. The colour space of the ICC profile
  1470. * shall be an RGB colour space for colour images (PNG colour types 2, 3, and
  1471. * 6), or a greyscale colour space for greyscale images (PNG colour types 0
  1472. * and 4)."
  1473. *
  1474. * This checking code ensures the embedded profile (on either read or write)
  1475. * conforms to the specification requirements. Notice that an ICC 'gray'
  1476. * color-space profile contains the information to transform the monochrome
  1477. * data to XYZ or L*a*b (according to which PCS the profile uses) and this
  1478. * should be used in preference to the standard libpng K channel replication
  1479. * into R, G and B channels.
  1480. *
  1481. * Previously it was suggested that an RGB profile on grayscale data could be
  1482. * handled. However it it is clear that using an RGB profile in this context
  1483. * must be an error - there is no specification of what it means. Thus it is
  1484. * almost certainly more correct to ignore the profile.
  1485. */
  1486. temp = png_get_uint_32(profile+16); /* data colour space field */
  1487. switch (temp)
  1488. {
  1489. case 0x52474220: /* 'RGB ' */
  1490. if ((color_type & PNG_COLOR_MASK_COLOR) == 0)
  1491. return png_icc_profile_error(png_ptr, name, temp,
  1492. "RGB color space not permitted on grayscale PNG");
  1493. break;
  1494. case 0x47524159: /* 'GRAY' */
  1495. if ((color_type & PNG_COLOR_MASK_COLOR) != 0)
  1496. return png_icc_profile_error(png_ptr, name, temp,
  1497. "Gray color space not permitted on RGB PNG");
  1498. break;
  1499. default:
  1500. return png_icc_profile_error(png_ptr, name, temp,
  1501. "invalid ICC profile color space");
  1502. }
  1503. /* It is up to the application to check that the profile class matches the
  1504. * application requirements; the spec provides no guidance, but it's pretty
  1505. * weird if the profile is not scanner ('scnr'), monitor ('mntr'), printer
  1506. * ('prtr') or 'spac' (for generic color spaces). Issue a warning in these
  1507. * cases. Issue an error for device link or abstract profiles - these don't
  1508. * contain the records necessary to transform the color-space to anything
  1509. * other than the target device (and not even that for an abstract profile).
  1510. * Profiles of these classes may not be embedded in images.
  1511. */
  1512. temp = png_get_uint_32(profile+12); /* profile/device class */
  1513. switch (temp)
  1514. {
  1515. case 0x73636e72: /* 'scnr' */
  1516. case 0x6d6e7472: /* 'mntr' */
  1517. case 0x70727472: /* 'prtr' */
  1518. case 0x73706163: /* 'spac' */
  1519. /* All supported */
  1520. break;
  1521. case 0x61627374: /* 'abst' */
  1522. /* May not be embedded in an image */
  1523. return png_icc_profile_error(png_ptr, name, temp,
  1524. "invalid embedded Abstract ICC profile");
  1525. case 0x6c696e6b: /* 'link' */
  1526. /* DeviceLink profiles cannot be interpreted in a non-device specific
  1527. * fashion, if an app uses the AToB0Tag in the profile the results are
  1528. * undefined unless the result is sent to the intended device,
  1529. * therefore a DeviceLink profile should not be found embedded in a
  1530. * PNG.
  1531. */
  1532. return png_icc_profile_error(png_ptr, name, temp,
  1533. "unexpected DeviceLink ICC profile class");
  1534. case 0x6e6d636c: /* 'nmcl' */
  1535. /* A NamedColor profile is also device specific, however it doesn't
  1536. * contain an AToB0 tag that is open to misinterpretation. Almost
  1537. * certainly it will fail the tests below.
  1538. */
  1539. (void)png_icc_profile_error(png_ptr, name, temp,
  1540. "unexpected NamedColor ICC profile class");
  1541. break;
  1542. default:
  1543. /* To allow for future enhancements to the profile accept unrecognized
  1544. * profile classes with a warning, these then hit the test below on the
  1545. * tag content to ensure they are backward compatible with one of the
  1546. * understood profiles.
  1547. */
  1548. (void)png_icc_profile_error(png_ptr, name, temp,
  1549. "unrecognized ICC profile class");
  1550. break;
  1551. }
  1552. /* For any profile other than a device link one the PCS must be encoded
  1553. * either in XYZ or Lab.
  1554. */
  1555. temp = png_get_uint_32(profile+20);
  1556. switch (temp)
  1557. {
  1558. case 0x58595a20: /* 'XYZ ' */
  1559. case 0x4c616220: /* 'Lab ' */
  1560. break;
  1561. default:
  1562. return png_icc_profile_error(png_ptr, name, temp,
  1563. "unexpected ICC PCS encoding");
  1564. }
  1565. return 1;
  1566. }
  1567. int /* PRIVATE */
  1568. png_icc_check_tag_table(png_const_structrp png_ptr, png_const_charp name,
  1569. png_uint_32 profile_length,
  1570. png_const_bytep profile /* header plus whole tag table */)
  1571. {
  1572. png_uint_32 tag_count = png_get_uint_32(profile+128);
  1573. png_uint_32 itag;
  1574. png_const_bytep tag = profile+132; /* The first tag */
  1575. /* First scan all the tags in the table and add bits to the icc_info value
  1576. * (temporarily in 'tags').
  1577. */
  1578. for (itag=0; itag < tag_count; ++itag, tag += 12)
  1579. {
  1580. png_uint_32 tag_id = png_get_uint_32(tag+0);
  1581. png_uint_32 tag_start = png_get_uint_32(tag+4); /* must be aligned */
  1582. png_uint_32 tag_length = png_get_uint_32(tag+8);/* not padded */
  1583. /* The ICC specification does not exclude zero length tags, therefore the
  1584. * start might actually be anywhere if there is no data, but this would be
  1585. * a clear abuse of the intent of the standard so the start is checked for
  1586. * being in range. All defined tag types have an 8 byte header - a 4 byte
  1587. * type signature then 0.
  1588. */
  1589. /* This is a hard error; potentially it can cause read outside the
  1590. * profile.
  1591. */
  1592. if (tag_start > profile_length || tag_length > profile_length - tag_start)
  1593. return png_icc_profile_error(png_ptr, name, tag_id,
  1594. "ICC profile tag outside profile");
  1595. if ((tag_start & 3) != 0)
  1596. {
  1597. /* CNHP730S.icc shipped with Microsoft Windows 64 violates this; it is
  1598. * only a warning here because libpng does not care about the
  1599. * alignment.
  1600. */
  1601. (void)png_icc_profile_error(png_ptr, name, tag_id,
  1602. "ICC profile tag start not a multiple of 4");
  1603. }
  1604. }
  1605. return 1; /* success, maybe with warnings */
  1606. }
  1607. #endif /* READ_iCCP */
  1608. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  1609. #if (defined PNG_READ_mDCV_SUPPORTED) || (defined PNG_READ_cHRM_SUPPORTED)
  1610. static int
  1611. have_chromaticities(png_const_structrp png_ptr)
  1612. {
  1613. /* Handle new PNGv3 chunks and the precedence rules to determine whether
  1614. * png_struct::chromaticities must be processed. Only required for RGB to
  1615. * gray.
  1616. *
  1617. * mDCV: this is the mastering colour space and it is independent of the
  1618. * encoding so it needs to be used regardless of the encoded space.
  1619. *
  1620. * cICP: first in priority but not yet implemented - the chromaticities come
  1621. * from the 'primaries'.
  1622. *
  1623. * iCCP: not supported by libpng (so ignored)
  1624. *
  1625. * sRGB: the defaults match sRGB
  1626. *
  1627. * cHRM: calculate the coefficients
  1628. */
  1629. # ifdef PNG_READ_mDCV_SUPPORTED
  1630. if (png_has_chunk(png_ptr, mDCV))
  1631. return 1;
  1632. # define check_chromaticities 1
  1633. # endif /*mDCV*/
  1634. # ifdef PNG_READ_sRGB_SUPPORTED
  1635. if (png_has_chunk(png_ptr, sRGB))
  1636. return 0;
  1637. # endif /*sRGB*/
  1638. # ifdef PNG_READ_cHRM_SUPPORTED
  1639. if (png_has_chunk(png_ptr, cHRM))
  1640. return 1;
  1641. # define check_chromaticities 1
  1642. # endif /*cHRM*/
  1643. return 0; /* sRGB defaults */
  1644. }
  1645. #endif /* READ_mDCV || READ_cHRM */
  1646. void /* PRIVATE */
  1647. png_set_rgb_coefficients(png_structrp png_ptr)
  1648. {
  1649. /* Set the rgb_to_gray coefficients from the colorspace if available. Note
  1650. * that '_set' means that png_rgb_to_gray was called **and** it successfully
  1651. * set up the coefficients.
  1652. */
  1653. if (png_ptr->rgb_to_gray_coefficients_set == 0)
  1654. {
  1655. # if check_chromaticities
  1656. png_XYZ xyz;
  1657. if (have_chromaticities(png_ptr) &&
  1658. png_XYZ_from_xy(&xyz, &png_ptr->chromaticities) == 0)
  1659. {
  1660. /* png_set_rgb_to_gray has not set the coefficients, get them from the
  1661. * Y * values of the colorspace colorants.
  1662. */
  1663. png_fixed_point r = xyz.red_Y;
  1664. png_fixed_point g = xyz.green_Y;
  1665. png_fixed_point b = xyz.blue_Y;
  1666. png_fixed_point total = r+g+b;
  1667. if (total > 0 &&
  1668. r >= 0 && png_muldiv(&r, r, 32768, total) && r >= 0 && r <= 32768 &&
  1669. g >= 0 && png_muldiv(&g, g, 32768, total) && g >= 0 && g <= 32768 &&
  1670. b >= 0 && png_muldiv(&b, b, 32768, total) && b >= 0 && b <= 32768 &&
  1671. r+g+b <= 32769)
  1672. {
  1673. /* We allow 0 coefficients here. r+g+b may be 32769 if two or
  1674. * all of the coefficients were rounded up. Handle this by
  1675. * reducing the *largest* coefficient by 1; this matches the
  1676. * approach used for the default coefficients in pngrtran.c
  1677. */
  1678. int add = 0;
  1679. if (r+g+b > 32768)
  1680. add = -1;
  1681. else if (r+g+b < 32768)
  1682. add = 1;
  1683. if (add != 0)
  1684. {
  1685. if (g >= r && g >= b)
  1686. g += add;
  1687. else if (r >= g && r >= b)
  1688. r += add;
  1689. else
  1690. b += add;
  1691. }
  1692. /* Check for an internal error. */
  1693. if (r+g+b != 32768)
  1694. png_error(png_ptr,
  1695. "internal error handling cHRM coefficients");
  1696. else
  1697. {
  1698. png_ptr->rgb_to_gray_red_coeff = (png_uint_16)r;
  1699. png_ptr->rgb_to_gray_green_coeff = (png_uint_16)g;
  1700. }
  1701. }
  1702. }
  1703. else
  1704. # endif /* check_chromaticities */
  1705. {
  1706. /* Use the historical REC 709 (etc) values: */
  1707. png_ptr->rgb_to_gray_red_coeff = 6968;
  1708. png_ptr->rgb_to_gray_green_coeff = 23434;
  1709. /* png_ptr->rgb_to_gray_blue_coeff = 2366; */
  1710. }
  1711. }
  1712. }
  1713. #endif /* READ_RGB_TO_GRAY */
  1714. void /* PRIVATE */
  1715. png_check_IHDR(png_const_structrp png_ptr,
  1716. png_uint_32 width, png_uint_32 height, int bit_depth,
  1717. int color_type, int interlace_type, int compression_type,
  1718. int filter_type)
  1719. {
  1720. int error = 0;
  1721. /* Check for width and height valid values */
  1722. if (width == 0)
  1723. {
  1724. png_warning(png_ptr, "Image width is zero in IHDR");
  1725. error = 1;
  1726. }
  1727. if (width > PNG_UINT_31_MAX)
  1728. {
  1729. png_warning(png_ptr, "Invalid image width in IHDR");
  1730. error = 1;
  1731. }
  1732. /* The bit mask on the first line below must be at least as big as a
  1733. * png_uint_32. "~7U" is not adequate on 16-bit systems because it will
  1734. * be an unsigned 16-bit value. Casting to (png_alloc_size_t) makes the
  1735. * type of the result at least as bit (in bits) as the RHS of the > operator
  1736. * which also avoids a common warning on 64-bit systems that the comparison
  1737. * of (png_uint_32) against the constant value on the RHS will always be
  1738. * false.
  1739. */
  1740. if (((width + 7) & ~(png_alloc_size_t)7) >
  1741. (((PNG_SIZE_MAX
  1742. - 48 /* big_row_buf hack */
  1743. - 1) /* filter byte */
  1744. / 8) /* 8-byte RGBA pixels */
  1745. - 1)) /* extra max_pixel_depth pad */
  1746. {
  1747. /* The size of the row must be within the limits of this architecture.
  1748. * Because the read code can perform arbitrary transformations the
  1749. * maximum size is checked here. Because the code in png_read_start_row
  1750. * adds extra space "for safety's sake" in several places a conservative
  1751. * limit is used here.
  1752. *
  1753. * NOTE: it would be far better to check the size that is actually used,
  1754. * but the effect in the real world is minor and the changes are more
  1755. * extensive, therefore much more dangerous and much more difficult to
  1756. * write in a way that avoids compiler warnings.
  1757. */
  1758. png_warning(png_ptr, "Image width is too large for this architecture");
  1759. error = 1;
  1760. }
  1761. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  1762. if (width > png_ptr->user_width_max)
  1763. #else
  1764. if (width > PNG_USER_WIDTH_MAX)
  1765. #endif
  1766. {
  1767. png_warning(png_ptr, "Image width exceeds user limit in IHDR");
  1768. error = 1;
  1769. }
  1770. if (height == 0)
  1771. {
  1772. png_warning(png_ptr, "Image height is zero in IHDR");
  1773. error = 1;
  1774. }
  1775. if (height > PNG_UINT_31_MAX)
  1776. {
  1777. png_warning(png_ptr, "Invalid image height in IHDR");
  1778. error = 1;
  1779. }
  1780. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  1781. if (height > png_ptr->user_height_max)
  1782. #else
  1783. if (height > PNG_USER_HEIGHT_MAX)
  1784. #endif
  1785. {
  1786. png_warning(png_ptr, "Image height exceeds user limit in IHDR");
  1787. error = 1;
  1788. }
  1789. /* Check other values */
  1790. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  1791. bit_depth != 8 && bit_depth != 16)
  1792. {
  1793. png_warning(png_ptr, "Invalid bit depth in IHDR");
  1794. error = 1;
  1795. }
  1796. if (color_type < 0 || color_type == 1 ||
  1797. color_type == 5 || color_type > 6)
  1798. {
  1799. png_warning(png_ptr, "Invalid color type in IHDR");
  1800. error = 1;
  1801. }
  1802. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  1803. ((color_type == PNG_COLOR_TYPE_RGB ||
  1804. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  1805. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  1806. {
  1807. png_warning(png_ptr, "Invalid color type/bit depth combination in IHDR");
  1808. error = 1;
  1809. }
  1810. if (interlace_type >= PNG_INTERLACE_LAST)
  1811. {
  1812. png_warning(png_ptr, "Unknown interlace method in IHDR");
  1813. error = 1;
  1814. }
  1815. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  1816. {
  1817. png_warning(png_ptr, "Unknown compression method in IHDR");
  1818. error = 1;
  1819. }
  1820. #ifdef PNG_MNG_FEATURES_SUPPORTED
  1821. /* Accept filter_method 64 (intrapixel differencing) only if
  1822. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  1823. * 2. Libpng did not read a PNG signature (this filter_method is only
  1824. * used in PNG datastreams that are embedded in MNG datastreams) and
  1825. * 3. The application called png_permit_mng_features with a mask that
  1826. * included PNG_FLAG_MNG_FILTER_64 and
  1827. * 4. The filter_method is 64 and
  1828. * 5. The color_type is RGB or RGBA
  1829. */
  1830. if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 &&
  1831. png_ptr->mng_features_permitted != 0)
  1832. png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");
  1833. if (filter_type != PNG_FILTER_TYPE_BASE)
  1834. {
  1835. if (!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
  1836. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  1837. ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) == 0) &&
  1838. (color_type == PNG_COLOR_TYPE_RGB ||
  1839. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  1840. {
  1841. png_warning(png_ptr, "Unknown filter method in IHDR");
  1842. error = 1;
  1843. }
  1844. if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0)
  1845. {
  1846. png_warning(png_ptr, "Invalid filter method in IHDR");
  1847. error = 1;
  1848. }
  1849. }
  1850. #else
  1851. if (filter_type != PNG_FILTER_TYPE_BASE)
  1852. {
  1853. png_warning(png_ptr, "Unknown filter method in IHDR");
  1854. error = 1;
  1855. }
  1856. #endif
  1857. if (error == 1)
  1858. png_error(png_ptr, "Invalid IHDR data");
  1859. }
  1860. #if defined(PNG_sCAL_SUPPORTED) || defined(PNG_pCAL_SUPPORTED)
  1861. /* ASCII to fp functions */
  1862. /* Check an ASCII formatted floating point value, see the more detailed
  1863. * comments in pngpriv.h
  1864. */
  1865. /* The following is used internally to preserve the sticky flags */
  1866. #define png_fp_add(state, flags) ((state) |= (flags))
  1867. #define png_fp_set(state, value) ((state) = (value) | ((state) & PNG_FP_STICKY))
  1868. int /* PRIVATE */
  1869. png_check_fp_number(png_const_charp string, size_t size, int *statep,
  1870. size_t *whereami)
  1871. {
  1872. int state = *statep;
  1873. size_t i = *whereami;
  1874. while (i < size)
  1875. {
  1876. int type;
  1877. /* First find the type of the next character */
  1878. switch (string[i])
  1879. {
  1880. case 43: type = PNG_FP_SAW_SIGN; break;
  1881. case 45: type = PNG_FP_SAW_SIGN + PNG_FP_NEGATIVE; break;
  1882. case 46: type = PNG_FP_SAW_DOT; break;
  1883. case 48: type = PNG_FP_SAW_DIGIT; break;
  1884. case 49: case 50: case 51: case 52:
  1885. case 53: case 54: case 55: case 56:
  1886. case 57: type = PNG_FP_SAW_DIGIT + PNG_FP_NONZERO; break;
  1887. case 69:
  1888. case 101: type = PNG_FP_SAW_E; break;
  1889. default: goto PNG_FP_End;
  1890. }
  1891. /* Now deal with this type according to the current
  1892. * state, the type is arranged to not overlap the
  1893. * bits of the PNG_FP_STATE.
  1894. */
  1895. switch ((state & PNG_FP_STATE) + (type & PNG_FP_SAW_ANY))
  1896. {
  1897. case PNG_FP_INTEGER + PNG_FP_SAW_SIGN:
  1898. if ((state & PNG_FP_SAW_ANY) != 0)
  1899. goto PNG_FP_End; /* not a part of the number */
  1900. png_fp_add(state, type);
  1901. break;
  1902. case PNG_FP_INTEGER + PNG_FP_SAW_DOT:
  1903. /* Ok as trailer, ok as lead of fraction. */
  1904. if ((state & PNG_FP_SAW_DOT) != 0) /* two dots */
  1905. goto PNG_FP_End;
  1906. else if ((state & PNG_FP_SAW_DIGIT) != 0) /* trailing dot? */
  1907. png_fp_add(state, type);
  1908. else
  1909. png_fp_set(state, PNG_FP_FRACTION | type);
  1910. break;
  1911. case PNG_FP_INTEGER + PNG_FP_SAW_DIGIT:
  1912. if ((state & PNG_FP_SAW_DOT) != 0) /* delayed fraction */
  1913. png_fp_set(state, PNG_FP_FRACTION | PNG_FP_SAW_DOT);
  1914. png_fp_add(state, type | PNG_FP_WAS_VALID);
  1915. break;
  1916. case PNG_FP_INTEGER + PNG_FP_SAW_E:
  1917. if ((state & PNG_FP_SAW_DIGIT) == 0)
  1918. goto PNG_FP_End;
  1919. png_fp_set(state, PNG_FP_EXPONENT);
  1920. break;
  1921. /* case PNG_FP_FRACTION + PNG_FP_SAW_SIGN:
  1922. goto PNG_FP_End; ** no sign in fraction */
  1923. /* case PNG_FP_FRACTION + PNG_FP_SAW_DOT:
  1924. goto PNG_FP_End; ** Because SAW_DOT is always set */
  1925. case PNG_FP_FRACTION + PNG_FP_SAW_DIGIT:
  1926. png_fp_add(state, type | PNG_FP_WAS_VALID);
  1927. break;
  1928. case PNG_FP_FRACTION + PNG_FP_SAW_E:
  1929. /* This is correct because the trailing '.' on an
  1930. * integer is handled above - so we can only get here
  1931. * with the sequence ".E" (with no preceding digits).
  1932. */
  1933. if ((state & PNG_FP_SAW_DIGIT) == 0)
  1934. goto PNG_FP_End;
  1935. png_fp_set(state, PNG_FP_EXPONENT);
  1936. break;
  1937. case PNG_FP_EXPONENT + PNG_FP_SAW_SIGN:
  1938. if ((state & PNG_FP_SAW_ANY) != 0)
  1939. goto PNG_FP_End; /* not a part of the number */
  1940. png_fp_add(state, PNG_FP_SAW_SIGN);
  1941. break;
  1942. /* case PNG_FP_EXPONENT + PNG_FP_SAW_DOT:
  1943. goto PNG_FP_End; */
  1944. case PNG_FP_EXPONENT + PNG_FP_SAW_DIGIT:
  1945. png_fp_add(state, PNG_FP_SAW_DIGIT | PNG_FP_WAS_VALID);
  1946. break;
  1947. /* case PNG_FP_EXPONEXT + PNG_FP_SAW_E:
  1948. goto PNG_FP_End; */
  1949. default: goto PNG_FP_End; /* I.e. break 2 */
  1950. }
  1951. /* The character seems ok, continue. */
  1952. ++i;
  1953. }
  1954. PNG_FP_End:
  1955. /* Here at the end, update the state and return the correct
  1956. * return code.
  1957. */
  1958. *statep = state;
  1959. *whereami = i;
  1960. return (state & PNG_FP_SAW_DIGIT) != 0;
  1961. }
  1962. /* The same but for a complete string. */
  1963. int
  1964. png_check_fp_string(png_const_charp string, size_t size)
  1965. {
  1966. int state=0;
  1967. size_t char_index=0;
  1968. if (png_check_fp_number(string, size, &state, &char_index) != 0 &&
  1969. (char_index == size || string[char_index] == 0))
  1970. return state /* must be non-zero - see above */;
  1971. return 0; /* i.e. fail */
  1972. }
  1973. #endif /* pCAL || sCAL */
  1974. #ifdef PNG_sCAL_SUPPORTED
  1975. # ifdef PNG_FLOATING_POINT_SUPPORTED
  1976. /* Utility used below - a simple accurate power of ten from an integral
  1977. * exponent.
  1978. */
  1979. static double
  1980. png_pow10(int power)
  1981. {
  1982. int recip = 0;
  1983. double d = 1;
  1984. /* Handle negative exponent with a reciprocal at the end because
  1985. * 10 is exact whereas .1 is inexact in base 2
  1986. */
  1987. if (power < 0)
  1988. {
  1989. if (power < DBL_MIN_10_EXP) return 0;
  1990. recip = 1; power = -power;
  1991. }
  1992. if (power > 0)
  1993. {
  1994. /* Decompose power bitwise. */
  1995. double mult = 10;
  1996. do
  1997. {
  1998. if (power & 1) d *= mult;
  1999. mult *= mult;
  2000. power >>= 1;
  2001. }
  2002. while (power > 0);
  2003. if (recip != 0) d = 1/d;
  2004. }
  2005. /* else power is 0 and d is 1 */
  2006. return d;
  2007. }
  2008. /* Function to format a floating point value in ASCII with a given
  2009. * precision.
  2010. */
  2011. void /* PRIVATE */
  2012. png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, size_t size,
  2013. double fp, unsigned int precision)
  2014. {
  2015. /* We use standard functions from math.h, but not printf because
  2016. * that would require stdio. The caller must supply a buffer of
  2017. * sufficient size or we will png_error. The tests on size and
  2018. * the space in ascii[] consumed are indicated below.
  2019. */
  2020. if (precision < 1)
  2021. precision = DBL_DIG;
  2022. /* Enforce the limit of the implementation precision too. */
  2023. if (precision > DBL_DIG+1)
  2024. precision = DBL_DIG+1;
  2025. /* Basic sanity checks */
  2026. if (size >= precision+5) /* See the requirements below. */
  2027. {
  2028. if (fp < 0)
  2029. {
  2030. fp = -fp;
  2031. *ascii++ = 45; /* '-' PLUS 1 TOTAL 1 */
  2032. --size;
  2033. }
  2034. if (fp >= DBL_MIN && fp <= DBL_MAX)
  2035. {
  2036. int exp_b10; /* A base 10 exponent */
  2037. double base; /* 10^exp_b10 */
  2038. /* First extract a base 10 exponent of the number,
  2039. * the calculation below rounds down when converting
  2040. * from base 2 to base 10 (multiply by log10(2) -
  2041. * 0.3010, but 77/256 is 0.3008, so exp_b10 needs to
  2042. * be increased. Note that the arithmetic shift
  2043. * performs a floor() unlike C arithmetic - using a
  2044. * C multiply would break the following for negative
  2045. * exponents.
  2046. */
  2047. (void)frexp(fp, &exp_b10); /* exponent to base 2 */
  2048. exp_b10 = (exp_b10 * 77) >> 8; /* <= exponent to base 10 */
  2049. /* Avoid underflow here. */
  2050. base = png_pow10(exp_b10); /* May underflow */
  2051. while (base < DBL_MIN || base < fp)
  2052. {
  2053. /* And this may overflow. */
  2054. double test = png_pow10(exp_b10+1);
  2055. if (test <= DBL_MAX)
  2056. {
  2057. ++exp_b10; base = test;
  2058. }
  2059. else
  2060. break;
  2061. }
  2062. /* Normalize fp and correct exp_b10, after this fp is in the
  2063. * range [.1,1) and exp_b10 is both the exponent and the digit
  2064. * *before* which the decimal point should be inserted
  2065. * (starting with 0 for the first digit). Note that this
  2066. * works even if 10^exp_b10 is out of range because of the
  2067. * test on DBL_MAX above.
  2068. */
  2069. fp /= base;
  2070. while (fp >= 1)
  2071. {
  2072. fp /= 10; ++exp_b10;
  2073. }
  2074. /* Because of the code above fp may, at this point, be
  2075. * less than .1, this is ok because the code below can
  2076. * handle the leading zeros this generates, so no attempt
  2077. * is made to correct that here.
  2078. */
  2079. {
  2080. unsigned int czero, clead, cdigits;
  2081. char exponent[10];
  2082. /* Allow up to two leading zeros - this will not lengthen
  2083. * the number compared to using E-n.
  2084. */
  2085. if (exp_b10 < 0 && exp_b10 > -3) /* PLUS 3 TOTAL 4 */
  2086. {
  2087. czero = 0U-exp_b10; /* PLUS 2 digits: TOTAL 3 */
  2088. exp_b10 = 0; /* Dot added below before first output. */
  2089. }
  2090. else
  2091. czero = 0; /* No zeros to add */
  2092. /* Generate the digit list, stripping trailing zeros and
  2093. * inserting a '.' before a digit if the exponent is 0.
  2094. */
  2095. clead = czero; /* Count of leading zeros */
  2096. cdigits = 0; /* Count of digits in list. */
  2097. do
  2098. {
  2099. double d;
  2100. fp *= 10;
  2101. /* Use modf here, not floor and subtract, so that
  2102. * the separation is done in one step. At the end
  2103. * of the loop don't break the number into parts so
  2104. * that the final digit is rounded.
  2105. */
  2106. if (cdigits+czero+1 < precision+clead)
  2107. fp = modf(fp, &d);
  2108. else
  2109. {
  2110. d = floor(fp + .5);
  2111. if (d > 9)
  2112. {
  2113. /* Rounding up to 10, handle that here. */
  2114. if (czero > 0)
  2115. {
  2116. --czero; d = 1;
  2117. if (cdigits == 0) --clead;
  2118. }
  2119. else
  2120. {
  2121. while (cdigits > 0 && d > 9)
  2122. {
  2123. int ch = *--ascii;
  2124. if (exp_b10 != (-1))
  2125. ++exp_b10;
  2126. else if (ch == 46)
  2127. {
  2128. ch = *--ascii; ++size;
  2129. /* Advance exp_b10 to '1', so that the
  2130. * decimal point happens after the
  2131. * previous digit.
  2132. */
  2133. exp_b10 = 1;
  2134. }
  2135. --cdigits;
  2136. d = ch - 47; /* I.e. 1+(ch-48) */
  2137. }
  2138. /* Did we reach the beginning? If so adjust the
  2139. * exponent but take into account the leading
  2140. * decimal point.
  2141. */
  2142. if (d > 9) /* cdigits == 0 */
  2143. {
  2144. if (exp_b10 == (-1))
  2145. {
  2146. /* Leading decimal point (plus zeros?), if
  2147. * we lose the decimal point here it must
  2148. * be reentered below.
  2149. */
  2150. int ch = *--ascii;
  2151. if (ch == 46)
  2152. {
  2153. ++size; exp_b10 = 1;
  2154. }
  2155. /* Else lost a leading zero, so 'exp_b10' is
  2156. * still ok at (-1)
  2157. */
  2158. }
  2159. else
  2160. ++exp_b10;
  2161. /* In all cases we output a '1' */
  2162. d = 1;
  2163. }
  2164. }
  2165. }
  2166. fp = 0; /* Guarantees termination below. */
  2167. }
  2168. if (d == 0)
  2169. {
  2170. ++czero;
  2171. if (cdigits == 0) ++clead;
  2172. }
  2173. else
  2174. {
  2175. /* Included embedded zeros in the digit count. */
  2176. cdigits += czero - clead;
  2177. clead = 0;
  2178. while (czero > 0)
  2179. {
  2180. /* exp_b10 == (-1) means we just output the decimal
  2181. * place - after the DP don't adjust 'exp_b10' any
  2182. * more!
  2183. */
  2184. if (exp_b10 != (-1))
  2185. {
  2186. if (exp_b10 == 0)
  2187. {
  2188. *ascii++ = 46; --size;
  2189. }
  2190. /* PLUS 1: TOTAL 4 */
  2191. --exp_b10;
  2192. }
  2193. *ascii++ = 48; --czero;
  2194. }
  2195. if (exp_b10 != (-1))
  2196. {
  2197. if (exp_b10 == 0)
  2198. {
  2199. *ascii++ = 46; --size; /* counted above */
  2200. }
  2201. --exp_b10;
  2202. }
  2203. *ascii++ = (char)(48 + (int)d); ++cdigits;
  2204. }
  2205. }
  2206. while (cdigits+czero < precision+clead && fp > DBL_MIN);
  2207. /* The total output count (max) is now 4+precision */
  2208. /* Check for an exponent, if we don't need one we are
  2209. * done and just need to terminate the string. At this
  2210. * point, exp_b10==(-1) is effectively a flag: it got
  2211. * to '-1' because of the decrement, after outputting
  2212. * the decimal point above. (The exponent required is
  2213. * *not* -1.)
  2214. */
  2215. if (exp_b10 >= (-1) && exp_b10 <= 2)
  2216. {
  2217. /* The following only happens if we didn't output the
  2218. * leading zeros above for negative exponent, so this
  2219. * doesn't add to the digit requirement. Note that the
  2220. * two zeros here can only be output if the two leading
  2221. * zeros were *not* output, so this doesn't increase
  2222. * the output count.
  2223. */
  2224. while (exp_b10-- > 0) *ascii++ = 48;
  2225. *ascii = 0;
  2226. /* Total buffer requirement (including the '\0') is
  2227. * 5+precision - see check at the start.
  2228. */
  2229. return;
  2230. }
  2231. /* Here if an exponent is required, adjust size for
  2232. * the digits we output but did not count. The total
  2233. * digit output here so far is at most 1+precision - no
  2234. * decimal point and no leading or trailing zeros have
  2235. * been output.
  2236. */
  2237. size -= cdigits;
  2238. *ascii++ = 69; --size; /* 'E': PLUS 1 TOTAL 2+precision */
  2239. /* The following use of an unsigned temporary avoids ambiguities in
  2240. * the signed arithmetic on exp_b10 and permits GCC at least to do
  2241. * better optimization.
  2242. */
  2243. {
  2244. unsigned int uexp_b10;
  2245. if (exp_b10 < 0)
  2246. {
  2247. *ascii++ = 45; --size; /* '-': PLUS 1 TOTAL 3+precision */
  2248. uexp_b10 = 0U-exp_b10;
  2249. }
  2250. else
  2251. uexp_b10 = 0U+exp_b10;
  2252. cdigits = 0;
  2253. while (uexp_b10 > 0)
  2254. {
  2255. exponent[cdigits++] = (char)(48 + uexp_b10 % 10);
  2256. uexp_b10 /= 10;
  2257. }
  2258. }
  2259. /* Need another size check here for the exponent digits, so
  2260. * this need not be considered above.
  2261. */
  2262. if (size > cdigits)
  2263. {
  2264. while (cdigits > 0) *ascii++ = exponent[--cdigits];
  2265. *ascii = 0;
  2266. return;
  2267. }
  2268. }
  2269. }
  2270. else if (!(fp >= DBL_MIN))
  2271. {
  2272. *ascii++ = 48; /* '0' */
  2273. *ascii = 0;
  2274. return;
  2275. }
  2276. else
  2277. {
  2278. *ascii++ = 105; /* 'i' */
  2279. *ascii++ = 110; /* 'n' */
  2280. *ascii++ = 102; /* 'f' */
  2281. *ascii = 0;
  2282. return;
  2283. }
  2284. }
  2285. /* Here on buffer too small. */
  2286. png_error(png_ptr, "ASCII conversion buffer too small");
  2287. }
  2288. # endif /* FLOATING_POINT */
  2289. # ifdef PNG_FIXED_POINT_SUPPORTED
  2290. /* Function to format a fixed point value in ASCII.
  2291. */
  2292. void /* PRIVATE */
  2293. png_ascii_from_fixed(png_const_structrp png_ptr, png_charp ascii,
  2294. size_t size, png_fixed_point fp)
  2295. {
  2296. /* Require space for 10 decimal digits, a decimal point, a minus sign and a
  2297. * trailing \0, 13 characters:
  2298. */
  2299. if (size > 12)
  2300. {
  2301. png_uint_32 num;
  2302. /* Avoid overflow here on the minimum integer. */
  2303. if (fp < 0)
  2304. {
  2305. *ascii++ = 45; num = (png_uint_32)(-fp);
  2306. }
  2307. else
  2308. num = (png_uint_32)fp;
  2309. if (num <= 0x80000000) /* else overflowed */
  2310. {
  2311. unsigned int ndigits = 0, first = 16 /* flag value */;
  2312. char digits[10] = {0};
  2313. while (num)
  2314. {
  2315. /* Split the low digit off num: */
  2316. unsigned int tmp = num/10;
  2317. num -= tmp*10;
  2318. digits[ndigits++] = (char)(48 + num);
  2319. /* Record the first non-zero digit, note that this is a number
  2320. * starting at 1, it's not actually the array index.
  2321. */
  2322. if (first == 16 && num > 0)
  2323. first = ndigits;
  2324. num = tmp;
  2325. }
  2326. if (ndigits > 0)
  2327. {
  2328. while (ndigits > 5) *ascii++ = digits[--ndigits];
  2329. /* The remaining digits are fractional digits, ndigits is '5' or
  2330. * smaller at this point. It is certainly not zero. Check for a
  2331. * non-zero fractional digit:
  2332. */
  2333. if (first <= 5)
  2334. {
  2335. unsigned int i;
  2336. *ascii++ = 46; /* decimal point */
  2337. /* ndigits may be <5 for small numbers, output leading zeros
  2338. * then ndigits digits to first:
  2339. */
  2340. i = 5;
  2341. while (ndigits < i)
  2342. {
  2343. *ascii++ = 48; --i;
  2344. }
  2345. while (ndigits >= first) *ascii++ = digits[--ndigits];
  2346. /* Don't output the trailing zeros! */
  2347. }
  2348. }
  2349. else
  2350. *ascii++ = 48;
  2351. /* And null terminate the string: */
  2352. *ascii = 0;
  2353. return;
  2354. }
  2355. }
  2356. /* Here on buffer too small. */
  2357. png_error(png_ptr, "ASCII conversion buffer too small");
  2358. }
  2359. # endif /* FIXED_POINT */
  2360. #endif /* SCAL */
  2361. #if defined(PNG_FLOATING_POINT_SUPPORTED) && \
  2362. !defined(PNG_FIXED_POINT_MACRO_SUPPORTED) && \
  2363. (defined(PNG_gAMA_SUPPORTED) || defined(PNG_cHRM_SUPPORTED) || \
  2364. defined(PNG_sCAL_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  2365. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)) || \
  2366. (defined(PNG_sCAL_SUPPORTED) && \
  2367. defined(PNG_FLOATING_ARITHMETIC_SUPPORTED))
  2368. png_fixed_point
  2369. png_fixed(png_const_structrp png_ptr, double fp, png_const_charp text)
  2370. {
  2371. double r = floor(100000 * fp + .5);
  2372. if (r > 2147483647. || r < -2147483648.)
  2373. png_fixed_error(png_ptr, text);
  2374. # ifndef PNG_ERROR_TEXT_SUPPORTED
  2375. PNG_UNUSED(text)
  2376. # endif
  2377. return (png_fixed_point)r;
  2378. }
  2379. #endif
  2380. #if defined(PNG_FLOATING_POINT_SUPPORTED) && \
  2381. !defined(PNG_FIXED_POINT_MACRO_SUPPORTED) && \
  2382. (defined(PNG_cLLI_SUPPORTED) || defined(PNG_mDCV_SUPPORTED))
  2383. png_uint_32
  2384. png_fixed_ITU(png_const_structrp png_ptr, double fp, png_const_charp text)
  2385. {
  2386. double r = floor(10000 * fp + .5);
  2387. if (r > 2147483647. || r < 0)
  2388. png_fixed_error(png_ptr, text);
  2389. # ifndef PNG_ERROR_TEXT_SUPPORTED
  2390. PNG_UNUSED(text)
  2391. # endif
  2392. return (png_uint_32)r;
  2393. }
  2394. #endif
  2395. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_COLORSPACE_SUPPORTED) ||\
  2396. defined(PNG_INCH_CONVERSIONS_SUPPORTED) || defined(PNG_READ_pHYs_SUPPORTED)
  2397. /* muldiv functions */
  2398. /* This API takes signed arguments and rounds the result to the nearest
  2399. * integer (or, for a fixed point number - the standard argument - to
  2400. * the nearest .00001). Overflow and divide by zero are signalled in
  2401. * the result, a boolean - true on success, false on overflow.
  2402. */
  2403. int /* PRIVATE */
  2404. png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times,
  2405. png_int_32 divisor)
  2406. {
  2407. /* Return a * times / divisor, rounded. */
  2408. if (divisor != 0)
  2409. {
  2410. if (a == 0 || times == 0)
  2411. {
  2412. *res = 0;
  2413. return 1;
  2414. }
  2415. else
  2416. {
  2417. #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  2418. double r = a;
  2419. r *= times;
  2420. r /= divisor;
  2421. r = floor(r+.5);
  2422. /* A png_fixed_point is a 32-bit integer. */
  2423. if (r <= 2147483647. && r >= -2147483648.)
  2424. {
  2425. *res = (png_fixed_point)r;
  2426. return 1;
  2427. }
  2428. #else
  2429. int negative = 0;
  2430. png_uint_32 A, T, D;
  2431. png_uint_32 s16, s32, s00;
  2432. if (a < 0)
  2433. negative = 1, A = -a;
  2434. else
  2435. A = a;
  2436. if (times < 0)
  2437. negative = !negative, T = -times;
  2438. else
  2439. T = times;
  2440. if (divisor < 0)
  2441. negative = !negative, D = -divisor;
  2442. else
  2443. D = divisor;
  2444. /* Following can't overflow because the arguments only
  2445. * have 31 bits each, however the result may be 32 bits.
  2446. */
  2447. s16 = (A >> 16) * (T & 0xffff) +
  2448. (A & 0xffff) * (T >> 16);
  2449. /* Can't overflow because the a*times bit is only 30
  2450. * bits at most.
  2451. */
  2452. s32 = (A >> 16) * (T >> 16) + (s16 >> 16);
  2453. s00 = (A & 0xffff) * (T & 0xffff);
  2454. s16 = (s16 & 0xffff) << 16;
  2455. s00 += s16;
  2456. if (s00 < s16)
  2457. ++s32; /* carry */
  2458. if (s32 < D) /* else overflow */
  2459. {
  2460. /* s32.s00 is now the 64-bit product, do a standard
  2461. * division, we know that s32 < D, so the maximum
  2462. * required shift is 31.
  2463. */
  2464. int bitshift = 32;
  2465. png_fixed_point result = 0; /* NOTE: signed */
  2466. while (--bitshift >= 0)
  2467. {
  2468. png_uint_32 d32, d00;
  2469. if (bitshift > 0)
  2470. d32 = D >> (32-bitshift), d00 = D << bitshift;
  2471. else
  2472. d32 = 0, d00 = D;
  2473. if (s32 > d32)
  2474. {
  2475. if (s00 < d00) --s32; /* carry */
  2476. s32 -= d32, s00 -= d00, result += 1<<bitshift;
  2477. }
  2478. else
  2479. if (s32 == d32 && s00 >= d00)
  2480. s32 = 0, s00 -= d00, result += 1<<bitshift;
  2481. }
  2482. /* Handle the rounding. */
  2483. if (s00 >= (D >> 1))
  2484. ++result;
  2485. if (negative != 0)
  2486. result = -result;
  2487. /* Check for overflow. */
  2488. if ((negative != 0 && result <= 0) ||
  2489. (negative == 0 && result >= 0))
  2490. {
  2491. *res = result;
  2492. return 1;
  2493. }
  2494. }
  2495. #endif
  2496. }
  2497. }
  2498. return 0;
  2499. }
  2500. /* Calculate a reciprocal, return 0 on div-by-zero or overflow. */
  2501. png_fixed_point
  2502. png_reciprocal(png_fixed_point a)
  2503. {
  2504. #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  2505. double r = floor(1E10/a+.5);
  2506. if (r <= 2147483647. && r >= -2147483648.)
  2507. return (png_fixed_point)r;
  2508. #else
  2509. png_fixed_point res;
  2510. if (png_muldiv(&res, 100000, 100000, a) != 0)
  2511. return res;
  2512. #endif
  2513. return 0; /* error/overflow */
  2514. }
  2515. #endif /* READ_GAMMA || COLORSPACE || INCH_CONVERSIONS || READ_pHYS */
  2516. #ifdef PNG_READ_GAMMA_SUPPORTED
  2517. /* This is the shared test on whether a gamma value is 'significant' - whether
  2518. * it is worth doing gamma correction.
  2519. */
  2520. int /* PRIVATE */
  2521. png_gamma_significant(png_fixed_point gamma_val)
  2522. {
  2523. /* sRGB: 1/2.2 == 0.4545(45)
  2524. * AdobeRGB: 1/(2+51/256) ~= 0.45471 5dp
  2525. *
  2526. * So the correction from AdobeRGB to sRGB (output) is:
  2527. *
  2528. * 2.2/(2+51/256) == 1.00035524
  2529. *
  2530. * I.e. vanishly small (<4E-4) but still detectable in 16-bit linear (+/-
  2531. * 23). Note that the Adobe choice seems to be something intended to give an
  2532. * exact number with 8 binary fractional digits - it is the closest to 2.2
  2533. * that is possible a base 2 .8p representation.
  2534. */
  2535. return gamma_val < PNG_FP_1 - PNG_GAMMA_THRESHOLD_FIXED ||
  2536. gamma_val > PNG_FP_1 + PNG_GAMMA_THRESHOLD_FIXED;
  2537. }
  2538. #ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED
  2539. /* A local convenience routine. */
  2540. static png_fixed_point
  2541. png_product2(png_fixed_point a, png_fixed_point b)
  2542. {
  2543. /* The required result is a * b; the following preserves accuracy. */
  2544. #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED /* Should now be unused */
  2545. double r = a * 1E-5;
  2546. r *= b;
  2547. r = floor(r+.5);
  2548. if (r <= 2147483647. && r >= -2147483648.)
  2549. return (png_fixed_point)r;
  2550. #else
  2551. png_fixed_point res;
  2552. if (png_muldiv(&res, a, b, 100000) != 0)
  2553. return res;
  2554. #endif
  2555. return 0; /* overflow */
  2556. }
  2557. #endif /* FLOATING_ARITHMETIC */
  2558. png_fixed_point
  2559. png_reciprocal2(png_fixed_point a, png_fixed_point b)
  2560. {
  2561. /* The required result is 1/a * 1/b; the following preserves accuracy. */
  2562. #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  2563. if (a != 0 && b != 0)
  2564. {
  2565. double r = 1E15/a;
  2566. r /= b;
  2567. r = floor(r+.5);
  2568. if (r <= 2147483647. && r >= -2147483648.)
  2569. return (png_fixed_point)r;
  2570. }
  2571. #else
  2572. /* This may overflow because the range of png_fixed_point isn't symmetric,
  2573. * but this API is only used for the product of file and screen gamma so it
  2574. * doesn't matter that the smallest number it can produce is 1/21474, not
  2575. * 1/100000
  2576. */
  2577. png_fixed_point res = png_product2(a, b);
  2578. if (res != 0)
  2579. return png_reciprocal(res);
  2580. #endif
  2581. return 0; /* overflow */
  2582. }
  2583. #endif /* READ_GAMMA */
  2584. #ifdef PNG_READ_GAMMA_SUPPORTED /* gamma table code */
  2585. #ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED
  2586. /* Fixed point gamma.
  2587. *
  2588. * The code to calculate the tables used below can be found in the shell script
  2589. * contrib/tools/intgamma.sh
  2590. *
  2591. * To calculate gamma this code implements fast log() and exp() calls using only
  2592. * fixed point arithmetic. This code has sufficient precision for either 8-bit
  2593. * or 16-bit sample values.
  2594. *
  2595. * The tables used here were calculated using simple 'bc' programs, but C double
  2596. * precision floating point arithmetic would work fine.
  2597. *
  2598. * 8-bit log table
  2599. * This is a table of -log(value/255)/log(2) for 'value' in the range 128 to
  2600. * 255, so it's the base 2 logarithm of a normalized 8-bit floating point
  2601. * mantissa. The numbers are 32-bit fractions.
  2602. */
  2603. static const png_uint_32
  2604. png_8bit_l2[128] =
  2605. {
  2606. 4270715492U, 4222494797U, 4174646467U, 4127164793U, 4080044201U, 4033279239U,
  2607. 3986864580U, 3940795015U, 3895065449U, 3849670902U, 3804606499U, 3759867474U,
  2608. 3715449162U, 3671346997U, 3627556511U, 3584073329U, 3540893168U, 3498011834U,
  2609. 3455425220U, 3413129301U, 3371120137U, 3329393864U, 3287946700U, 3246774933U,
  2610. 3205874930U, 3165243125U, 3124876025U, 3084770202U, 3044922296U, 3005329011U,
  2611. 2965987113U, 2926893432U, 2888044853U, 2849438323U, 2811070844U, 2772939474U,
  2612. 2735041326U, 2697373562U, 2659933400U, 2622718104U, 2585724991U, 2548951424U,
  2613. 2512394810U, 2476052606U, 2439922311U, 2404001468U, 2368287663U, 2332778523U,
  2614. 2297471715U, 2262364947U, 2227455964U, 2192742551U, 2158222529U, 2123893754U,
  2615. 2089754119U, 2055801552U, 2022034013U, 1988449497U, 1955046031U, 1921821672U,
  2616. 1888774511U, 1855902668U, 1823204291U, 1790677560U, 1758320682U, 1726131893U,
  2617. 1694109454U, 1662251657U, 1630556815U, 1599023271U, 1567649391U, 1536433567U,
  2618. 1505374214U, 1474469770U, 1443718700U, 1413119487U, 1382670639U, 1352370686U,
  2619. 1322218179U, 1292211689U, 1262349810U, 1232631153U, 1203054352U, 1173618059U,
  2620. 1144320946U, 1115161701U, 1086139034U, 1057251672U, 1028498358U, 999877854U,
  2621. 971388940U, 943030410U, 914801076U, 886699767U, 858725327U, 830876614U,
  2622. 803152505U, 775551890U, 748073672U, 720716771U, 693480120U, 666362667U,
  2623. 639363374U, 612481215U, 585715177U, 559064263U, 532527486U, 506103872U,
  2624. 479792461U, 453592303U, 427502463U, 401522014U, 375650043U, 349885648U,
  2625. 324227938U, 298676034U, 273229066U, 247886176U, 222646516U, 197509248U,
  2626. 172473545U, 147538590U, 122703574U, 97967701U, 73330182U, 48790236U,
  2627. 24347096U, 0U
  2628. #if 0
  2629. /* The following are the values for 16-bit tables - these work fine for the
  2630. * 8-bit conversions but produce very slightly larger errors in the 16-bit
  2631. * log (about 1.2 as opposed to 0.7 absolute error in the final value). To
  2632. * use these all the shifts below must be adjusted appropriately.
  2633. */
  2634. 65166, 64430, 63700, 62976, 62257, 61543, 60835, 60132, 59434, 58741, 58054,
  2635. 57371, 56693, 56020, 55352, 54689, 54030, 53375, 52726, 52080, 51439, 50803,
  2636. 50170, 49542, 48918, 48298, 47682, 47070, 46462, 45858, 45257, 44661, 44068,
  2637. 43479, 42894, 42312, 41733, 41159, 40587, 40020, 39455, 38894, 38336, 37782,
  2638. 37230, 36682, 36137, 35595, 35057, 34521, 33988, 33459, 32932, 32408, 31887,
  2639. 31369, 30854, 30341, 29832, 29325, 28820, 28319, 27820, 27324, 26830, 26339,
  2640. 25850, 25364, 24880, 24399, 23920, 23444, 22970, 22499, 22029, 21562, 21098,
  2641. 20636, 20175, 19718, 19262, 18808, 18357, 17908, 17461, 17016, 16573, 16132,
  2642. 15694, 15257, 14822, 14390, 13959, 13530, 13103, 12678, 12255, 11834, 11415,
  2643. 10997, 10582, 10168, 9756, 9346, 8937, 8531, 8126, 7723, 7321, 6921, 6523,
  2644. 6127, 5732, 5339, 4947, 4557, 4169, 3782, 3397, 3014, 2632, 2251, 1872, 1495,
  2645. 1119, 744, 372
  2646. #endif
  2647. };
  2648. static png_int_32
  2649. png_log8bit(unsigned int x)
  2650. {
  2651. unsigned int lg2 = 0;
  2652. /* Each time 'x' is multiplied by 2, 1 must be subtracted off the final log,
  2653. * because the log is actually negate that means adding 1. The final
  2654. * returned value thus has the range 0 (for 255 input) to 7.994 (for 1
  2655. * input), return -1 for the overflow (log 0) case, - so the result is
  2656. * always at most 19 bits.
  2657. */
  2658. if ((x &= 0xff) == 0)
  2659. return -1;
  2660. if ((x & 0xf0) == 0)
  2661. lg2 = 4, x <<= 4;
  2662. if ((x & 0xc0) == 0)
  2663. lg2 += 2, x <<= 2;
  2664. if ((x & 0x80) == 0)
  2665. lg2 += 1, x <<= 1;
  2666. /* result is at most 19 bits, so this cast is safe: */
  2667. return (png_int_32)((lg2 << 16) + ((png_8bit_l2[x-128]+32768)>>16));
  2668. }
  2669. /* The above gives exact (to 16 binary places) log2 values for 8-bit images,
  2670. * for 16-bit images we use the most significant 8 bits of the 16-bit value to
  2671. * get an approximation then multiply the approximation by a correction factor
  2672. * determined by the remaining up to 8 bits. This requires an additional step
  2673. * in the 16-bit case.
  2674. *
  2675. * We want log2(value/65535), we have log2(v'/255), where:
  2676. *
  2677. * value = v' * 256 + v''
  2678. * = v' * f
  2679. *
  2680. * So f is value/v', which is equal to (256+v''/v') since v' is in the range 128
  2681. * to 255 and v'' is in the range 0 to 255 f will be in the range 256 to less
  2682. * than 258. The final factor also needs to correct for the fact that our 8-bit
  2683. * value is scaled by 255, whereas the 16-bit values must be scaled by 65535.
  2684. *
  2685. * This gives a final formula using a calculated value 'x' which is value/v' and
  2686. * scaling by 65536 to match the above table:
  2687. *
  2688. * log2(x/257) * 65536
  2689. *
  2690. * Since these numbers are so close to '1' we can use simple linear
  2691. * interpolation between the two end values 256/257 (result -368.61) and 258/257
  2692. * (result 367.179). The values used below are scaled by a further 64 to give
  2693. * 16-bit precision in the interpolation:
  2694. *
  2695. * Start (256): -23591
  2696. * Zero (257): 0
  2697. * End (258): 23499
  2698. */
  2699. #ifdef PNG_16BIT_SUPPORTED
  2700. static png_int_32
  2701. png_log16bit(png_uint_32 x)
  2702. {
  2703. unsigned int lg2 = 0;
  2704. /* As above, but now the input has 16 bits. */
  2705. if ((x &= 0xffff) == 0)
  2706. return -1;
  2707. if ((x & 0xff00) == 0)
  2708. lg2 = 8, x <<= 8;
  2709. if ((x & 0xf000) == 0)
  2710. lg2 += 4, x <<= 4;
  2711. if ((x & 0xc000) == 0)
  2712. lg2 += 2, x <<= 2;
  2713. if ((x & 0x8000) == 0)
  2714. lg2 += 1, x <<= 1;
  2715. /* Calculate the base logarithm from the top 8 bits as a 28-bit fractional
  2716. * value.
  2717. */
  2718. lg2 <<= 28;
  2719. lg2 += (png_8bit_l2[(x>>8)-128]+8) >> 4;
  2720. /* Now we need to interpolate the factor, this requires a division by the top
  2721. * 8 bits. Do this with maximum precision.
  2722. */
  2723. x = ((x << 16) + (x >> 9)) / (x >> 8);
  2724. /* Since we divided by the top 8 bits of 'x' there will be a '1' at 1<<24,
  2725. * the value at 1<<16 (ignoring this) will be 0 or 1; this gives us exactly
  2726. * 16 bits to interpolate to get the low bits of the result. Round the
  2727. * answer. Note that the end point values are scaled by 64 to retain overall
  2728. * precision and that 'lg2' is current scaled by an extra 12 bits, so adjust
  2729. * the overall scaling by 6-12. Round at every step.
  2730. */
  2731. x -= 1U << 24;
  2732. if (x <= 65536U) /* <= '257' */
  2733. lg2 += ((23591U * (65536U-x)) + (1U << (16+6-12-1))) >> (16+6-12);
  2734. else
  2735. lg2 -= ((23499U * (x-65536U)) + (1U << (16+6-12-1))) >> (16+6-12);
  2736. /* Safe, because the result can't have more than 20 bits: */
  2737. return (png_int_32)((lg2 + 2048) >> 12);
  2738. }
  2739. #endif /* 16BIT */
  2740. /* The 'exp()' case must invert the above, taking a 20-bit fixed point
  2741. * logarithmic value and returning a 16 or 8-bit number as appropriate. In
  2742. * each case only the low 16 bits are relevant - the fraction - since the
  2743. * integer bits (the top 4) simply determine a shift.
  2744. *
  2745. * The worst case is the 16-bit distinction between 65535 and 65534. This
  2746. * requires perhaps spurious accuracy in the decoding of the logarithm to
  2747. * distinguish log2(65535/65534.5) - 10^-5 or 17 bits. There is little chance
  2748. * of getting this accuracy in practice.
  2749. *
  2750. * To deal with this the following exp() function works out the exponent of the
  2751. * fractional part of the logarithm by using an accurate 32-bit value from the
  2752. * top four fractional bits then multiplying in the remaining bits.
  2753. */
  2754. static const png_uint_32
  2755. png_32bit_exp[16] =
  2756. {
  2757. /* NOTE: the first entry is deliberately set to the maximum 32-bit value. */
  2758. 4294967295U, 4112874773U, 3938502376U, 3771522796U, 3611622603U, 3458501653U,
  2759. 3311872529U, 3171459999U, 3037000500U, 2908241642U, 2784941738U, 2666869345U,
  2760. 2553802834U, 2445529972U, 2341847524U, 2242560872U
  2761. };
  2762. /* Adjustment table; provided to explain the numbers in the code below. */
  2763. #if 0
  2764. for (i=11;i>=0;--i){ print i, " ", (1 - e(-(2^i)/65536*l(2))) * 2^(32-i), "\n"}
  2765. 11 44937.64284865548751208448
  2766. 10 45180.98734845585101160448
  2767. 9 45303.31936980687359311872
  2768. 8 45364.65110595323018870784
  2769. 7 45395.35850361789624614912
  2770. 6 45410.72259715102037508096
  2771. 5 45418.40724413220722311168
  2772. 4 45422.25021786898173001728
  2773. 3 45424.17186732298419044352
  2774. 2 45425.13273269940811464704
  2775. 1 45425.61317555035558641664
  2776. 0 45425.85339951654943850496
  2777. #endif
  2778. static png_uint_32
  2779. png_exp(png_fixed_point x)
  2780. {
  2781. if (x > 0 && x <= 0xfffff) /* Else overflow or zero (underflow) */
  2782. {
  2783. /* Obtain a 4-bit approximation */
  2784. png_uint_32 e = png_32bit_exp[(x >> 12) & 0x0f];
  2785. /* Incorporate the low 12 bits - these decrease the returned value by
  2786. * multiplying by a number less than 1 if the bit is set. The multiplier
  2787. * is determined by the above table and the shift. Notice that the values
  2788. * converge on 45426 and this is used to allow linear interpolation of the
  2789. * low bits.
  2790. */
  2791. if (x & 0x800)
  2792. e -= (((e >> 16) * 44938U) + 16U) >> 5;
  2793. if (x & 0x400)
  2794. e -= (((e >> 16) * 45181U) + 32U) >> 6;
  2795. if (x & 0x200)
  2796. e -= (((e >> 16) * 45303U) + 64U) >> 7;
  2797. if (x & 0x100)
  2798. e -= (((e >> 16) * 45365U) + 128U) >> 8;
  2799. if (x & 0x080)
  2800. e -= (((e >> 16) * 45395U) + 256U) >> 9;
  2801. if (x & 0x040)
  2802. e -= (((e >> 16) * 45410U) + 512U) >> 10;
  2803. /* And handle the low 6 bits in a single block. */
  2804. e -= (((e >> 16) * 355U * (x & 0x3fU)) + 256U) >> 9;
  2805. /* Handle the upper bits of x. */
  2806. e >>= x >> 16;
  2807. return e;
  2808. }
  2809. /* Check for overflow */
  2810. if (x <= 0)
  2811. return png_32bit_exp[0];
  2812. /* Else underflow */
  2813. return 0;
  2814. }
  2815. static png_byte
  2816. png_exp8bit(png_fixed_point lg2)
  2817. {
  2818. /* Get a 32-bit value: */
  2819. png_uint_32 x = png_exp(lg2);
  2820. /* Convert the 32-bit value to 0..255 by multiplying by 256-1. Note that the
  2821. * second, rounding, step can't overflow because of the first, subtraction,
  2822. * step.
  2823. */
  2824. x -= x >> 8;
  2825. return (png_byte)(((x + 0x7fffffU) >> 24) & 0xff);
  2826. }
  2827. #ifdef PNG_16BIT_SUPPORTED
  2828. static png_uint_16
  2829. png_exp16bit(png_fixed_point lg2)
  2830. {
  2831. /* Get a 32-bit value: */
  2832. png_uint_32 x = png_exp(lg2);
  2833. /* Convert the 32-bit value to 0..65535 by multiplying by 65536-1: */
  2834. x -= x >> 16;
  2835. return (png_uint_16)((x + 32767U) >> 16);
  2836. }
  2837. #endif /* 16BIT */
  2838. #endif /* FLOATING_ARITHMETIC */
  2839. png_byte
  2840. png_gamma_8bit_correct(unsigned int value, png_fixed_point gamma_val)
  2841. {
  2842. if (value > 0 && value < 255)
  2843. {
  2844. # ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  2845. /* 'value' is unsigned, ANSI-C90 requires the compiler to correctly
  2846. * convert this to a floating point value. This includes values that
  2847. * would overflow if 'value' were to be converted to 'int'.
  2848. *
  2849. * Apparently GCC, however, does an intermediate conversion to (int)
  2850. * on some (ARM) but not all (x86) platforms, possibly because of
  2851. * hardware FP limitations. (E.g. if the hardware conversion always
  2852. * assumes the integer register contains a signed value.) This results
  2853. * in ANSI-C undefined behavior for large values.
  2854. *
  2855. * Other implementations on the same machine might actually be ANSI-C90
  2856. * conformant and therefore compile spurious extra code for the large
  2857. * values.
  2858. *
  2859. * We can be reasonably sure that an unsigned to float conversion
  2860. * won't be faster than an int to float one. Therefore this code
  2861. * assumes responsibility for the undefined behavior, which it knows
  2862. * can't happen because of the check above.
  2863. *
  2864. * Note the argument to this routine is an (unsigned int) because, on
  2865. * 16-bit platforms, it is assigned a value which might be out of
  2866. * range for an (int); that would result in undefined behavior in the
  2867. * caller if the *argument* ('value') were to be declared (int).
  2868. */
  2869. double r = floor(255*pow((int)/*SAFE*/value/255.,gamma_val*.00001)+.5);
  2870. return (png_byte)r;
  2871. # else
  2872. png_int_32 lg2 = png_log8bit(value);
  2873. png_fixed_point res;
  2874. if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1) != 0)
  2875. return png_exp8bit(res);
  2876. /* Overflow. */
  2877. value = 0;
  2878. # endif
  2879. }
  2880. return (png_byte)(value & 0xff);
  2881. }
  2882. #ifdef PNG_16BIT_SUPPORTED
  2883. png_uint_16
  2884. png_gamma_16bit_correct(unsigned int value, png_fixed_point gamma_val)
  2885. {
  2886. if (value > 0 && value < 65535)
  2887. {
  2888. # ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  2889. /* The same (unsigned int)->(double) constraints apply here as above,
  2890. * however in this case the (unsigned int) to (int) conversion can
  2891. * overflow on an ANSI-C90 compliant system so the cast needs to ensure
  2892. * that this is not possible.
  2893. */
  2894. double r = floor(65535*pow((png_int_32)value/65535.,
  2895. gamma_val*.00001)+.5);
  2896. return (png_uint_16)r;
  2897. # else
  2898. png_int_32 lg2 = png_log16bit(value);
  2899. png_fixed_point res;
  2900. if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1) != 0)
  2901. return png_exp16bit(res);
  2902. /* Overflow. */
  2903. value = 0;
  2904. # endif
  2905. }
  2906. return (png_uint_16)value;
  2907. }
  2908. #endif /* 16BIT */
  2909. /* This does the right thing based on the bit_depth field of the
  2910. * png_struct, interpreting values as 8-bit or 16-bit. While the result
  2911. * is nominally a 16-bit value if bit depth is 8 then the result is
  2912. * 8-bit (as are the arguments.)
  2913. */
  2914. png_uint_16 /* PRIVATE */
  2915. png_gamma_correct(png_structrp png_ptr, unsigned int value,
  2916. png_fixed_point gamma_val)
  2917. {
  2918. if (png_ptr->bit_depth == 8)
  2919. return png_gamma_8bit_correct(value, gamma_val);
  2920. #ifdef PNG_16BIT_SUPPORTED
  2921. else
  2922. return png_gamma_16bit_correct(value, gamma_val);
  2923. #else
  2924. /* should not reach this */
  2925. return 0;
  2926. #endif /* 16BIT */
  2927. }
  2928. #ifdef PNG_16BIT_SUPPORTED
  2929. /* Internal function to build a single 16-bit table - the table consists of
  2930. * 'num' 256 entry subtables, where 'num' is determined by 'shift' - the amount
  2931. * to shift the input values right (or 16-number_of_signifiant_bits).
  2932. *
  2933. * The caller is responsible for ensuring that the table gets cleaned up on
  2934. * png_error (i.e. if one of the mallocs below fails) - i.e. the *table argument
  2935. * should be somewhere that will be cleaned.
  2936. */
  2937. static void
  2938. png_build_16bit_table(png_structrp png_ptr, png_uint_16pp *ptable,
  2939. unsigned int shift, png_fixed_point gamma_val)
  2940. {
  2941. /* Various values derived from 'shift': */
  2942. unsigned int num = 1U << (8U - shift);
  2943. #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  2944. /* CSE the division and work round wacky GCC warnings (see the comments
  2945. * in png_gamma_8bit_correct for where these come from.)
  2946. */
  2947. double fmax = 1.0 / (((png_int_32)1 << (16U - shift)) - 1);
  2948. #endif
  2949. unsigned int max = (1U << (16U - shift)) - 1U;
  2950. unsigned int max_by_2 = 1U << (15U - shift);
  2951. unsigned int i;
  2952. png_uint_16pp table = *ptable =
  2953. (png_uint_16pp)png_calloc(png_ptr, num * (sizeof (png_uint_16p)));
  2954. for (i = 0; i < num; i++)
  2955. {
  2956. png_uint_16p sub_table = table[i] =
  2957. (png_uint_16p)png_malloc(png_ptr, 256 * (sizeof (png_uint_16)));
  2958. /* The 'threshold' test is repeated here because it can arise for one of
  2959. * the 16-bit tables even if the others don't hit it.
  2960. */
  2961. if (png_gamma_significant(gamma_val) != 0)
  2962. {
  2963. /* The old code would overflow at the end and this would cause the
  2964. * 'pow' function to return a result >1, resulting in an
  2965. * arithmetic error. This code follows the spec exactly; ig is
  2966. * the recovered input sample, it always has 8-16 bits.
  2967. *
  2968. * We want input * 65535/max, rounded, the arithmetic fits in 32
  2969. * bits (unsigned) so long as max <= 32767.
  2970. */
  2971. unsigned int j;
  2972. for (j = 0; j < 256; j++)
  2973. {
  2974. png_uint_32 ig = (j << (8-shift)) + i;
  2975. # ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  2976. /* Inline the 'max' scaling operation: */
  2977. /* See png_gamma_8bit_correct for why the cast to (int) is
  2978. * required here.
  2979. */
  2980. double d = floor(65535.*pow(ig*fmax, gamma_val*.00001)+.5);
  2981. sub_table[j] = (png_uint_16)d;
  2982. # else
  2983. if (shift != 0)
  2984. ig = (ig * 65535U + max_by_2)/max;
  2985. sub_table[j] = png_gamma_16bit_correct(ig, gamma_val);
  2986. # endif
  2987. }
  2988. }
  2989. else
  2990. {
  2991. /* We must still build a table, but do it the fast way. */
  2992. unsigned int j;
  2993. for (j = 0; j < 256; j++)
  2994. {
  2995. png_uint_32 ig = (j << (8-shift)) + i;
  2996. if (shift != 0)
  2997. ig = (ig * 65535U + max_by_2)/max;
  2998. sub_table[j] = (png_uint_16)ig;
  2999. }
  3000. }
  3001. }
  3002. }
  3003. /* NOTE: this function expects the *inverse* of the overall gamma transformation
  3004. * required.
  3005. */
  3006. static void
  3007. png_build_16to8_table(png_structrp png_ptr, png_uint_16pp *ptable,
  3008. unsigned int shift, png_fixed_point gamma_val)
  3009. {
  3010. unsigned int num = 1U << (8U - shift);
  3011. unsigned int max = (1U << (16U - shift))-1U;
  3012. unsigned int i;
  3013. png_uint_32 last;
  3014. png_uint_16pp table = *ptable =
  3015. (png_uint_16pp)png_calloc(png_ptr, num * (sizeof (png_uint_16p)));
  3016. /* 'num' is the number of tables and also the number of low bits of low
  3017. * bits of the input 16-bit value used to select a table. Each table is
  3018. * itself indexed by the high 8 bits of the value.
  3019. */
  3020. for (i = 0; i < num; i++)
  3021. table[i] = (png_uint_16p)png_malloc(png_ptr,
  3022. 256 * (sizeof (png_uint_16)));
  3023. /* 'gamma_val' is set to the reciprocal of the value calculated above, so
  3024. * pow(out,g) is an *input* value. 'last' is the last input value set.
  3025. *
  3026. * In the loop 'i' is used to find output values. Since the output is
  3027. * 8-bit there are only 256 possible values. The tables are set up to
  3028. * select the closest possible output value for each input by finding
  3029. * the input value at the boundary between each pair of output values
  3030. * and filling the table up to that boundary with the lower output
  3031. * value.
  3032. *
  3033. * The boundary values are 0.5,1.5..253.5,254.5. Since these are 9-bit
  3034. * values the code below uses a 16-bit value in i; the values start at
  3035. * 128.5 (for 0.5) and step by 257, for a total of 254 values (the last
  3036. * entries are filled with 255). Start i at 128 and fill all 'last'
  3037. * table entries <= 'max'
  3038. */
  3039. last = 0;
  3040. for (i = 0; i < 255; ++i) /* 8-bit output value */
  3041. {
  3042. /* Find the corresponding maximum input value */
  3043. png_uint_16 out = (png_uint_16)(i * 257U); /* 16-bit output value */
  3044. /* Find the boundary value in 16 bits: */
  3045. png_uint_32 bound = png_gamma_16bit_correct(out+128U, gamma_val);
  3046. /* Adjust (round) to (16-shift) bits: */
  3047. bound = (bound * max + 32768U)/65535U + 1U;
  3048. while (last < bound)
  3049. {
  3050. table[last & (0xffU >> shift)][last >> (8U - shift)] = out;
  3051. last++;
  3052. }
  3053. }
  3054. /* And fill in the final entries. */
  3055. while (last < (num << 8))
  3056. {
  3057. table[last & (0xff >> shift)][last >> (8U - shift)] = 65535U;
  3058. last++;
  3059. }
  3060. }
  3061. #endif /* 16BIT */
  3062. /* Build a single 8-bit table: same as the 16-bit case but much simpler (and
  3063. * typically much faster). Note that libpng currently does no sBIT processing
  3064. * (apparently contrary to the spec) so a 256-entry table is always generated.
  3065. */
  3066. static void
  3067. png_build_8bit_table(png_structrp png_ptr, png_bytepp ptable,
  3068. png_fixed_point gamma_val)
  3069. {
  3070. unsigned int i;
  3071. png_bytep table = *ptable = (png_bytep)png_malloc(png_ptr, 256);
  3072. if (png_gamma_significant(gamma_val) != 0)
  3073. for (i=0; i<256; i++)
  3074. table[i] = png_gamma_8bit_correct(i, gamma_val);
  3075. else
  3076. for (i=0; i<256; ++i)
  3077. table[i] = (png_byte)(i & 0xff);
  3078. }
  3079. /* Used from png_read_destroy and below to release the memory used by the gamma
  3080. * tables.
  3081. */
  3082. void /* PRIVATE */
  3083. png_destroy_gamma_table(png_structrp png_ptr)
  3084. {
  3085. png_free(png_ptr, png_ptr->gamma_table);
  3086. png_ptr->gamma_table = NULL;
  3087. #ifdef PNG_16BIT_SUPPORTED
  3088. if (png_ptr->gamma_16_table != NULL)
  3089. {
  3090. int i;
  3091. int istop = (1 << (8 - png_ptr->gamma_shift));
  3092. for (i = 0; i < istop; i++)
  3093. {
  3094. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  3095. }
  3096. png_free(png_ptr, png_ptr->gamma_16_table);
  3097. png_ptr->gamma_16_table = NULL;
  3098. }
  3099. #endif /* 16BIT */
  3100. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  3101. defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \
  3102. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  3103. png_free(png_ptr, png_ptr->gamma_from_1);
  3104. png_ptr->gamma_from_1 = NULL;
  3105. png_free(png_ptr, png_ptr->gamma_to_1);
  3106. png_ptr->gamma_to_1 = NULL;
  3107. #ifdef PNG_16BIT_SUPPORTED
  3108. if (png_ptr->gamma_16_from_1 != NULL)
  3109. {
  3110. int i;
  3111. int istop = (1 << (8 - png_ptr->gamma_shift));
  3112. for (i = 0; i < istop; i++)
  3113. {
  3114. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  3115. }
  3116. png_free(png_ptr, png_ptr->gamma_16_from_1);
  3117. png_ptr->gamma_16_from_1 = NULL;
  3118. }
  3119. if (png_ptr->gamma_16_to_1 != NULL)
  3120. {
  3121. int i;
  3122. int istop = (1 << (8 - png_ptr->gamma_shift));
  3123. for (i = 0; i < istop; i++)
  3124. {
  3125. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  3126. }
  3127. png_free(png_ptr, png_ptr->gamma_16_to_1);
  3128. png_ptr->gamma_16_to_1 = NULL;
  3129. }
  3130. #endif /* 16BIT */
  3131. #endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */
  3132. }
  3133. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  3134. * tables, we don't make a full table if we are reducing to 8-bit in
  3135. * the future. Note also how the gamma_16 tables are segmented so that
  3136. * we don't need to allocate > 64K chunks for a full 16-bit table.
  3137. *
  3138. * TODO: move this to pngrtran.c and make it static. Better yet create
  3139. * pngcolor.c and put all the PNG_COLORSPACE stuff in there.
  3140. */
  3141. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  3142. defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \
  3143. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  3144. # define GAMMA_TRANSFORMS 1 /* #ifdef CSE */
  3145. #else
  3146. # define GAMMA_TRANSFORMS 0
  3147. #endif
  3148. void /* PRIVATE */
  3149. png_build_gamma_table(png_structrp png_ptr, int bit_depth)
  3150. {
  3151. png_fixed_point file_gamma, screen_gamma;
  3152. png_fixed_point correction;
  3153. # if GAMMA_TRANSFORMS
  3154. png_fixed_point file_to_linear, linear_to_screen;
  3155. # endif
  3156. png_debug(1, "in png_build_gamma_table");
  3157. /* Remove any existing table; this copes with multiple calls to
  3158. * png_read_update_info. The warning is because building the gamma tables
  3159. * multiple times is a performance hit - it's harmless but the ability to
  3160. * call png_read_update_info() multiple times is new in 1.5.6 so it seems
  3161. * sensible to warn if the app introduces such a hit.
  3162. */
  3163. if (png_ptr->gamma_table != NULL || png_ptr->gamma_16_table != NULL)
  3164. {
  3165. png_warning(png_ptr, "gamma table being rebuilt");
  3166. png_destroy_gamma_table(png_ptr);
  3167. }
  3168. /* The following fields are set, finally, in png_init_read_transformations.
  3169. * If file_gamma is 0 (unset) nothing can be done otherwise if screen_gamma
  3170. * is 0 (unset) there is no gamma correction but to/from linear is possible.
  3171. */
  3172. file_gamma = png_ptr->file_gamma;
  3173. screen_gamma = png_ptr->screen_gamma;
  3174. # if GAMMA_TRANSFORMS
  3175. file_to_linear = png_reciprocal(file_gamma);
  3176. # endif
  3177. if (screen_gamma > 0)
  3178. {
  3179. # if GAMMA_TRANSFORMS
  3180. linear_to_screen = png_reciprocal(screen_gamma);
  3181. # endif
  3182. correction = png_reciprocal2(screen_gamma, file_gamma);
  3183. }
  3184. else /* screen gamma unknown */
  3185. {
  3186. # if GAMMA_TRANSFORMS
  3187. linear_to_screen = file_gamma;
  3188. # endif
  3189. correction = PNG_FP_1;
  3190. }
  3191. if (bit_depth <= 8)
  3192. {
  3193. png_build_8bit_table(png_ptr, &png_ptr->gamma_table, correction);
  3194. #if GAMMA_TRANSFORMS
  3195. if ((png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY)) != 0)
  3196. {
  3197. png_build_8bit_table(png_ptr, &png_ptr->gamma_to_1, file_to_linear);
  3198. png_build_8bit_table(png_ptr, &png_ptr->gamma_from_1,
  3199. linear_to_screen);
  3200. }
  3201. #endif /* GAMMA_TRANSFORMS */
  3202. }
  3203. #ifdef PNG_16BIT_SUPPORTED
  3204. else
  3205. {
  3206. png_byte shift, sig_bit;
  3207. if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
  3208. {
  3209. sig_bit = png_ptr->sig_bit.red;
  3210. if (png_ptr->sig_bit.green > sig_bit)
  3211. sig_bit = png_ptr->sig_bit.green;
  3212. if (png_ptr->sig_bit.blue > sig_bit)
  3213. sig_bit = png_ptr->sig_bit.blue;
  3214. }
  3215. else
  3216. sig_bit = png_ptr->sig_bit.gray;
  3217. /* 16-bit gamma code uses this equation:
  3218. *
  3219. * ov = table[(iv & 0xff) >> gamma_shift][iv >> 8]
  3220. *
  3221. * Where 'iv' is the input color value and 'ov' is the output value -
  3222. * pow(iv, gamma).
  3223. *
  3224. * Thus the gamma table consists of up to 256 256-entry tables. The table
  3225. * is selected by the (8-gamma_shift) most significant of the low 8 bits
  3226. * of the color value then indexed by the upper 8 bits:
  3227. *
  3228. * table[low bits][high 8 bits]
  3229. *
  3230. * So the table 'n' corresponds to all those 'iv' of:
  3231. *
  3232. * <all high 8-bit values><n << gamma_shift>..<(n+1 << gamma_shift)-1>
  3233. *
  3234. */
  3235. if (sig_bit > 0 && sig_bit < 16U)
  3236. /* shift == insignificant bits */
  3237. shift = (png_byte)((16U - sig_bit) & 0xff);
  3238. else
  3239. shift = 0; /* keep all 16 bits */
  3240. if ((png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8)) != 0)
  3241. {
  3242. /* PNG_MAX_GAMMA_8 is the number of bits to keep - effectively
  3243. * the significant bits in the *input* when the output will
  3244. * eventually be 8 bits. By default it is 11.
  3245. */
  3246. if (shift < (16U - PNG_MAX_GAMMA_8))
  3247. shift = (16U - PNG_MAX_GAMMA_8);
  3248. }
  3249. if (shift > 8U)
  3250. shift = 8U; /* Guarantees at least one table! */
  3251. png_ptr->gamma_shift = shift;
  3252. /* NOTE: prior to 1.5.4 this test used to include PNG_BACKGROUND (now
  3253. * PNG_COMPOSE). This effectively smashed the background calculation for
  3254. * 16-bit output because the 8-bit table assumes the result will be
  3255. * reduced to 8 bits.
  3256. */
  3257. if ((png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8)) != 0)
  3258. png_build_16to8_table(png_ptr, &png_ptr->gamma_16_table, shift,
  3259. png_reciprocal(correction));
  3260. else
  3261. png_build_16bit_table(png_ptr, &png_ptr->gamma_16_table, shift,
  3262. correction);
  3263. # if GAMMA_TRANSFORMS
  3264. if ((png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY)) != 0)
  3265. {
  3266. png_build_16bit_table(png_ptr, &png_ptr->gamma_16_to_1, shift,
  3267. file_to_linear);
  3268. /* Notice that the '16 from 1' table should be full precision, however
  3269. * the lookup on this table still uses gamma_shift, so it can't be.
  3270. * TODO: fix this.
  3271. */
  3272. png_build_16bit_table(png_ptr, &png_ptr->gamma_16_from_1, shift,
  3273. linear_to_screen);
  3274. }
  3275. #endif /* GAMMA_TRANSFORMS */
  3276. }
  3277. #endif /* 16BIT */
  3278. }
  3279. #endif /* READ_GAMMA */
  3280. /* HARDWARE OR SOFTWARE OPTION SUPPORT */
  3281. #ifdef PNG_SET_OPTION_SUPPORTED
  3282. int PNGAPI
  3283. png_set_option(png_structrp png_ptr, int option, int onoff)
  3284. {
  3285. if (png_ptr != NULL && option >= 0 && option < PNG_OPTION_NEXT &&
  3286. (option & 1) == 0)
  3287. {
  3288. png_uint_32 mask = 3U << option;
  3289. png_uint_32 setting = (2U + (onoff != 0)) << option;
  3290. png_uint_32 current = png_ptr->options;
  3291. png_ptr->options = (png_uint_32)((current & ~mask) | setting);
  3292. return (int)(current & mask) >> option;
  3293. }
  3294. return PNG_OPTION_INVALID;
  3295. }
  3296. #endif
  3297. /* sRGB support */
  3298. #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\
  3299. defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
  3300. /* sRGB conversion tables; these are machine generated with the code in
  3301. * contrib/tools/makesRGB.c. The actual sRGB transfer curve defined in the
  3302. * specification (see the article at https://en.wikipedia.org/wiki/SRGB)
  3303. * is used, not the gamma=1/2.2 approximation use elsewhere in libpng.
  3304. * The sRGB to linear table is exact (to the nearest 16-bit linear fraction).
  3305. * The inverse (linear to sRGB) table has accuracies as follows:
  3306. *
  3307. * For all possible (255*65535+1) input values:
  3308. *
  3309. * error: -0.515566 - 0.625971, 79441 (0.475369%) of readings inexact
  3310. *
  3311. * For the input values corresponding to the 65536 16-bit values:
  3312. *
  3313. * error: -0.513727 - 0.607759, 308 (0.469978%) of readings inexact
  3314. *
  3315. * In all cases the inexact readings are only off by one.
  3316. */
  3317. #ifdef PNG_SIMPLIFIED_READ_SUPPORTED
  3318. /* The convert-to-sRGB table is only currently required for read. */
  3319. const png_uint_16 png_sRGB_table[256] =
  3320. {
  3321. 0,20,40,60,80,99,119,139,
  3322. 159,179,199,219,241,264,288,313,
  3323. 340,367,396,427,458,491,526,562,
  3324. 599,637,677,718,761,805,851,898,
  3325. 947,997,1048,1101,1156,1212,1270,1330,
  3326. 1391,1453,1517,1583,1651,1720,1790,1863,
  3327. 1937,2013,2090,2170,2250,2333,2418,2504,
  3328. 2592,2681,2773,2866,2961,3058,3157,3258,
  3329. 3360,3464,3570,3678,3788,3900,4014,4129,
  3330. 4247,4366,4488,4611,4736,4864,4993,5124,
  3331. 5257,5392,5530,5669,5810,5953,6099,6246,
  3332. 6395,6547,6700,6856,7014,7174,7335,7500,
  3333. 7666,7834,8004,8177,8352,8528,8708,8889,
  3334. 9072,9258,9445,9635,9828,10022,10219,10417,
  3335. 10619,10822,11028,11235,11446,11658,11873,12090,
  3336. 12309,12530,12754,12980,13209,13440,13673,13909,
  3337. 14146,14387,14629,14874,15122,15371,15623,15878,
  3338. 16135,16394,16656,16920,17187,17456,17727,18001,
  3339. 18277,18556,18837,19121,19407,19696,19987,20281,
  3340. 20577,20876,21177,21481,21787,22096,22407,22721,
  3341. 23038,23357,23678,24002,24329,24658,24990,25325,
  3342. 25662,26001,26344,26688,27036,27386,27739,28094,
  3343. 28452,28813,29176,29542,29911,30282,30656,31033,
  3344. 31412,31794,32179,32567,32957,33350,33745,34143,
  3345. 34544,34948,35355,35764,36176,36591,37008,37429,
  3346. 37852,38278,38706,39138,39572,40009,40449,40891,
  3347. 41337,41785,42236,42690,43147,43606,44069,44534,
  3348. 45002,45473,45947,46423,46903,47385,47871,48359,
  3349. 48850,49344,49841,50341,50844,51349,51858,52369,
  3350. 52884,53401,53921,54445,54971,55500,56032,56567,
  3351. 57105,57646,58190,58737,59287,59840,60396,60955,
  3352. 61517,62082,62650,63221,63795,64372,64952,65535
  3353. };
  3354. #endif /* SIMPLIFIED_READ */
  3355. /* The base/delta tables are required for both read and write (but currently
  3356. * only the simplified versions.)
  3357. */
  3358. const png_uint_16 png_sRGB_base[512] =
  3359. {
  3360. 128,1782,3383,4644,5675,6564,7357,8074,
  3361. 8732,9346,9921,10463,10977,11466,11935,12384,
  3362. 12816,13233,13634,14024,14402,14769,15125,15473,
  3363. 15812,16142,16466,16781,17090,17393,17690,17981,
  3364. 18266,18546,18822,19093,19359,19621,19879,20133,
  3365. 20383,20630,20873,21113,21349,21583,21813,22041,
  3366. 22265,22487,22707,22923,23138,23350,23559,23767,
  3367. 23972,24175,24376,24575,24772,24967,25160,25352,
  3368. 25542,25730,25916,26101,26284,26465,26645,26823,
  3369. 27000,27176,27350,27523,27695,27865,28034,28201,
  3370. 28368,28533,28697,28860,29021,29182,29341,29500,
  3371. 29657,29813,29969,30123,30276,30429,30580,30730,
  3372. 30880,31028,31176,31323,31469,31614,31758,31902,
  3373. 32045,32186,32327,32468,32607,32746,32884,33021,
  3374. 33158,33294,33429,33564,33697,33831,33963,34095,
  3375. 34226,34357,34486,34616,34744,34873,35000,35127,
  3376. 35253,35379,35504,35629,35753,35876,35999,36122,
  3377. 36244,36365,36486,36606,36726,36845,36964,37083,
  3378. 37201,37318,37435,37551,37668,37783,37898,38013,
  3379. 38127,38241,38354,38467,38580,38692,38803,38915,
  3380. 39026,39136,39246,39356,39465,39574,39682,39790,
  3381. 39898,40005,40112,40219,40325,40431,40537,40642,
  3382. 40747,40851,40955,41059,41163,41266,41369,41471,
  3383. 41573,41675,41777,41878,41979,42079,42179,42279,
  3384. 42379,42478,42577,42676,42775,42873,42971,43068,
  3385. 43165,43262,43359,43456,43552,43648,43743,43839,
  3386. 43934,44028,44123,44217,44311,44405,44499,44592,
  3387. 44685,44778,44870,44962,45054,45146,45238,45329,
  3388. 45420,45511,45601,45692,45782,45872,45961,46051,
  3389. 46140,46229,46318,46406,46494,46583,46670,46758,
  3390. 46846,46933,47020,47107,47193,47280,47366,47452,
  3391. 47538,47623,47709,47794,47879,47964,48048,48133,
  3392. 48217,48301,48385,48468,48552,48635,48718,48801,
  3393. 48884,48966,49048,49131,49213,49294,49376,49458,
  3394. 49539,49620,49701,49782,49862,49943,50023,50103,
  3395. 50183,50263,50342,50422,50501,50580,50659,50738,
  3396. 50816,50895,50973,51051,51129,51207,51285,51362,
  3397. 51439,51517,51594,51671,51747,51824,51900,51977,
  3398. 52053,52129,52205,52280,52356,52432,52507,52582,
  3399. 52657,52732,52807,52881,52956,53030,53104,53178,
  3400. 53252,53326,53400,53473,53546,53620,53693,53766,
  3401. 53839,53911,53984,54056,54129,54201,54273,54345,
  3402. 54417,54489,54560,54632,54703,54774,54845,54916,
  3403. 54987,55058,55129,55199,55269,55340,55410,55480,
  3404. 55550,55620,55689,55759,55828,55898,55967,56036,
  3405. 56105,56174,56243,56311,56380,56448,56517,56585,
  3406. 56653,56721,56789,56857,56924,56992,57059,57127,
  3407. 57194,57261,57328,57395,57462,57529,57595,57662,
  3408. 57728,57795,57861,57927,57993,58059,58125,58191,
  3409. 58256,58322,58387,58453,58518,58583,58648,58713,
  3410. 58778,58843,58908,58972,59037,59101,59165,59230,
  3411. 59294,59358,59422,59486,59549,59613,59677,59740,
  3412. 59804,59867,59930,59993,60056,60119,60182,60245,
  3413. 60308,60370,60433,60495,60558,60620,60682,60744,
  3414. 60806,60868,60930,60992,61054,61115,61177,61238,
  3415. 61300,61361,61422,61483,61544,61605,61666,61727,
  3416. 61788,61848,61909,61969,62030,62090,62150,62211,
  3417. 62271,62331,62391,62450,62510,62570,62630,62689,
  3418. 62749,62808,62867,62927,62986,63045,63104,63163,
  3419. 63222,63281,63340,63398,63457,63515,63574,63632,
  3420. 63691,63749,63807,63865,63923,63981,64039,64097,
  3421. 64155,64212,64270,64328,64385,64443,64500,64557,
  3422. 64614,64672,64729,64786,64843,64900,64956,65013,
  3423. 65070,65126,65183,65239,65296,65352,65409,65465
  3424. };
  3425. const png_byte png_sRGB_delta[512] =
  3426. {
  3427. 207,201,158,129,113,100,90,82,77,72,68,64,61,59,56,54,
  3428. 52,50,49,47,46,45,43,42,41,40,39,39,38,37,36,36,
  3429. 35,34,34,33,33,32,32,31,31,30,30,30,29,29,28,28,
  3430. 28,27,27,27,27,26,26,26,25,25,25,25,24,24,24,24,
  3431. 23,23,23,23,23,22,22,22,22,22,22,21,21,21,21,21,
  3432. 21,20,20,20,20,20,20,20,20,19,19,19,19,19,19,19,
  3433. 19,18,18,18,18,18,18,18,18,18,18,17,17,17,17,17,
  3434. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  3435. 16,16,16,16,15,15,15,15,15,15,15,15,15,15,15,15,
  3436. 15,15,15,15,14,14,14,14,14,14,14,14,14,14,14,14,
  3437. 14,14,14,14,14,14,14,13,13,13,13,13,13,13,13,13,
  3438. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,
  3439. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  3440. 12,12,12,12,12,12,12,12,12,12,12,12,11,11,11,11,
  3441. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  3442. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  3443. 11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  3444. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  3445. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  3446. 10,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
  3447. 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
  3448. 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
  3449. 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
  3450. 9,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  3451. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  3452. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  3453. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  3454. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  3455. 8,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,
  3456. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  3457. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  3458. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
  3459. };
  3460. #endif /* SIMPLIFIED READ/WRITE sRGB support */
  3461. /* SIMPLIFIED READ/WRITE SUPPORT */
  3462. #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) ||\
  3463. defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
  3464. static int
  3465. png_image_free_function(png_voidp argument)
  3466. {
  3467. png_imagep image = png_voidcast(png_imagep, argument);
  3468. png_controlp cp = image->opaque;
  3469. png_control c;
  3470. /* Double check that we have a png_ptr - it should be impossible to get here
  3471. * without one.
  3472. */
  3473. if (cp->png_ptr == NULL)
  3474. return 0;
  3475. /* First free any data held in the control structure. */
  3476. # ifdef PNG_STDIO_SUPPORTED
  3477. if (cp->owned_file != 0)
  3478. {
  3479. FILE *fp = png_voidcast(FILE *, cp->png_ptr->io_ptr);
  3480. cp->owned_file = 0;
  3481. /* Ignore errors here. */
  3482. if (fp != NULL)
  3483. {
  3484. cp->png_ptr->io_ptr = NULL;
  3485. (void)fclose(fp);
  3486. }
  3487. }
  3488. # endif
  3489. /* Copy the control structure so that the original, allocated, version can be
  3490. * safely freed. Notice that a png_error here stops the remainder of the
  3491. * cleanup, but this is probably fine because that would indicate bad memory
  3492. * problems anyway.
  3493. */
  3494. c = *cp;
  3495. image->opaque = &c;
  3496. png_free(c.png_ptr, cp);
  3497. /* Then the structures, calling the correct API. */
  3498. if (c.for_write != 0)
  3499. {
  3500. # ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
  3501. png_destroy_write_struct(&c.png_ptr, &c.info_ptr);
  3502. # else
  3503. png_error(c.png_ptr, "simplified write not supported");
  3504. # endif
  3505. }
  3506. else
  3507. {
  3508. # ifdef PNG_SIMPLIFIED_READ_SUPPORTED
  3509. png_destroy_read_struct(&c.png_ptr, &c.info_ptr, NULL);
  3510. # else
  3511. png_error(c.png_ptr, "simplified read not supported");
  3512. # endif
  3513. }
  3514. /* Success. */
  3515. return 1;
  3516. }
  3517. void PNGAPI
  3518. png_image_free(png_imagep image)
  3519. {
  3520. /* Safely call the real function, but only if doing so is safe at this point
  3521. * (if not inside an error handling context). Otherwise assume
  3522. * png_safe_execute will call this API after the return.
  3523. */
  3524. if (image != NULL && image->opaque != NULL &&
  3525. image->opaque->error_buf == NULL)
  3526. {
  3527. png_image_free_function(image);
  3528. image->opaque = NULL;
  3529. }
  3530. }
  3531. int /* PRIVATE */
  3532. png_image_error(png_imagep image, png_const_charp error_message)
  3533. {
  3534. /* Utility to log an error. */
  3535. png_safecat(image->message, (sizeof image->message), 0, error_message);
  3536. image->warning_or_error |= PNG_IMAGE_ERROR;
  3537. png_image_free(image);
  3538. return 0;
  3539. }
  3540. #endif /* SIMPLIFIED READ/WRITE */
  3541. #endif /* READ || WRITE */