png.c 151 KB

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