png.c 132 KB

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