png.c 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934
  1. /* png.c - location for general purpose libpng functions
  2. *
  3. * Last changed in libpng 1.5.23 [July 23, 2015]
  4. * Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson
  5. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  6. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  7. *
  8. * This code is released under the libpng license.
  9. * For conditions of distribution and use, see the disclaimer
  10. * and license in png.h
  11. */
  12. #include "pngpriv.h"
  13. /* Generate a compiler error if there is an old png.h in the search path. */
  14. typedef png_libpng_version_1_5_26 Your_png_h_is_not_version_1_5_26;
  15. /* Tells libpng that we have already handled the first "num_bytes" bytes
  16. * of the PNG file signature. If the PNG data is embedded into another
  17. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  18. * or write any of the magic bytes before it starts on the IHDR.
  19. */
  20. #ifdef PNG_READ_SUPPORTED
  21. void PNGAPI
  22. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  23. {
  24. unsigned int nb = (unsigned int)num_bytes;
  25. png_debug(1, "in png_set_sig_bytes");
  26. if (png_ptr == NULL)
  27. return;
  28. if (num_bytes < 0)
  29. nb = 0;
  30. if (nb > 8)
  31. png_error(png_ptr, "Too many bytes for PNG signature");
  32. png_ptr->sig_bytes = (png_byte)nb;
  33. }
  34. /* Checks whether the supplied bytes match the PNG signature. We allow
  35. * checking less than the full 8-byte signature so that those apps that
  36. * already read the first few bytes of a file to determine the file type
  37. * can simply check the remaining bytes for extra assurance. Returns
  38. * an integer less than, equal to, or greater than zero if sig is found,
  39. * respectively, to be less than, to match, or be greater than the correct
  40. * PNG signature (this is the same behavior as strcmp, memcmp, etc).
  41. */
  42. int PNGAPI
  43. png_sig_cmp(png_const_bytep sig, png_size_t start, png_size_t num_to_check)
  44. {
  45. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  46. if (num_to_check > 8)
  47. num_to_check = 8;
  48. else if (num_to_check < 1)
  49. return (-1);
  50. if (start > 7)
  51. return (-1);
  52. if (start + num_to_check > 8)
  53. num_to_check = 8 - start;
  54. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  55. }
  56. #endif /* PNG_READ_SUPPORTED */
  57. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  58. /* Function to allocate memory for zlib */
  59. PNG_FUNCTION(voidpf /* PRIVATE */,
  60. png_zalloc,(voidpf png_ptr, uInt items, uInt size),PNG_ALLOCATED)
  61. {
  62. png_voidp ptr;
  63. png_structp p;
  64. png_uint_32 save_flags;
  65. png_alloc_size_t num_bytes;
  66. if (png_ptr == NULL)
  67. return (NULL);
  68. p=(png_structp)png_ptr;
  69. save_flags=p->flags;
  70. if (items > PNG_UINT_32_MAX/size)
  71. {
  72. png_warning (p, "Potential overflow in png_zalloc()");
  73. return (NULL);
  74. }
  75. num_bytes = (png_alloc_size_t)items * size;
  76. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  77. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  78. p->flags=save_flags;
  79. return ((voidpf)ptr);
  80. }
  81. /* Function to free memory for zlib */
  82. void /* PRIVATE */
  83. png_zfree(voidpf png_ptr, voidpf ptr)
  84. {
  85. png_free((png_structp)png_ptr, (png_voidp)ptr);
  86. }
  87. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  88. * in case CRC is > 32 bits to leave the top bits 0.
  89. */
  90. void /* PRIVATE */
  91. png_reset_crc(png_structp png_ptr)
  92. {
  93. /* The cast is safe because the crc is a 32 bit value. */
  94. png_ptr->crc = (png_uint_32)crc32(0, Z_NULL, 0);
  95. }
  96. /* Calculate the CRC over a section of data. We can only pass as
  97. * much data to this routine as the largest single buffer size. We
  98. * also check that this data will actually be used before going to the
  99. * trouble of calculating it.
  100. */
  101. void /* PRIVATE */
  102. png_calculate_crc(png_structp png_ptr, png_const_bytep ptr, png_size_t length)
  103. {
  104. int need_crc = 1;
  105. if (PNG_CHUNK_ANCILLIARY(png_ptr->chunk_name))
  106. {
  107. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  108. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  109. need_crc = 0;
  110. }
  111. else /* critical */
  112. {
  113. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  114. need_crc = 0;
  115. }
  116. /* 'uLong' is defined as unsigned long, this means that on some systems it is
  117. * a 64 bit value. crc32, however, returns 32 bits so the following cast is
  118. * safe. 'uInt' may be no more than 16 bits, so it is necessary to perform a
  119. * loop here.
  120. */
  121. if (need_crc && length > 0)
  122. {
  123. uLong crc = png_ptr->crc; /* Should never issue a warning */
  124. do
  125. {
  126. uInt safeLength = (uInt)length;
  127. #ifndef __COVERITY__
  128. if (safeLength == 0)
  129. safeLength = (uInt)-1; /* evil, but safe */
  130. #endif
  131. crc = crc32(crc, ptr, safeLength);
  132. /* The following should never issue compiler warnings, if they do the
  133. * target system has characteristics that will probably violate other
  134. * assumptions within the libpng code.
  135. */
  136. ptr += safeLength;
  137. length -= safeLength;
  138. }
  139. while (length > 0);
  140. /* And the following is always safe because the crc is only 32 bits. */
  141. png_ptr->crc = (png_uint_32)crc;
  142. }
  143. }
  144. /* Check a user supplied version number, called from both read and write
  145. * functions that create a png_struct
  146. */
  147. int
  148. png_user_version_check(png_structp png_ptr, png_const_charp user_png_ver)
  149. {
  150. /* Libpng versions 1.0.0 and later are binary compatible if the version
  151. * string matches through the second '.'; we must recompile any
  152. * applications that use any older library version.
  153. */
  154. if (user_png_ver != NULL)
  155. {
  156. int i = -1;
  157. int found_dots = 0;
  158. do
  159. {
  160. i++;
  161. if (user_png_ver[i] != PNG_LIBPNG_VER_STRING[i])
  162. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  163. if (user_png_ver[i] == '.')
  164. found_dots++;
  165. } while (found_dots < 2 && user_png_ver[i] != 0 &&
  166. PNG_LIBPNG_VER_STRING[i] != 0);
  167. }
  168. else
  169. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  170. if ((png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH) != 0)
  171. {
  172. #ifdef PNG_WARNINGS_SUPPORTED
  173. size_t pos = 0;
  174. char m[128];
  175. pos = png_safecat(m, (sizeof m), pos,
  176. "Application built with libpng-");
  177. pos = png_safecat(m, (sizeof m), pos, user_png_ver);
  178. pos = png_safecat(m, (sizeof m), pos, " but running with ");
  179. pos = png_safecat(m, (sizeof m), pos, PNG_LIBPNG_VER_STRING);
  180. PNG_UNUSED(pos)
  181. png_warning(png_ptr, m);
  182. #endif
  183. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184. png_ptr->flags = 0;
  185. #endif
  186. return 0;
  187. }
  188. /* Success return. */
  189. return 1;
  190. }
  191. /* Allocate the memory for an info_struct for the application. We don't
  192. * really need the png_ptr, but it could potentially be useful in the
  193. * future. This should be used in favour of malloc(png_sizeof(png_info))
  194. * and png_info_init() so that applications that want to use a shared
  195. * libpng don't have to be recompiled if png_info changes size.
  196. */
  197. PNG_FUNCTION(png_infop,PNGAPI
  198. png_create_info_struct,(png_structp png_ptr),PNG_ALLOCATED)
  199. {
  200. png_infop info_ptr;
  201. png_debug(1, "in png_create_info_struct");
  202. if (png_ptr == NULL)
  203. return (NULL);
  204. #ifdef PNG_USER_MEM_SUPPORTED
  205. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  206. png_ptr->malloc_fn, png_ptr->mem_ptr);
  207. #else
  208. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  209. #endif
  210. if (info_ptr != NULL)
  211. png_info_init_3(&info_ptr, png_sizeof(png_info));
  212. return (info_ptr);
  213. }
  214. /* This function frees the memory associated with a single info struct.
  215. * Normally, one would use either png_destroy_read_struct() or
  216. * png_destroy_write_struct() to free an info struct, but this may be
  217. * useful for some applications.
  218. */
  219. void PNGAPI
  220. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  221. {
  222. png_infop info_ptr = NULL;
  223. png_debug(1, "in png_destroy_info_struct");
  224. if (png_ptr == NULL)
  225. return;
  226. if (info_ptr_ptr != NULL)
  227. info_ptr = *info_ptr_ptr;
  228. if (info_ptr != NULL)
  229. {
  230. png_info_destroy(png_ptr, info_ptr);
  231. #ifdef PNG_USER_MEM_SUPPORTED
  232. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  233. png_ptr->mem_ptr);
  234. #else
  235. png_destroy_struct((png_voidp)info_ptr);
  236. #endif
  237. *info_ptr_ptr = NULL;
  238. }
  239. }
  240. /* Initialize the info structure. This is now an internal function (0.89)
  241. * and applications using it are urged to use png_create_info_struct()
  242. * instead.
  243. */
  244. void PNGAPI
  245. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  246. {
  247. png_infop info_ptr = *ptr_ptr;
  248. png_debug(1, "in png_info_init_3");
  249. if (info_ptr == NULL)
  250. return;
  251. if (png_sizeof(png_info) > png_info_struct_size)
  252. {
  253. png_destroy_struct(info_ptr);
  254. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  255. *ptr_ptr = info_ptr;
  256. if (info_ptr == NULL)
  257. return;
  258. }
  259. /* Set everything to 0 */
  260. png_memset(info_ptr, 0, png_sizeof(png_info));
  261. }
  262. void PNGAPI
  263. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  264. int freer, png_uint_32 mask)
  265. {
  266. png_debug(1, "in png_data_freer");
  267. if (png_ptr == NULL || info_ptr == NULL)
  268. return;
  269. if (freer == PNG_DESTROY_WILL_FREE_DATA)
  270. info_ptr->free_me |= mask;
  271. else if (freer == PNG_USER_WILL_FREE_DATA)
  272. info_ptr->free_me &= ~mask;
  273. else
  274. png_warning(png_ptr,
  275. "Unknown freer parameter in png_data_freer");
  276. }
  277. void PNGAPI
  278. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  279. int num)
  280. {
  281. png_debug(1, "in png_free_data");
  282. if (png_ptr == NULL || info_ptr == NULL)
  283. return;
  284. #ifdef PNG_TEXT_SUPPORTED
  285. /* Free text item num or (if num == -1) all text items */
  286. if (info_ptr->text != 0 &&
  287. ((mask & PNG_FREE_TEXT) & info_ptr->free_me) != 0)
  288. {
  289. if (num != -1)
  290. {
  291. png_free(png_ptr, info_ptr->text[num].key);
  292. info_ptr->text[num].key = NULL;
  293. }
  294. else
  295. {
  296. int i;
  297. for (i = 0; i < info_ptr->num_text; i++)
  298. png_free(png_ptr, info_ptr->text[i].key);
  299. png_free(png_ptr, info_ptr->text);
  300. info_ptr->text = NULL;
  301. info_ptr->num_text = 0;
  302. }
  303. }
  304. #endif
  305. #ifdef PNG_tRNS_SUPPORTED
  306. /* Free any tRNS entry */
  307. if (((mask & PNG_FREE_TRNS) & info_ptr->free_me) != 0)
  308. {
  309. info_ptr->valid &= ~PNG_INFO_tRNS;
  310. png_free(png_ptr, info_ptr->trans_alpha);
  311. info_ptr->trans_alpha = NULL;
  312. info_ptr->num_trans = 0;
  313. }
  314. #endif
  315. #ifdef PNG_sCAL_SUPPORTED
  316. /* Free any sCAL entry */
  317. if (((mask & PNG_FREE_SCAL) & info_ptr->free_me) != 0)
  318. {
  319. png_free(png_ptr, info_ptr->scal_s_width);
  320. png_free(png_ptr, info_ptr->scal_s_height);
  321. info_ptr->scal_s_width = NULL;
  322. info_ptr->scal_s_height = NULL;
  323. info_ptr->valid &= ~PNG_INFO_sCAL;
  324. }
  325. #endif
  326. #ifdef PNG_pCAL_SUPPORTED
  327. /* Free any pCAL entry */
  328. if (((mask & PNG_FREE_PCAL) & info_ptr->free_me) != 0)
  329. {
  330. png_free(png_ptr, info_ptr->pcal_purpose);
  331. png_free(png_ptr, info_ptr->pcal_units);
  332. info_ptr->pcal_purpose = NULL;
  333. info_ptr->pcal_units = NULL;
  334. if (info_ptr->pcal_params != NULL)
  335. {
  336. int i;
  337. for (i = 0; i < info_ptr->pcal_nparams; i++)
  338. png_free(png_ptr, info_ptr->pcal_params[i]);
  339. png_free(png_ptr, info_ptr->pcal_params);
  340. info_ptr->pcal_params = NULL;
  341. }
  342. info_ptr->valid &= ~PNG_INFO_pCAL;
  343. }
  344. #endif
  345. #ifdef PNG_iCCP_SUPPORTED
  346. /* Free any profile entry */
  347. if (((mask & PNG_FREE_ICCP) & info_ptr->free_me) != 0)
  348. {
  349. png_free(png_ptr, info_ptr->iccp_name);
  350. png_free(png_ptr, info_ptr->iccp_profile);
  351. info_ptr->iccp_name = NULL;
  352. info_ptr->iccp_profile = NULL;
  353. info_ptr->valid &= ~PNG_INFO_iCCP;
  354. }
  355. #endif
  356. #ifdef PNG_sPLT_SUPPORTED
  357. /* Free a given sPLT entry, or (if num == -1) all sPLT entries */
  358. if (info_ptr->splt_palettes != 0 &&
  359. ((mask & PNG_FREE_SPLT) & info_ptr->free_me) != 0)
  360. {
  361. if (num != -1)
  362. {
  363. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  364. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  365. info_ptr->splt_palettes[num].name = NULL;
  366. info_ptr->splt_palettes[num].entries = NULL;
  367. }
  368. else
  369. {
  370. int i;
  371. for (i = 0; i < info_ptr->splt_palettes_num; i++)
  372. {
  373. png_free(png_ptr, info_ptr->splt_palettes[i].name);
  374. png_free(png_ptr, info_ptr->splt_palettes[i].entries);
  375. }
  376. png_free(png_ptr, info_ptr->splt_palettes);
  377. info_ptr->splt_palettes = NULL;
  378. info_ptr->splt_palettes_num = 0;
  379. info_ptr->valid &= ~PNG_INFO_sPLT;
  380. }
  381. }
  382. #endif
  383. #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
  384. if (info_ptr->unknown_chunks != 0 &&
  385. ((mask & PNG_FREE_UNKN) & info_ptr->free_me) != 0)
  386. {
  387. if (num != -1)
  388. {
  389. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  390. info_ptr->unknown_chunks[num].data = NULL;
  391. }
  392. else
  393. {
  394. int i;
  395. for (i = 0; i < info_ptr->unknown_chunks_num; i++)
  396. png_free(png_ptr, info_ptr->unknown_chunks[i].data);
  397. png_free(png_ptr, info_ptr->unknown_chunks);
  398. info_ptr->unknown_chunks = NULL;
  399. info_ptr->unknown_chunks_num = 0;
  400. }
  401. }
  402. #endif
  403. #ifdef PNG_hIST_SUPPORTED
  404. /* Free any hIST entry */
  405. if (((mask & PNG_FREE_HIST) & info_ptr->free_me) != 0)
  406. {
  407. png_free(png_ptr, info_ptr->hist);
  408. info_ptr->hist = NULL;
  409. info_ptr->valid &= ~PNG_INFO_hIST;
  410. }
  411. #endif
  412. /* Free any PLTE entry that was internally allocated */
  413. if (((mask & PNG_FREE_PLTE) & info_ptr->free_me) != 0)
  414. {
  415. png_free(png_ptr, info_ptr->palette);
  416. info_ptr->palette = NULL;
  417. info_ptr->valid &= ~PNG_INFO_PLTE;
  418. info_ptr->num_palette = 0;
  419. }
  420. #ifdef PNG_INFO_IMAGE_SUPPORTED
  421. /* Free any image bits attached to the info structure */
  422. if (((mask & PNG_FREE_ROWS) & info_ptr->free_me) != 0)
  423. {
  424. if (info_ptr->row_pointers != 0)
  425. {
  426. png_uint_32 row;
  427. for (row = 0; row < info_ptr->height; row++)
  428. png_free(png_ptr, info_ptr->row_pointers[row]);
  429. png_free(png_ptr, info_ptr->row_pointers);
  430. info_ptr->row_pointers = NULL;
  431. }
  432. info_ptr->valid &= ~PNG_INFO_IDAT;
  433. }
  434. #endif
  435. if (num != -1)
  436. mask &= ~PNG_FREE_MUL;
  437. info_ptr->free_me &= ~mask;
  438. }
  439. /* This is an internal routine to free any memory that the info struct is
  440. * pointing to before re-using it or freeing the struct itself. Recall
  441. * that png_free() checks for NULL pointers for us.
  442. */
  443. void /* PRIVATE */
  444. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  445. {
  446. png_debug(1, "in png_info_destroy");
  447. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  448. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  449. if (png_ptr->num_chunk_list)
  450. {
  451. png_free(png_ptr, png_ptr->chunk_list);
  452. png_ptr->chunk_list = NULL;
  453. png_ptr->num_chunk_list = 0;
  454. }
  455. #endif
  456. png_info_init_3(&info_ptr, png_sizeof(png_info));
  457. }
  458. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  459. /* This function returns a pointer to the io_ptr associated with the user
  460. * functions. The application should free any memory associated with this
  461. * pointer before png_write_destroy() or png_read_destroy() are called.
  462. */
  463. png_voidp PNGAPI
  464. png_get_io_ptr(png_structp png_ptr)
  465. {
  466. if (png_ptr == NULL)
  467. return (NULL);
  468. return (png_ptr->io_ptr);
  469. }
  470. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  471. # ifdef PNG_STDIO_SUPPORTED
  472. /* Initialize the default input/output functions for the PNG file. If you
  473. * use your own read or write routines, you can call either png_set_read_fn()
  474. * or png_set_write_fn() instead of png_init_io(). If you have defined
  475. * PNG_NO_STDIO or otherwise disabled PNG_STDIO_SUPPORTED, you must use a
  476. * function of your own because "FILE *" isn't necessarily available.
  477. */
  478. void PNGAPI
  479. png_init_io(png_structp png_ptr, png_FILE_p fp)
  480. {
  481. png_debug(1, "in png_init_io");
  482. if (png_ptr == NULL)
  483. return;
  484. png_ptr->io_ptr = (png_voidp)fp;
  485. }
  486. # endif
  487. # ifdef PNG_TIME_RFC1123_SUPPORTED
  488. /* Convert the supplied time into an RFC 1123 string suitable for use in
  489. * a "Creation Time" or other text-based time string.
  490. */
  491. png_const_charp PNGAPI
  492. png_convert_to_rfc1123(png_structp png_ptr, png_const_timep ptime)
  493. {
  494. static PNG_CONST char short_months[12][4] =
  495. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  496. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  497. if (png_ptr == NULL)
  498. return (NULL);
  499. if (ptime->year > 9999 /* RFC1123 limitation */ ||
  500. ptime->month == 0 || ptime->month > 12 ||
  501. ptime->day == 0 || ptime->day > 31 ||
  502. ptime->hour > 23 || ptime->minute > 59 ||
  503. ptime->second > 60)
  504. {
  505. png_warning(png_ptr, "Ignoring invalid time value");
  506. return (NULL);
  507. }
  508. {
  509. size_t pos = 0;
  510. char number_buf[5]; /* enough for a four-digit year */
  511. # define APPEND_STRING(string)\
  512. pos = png_safecat(png_ptr->time_buffer, sizeof png_ptr->time_buffer,\
  513. pos, (string))
  514. # define APPEND_NUMBER(format, value)\
  515. APPEND_STRING(PNG_FORMAT_NUMBER(number_buf, format, (value)))
  516. # define APPEND(ch)\
  517. if (pos < (sizeof png_ptr->time_buffer)-1)\
  518. png_ptr->time_buffer[pos++] = (ch)
  519. APPEND_NUMBER(PNG_NUMBER_FORMAT_u, (unsigned)ptime->day);
  520. APPEND(' ');
  521. APPEND_STRING(short_months[(ptime->month - 1)]);
  522. APPEND(' ');
  523. APPEND_NUMBER(PNG_NUMBER_FORMAT_u, ptime->year);
  524. APPEND(' ');
  525. APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->hour);
  526. APPEND(':');
  527. APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->minute);
  528. APPEND(':');
  529. APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->second);
  530. APPEND_STRING(" +0000"); /* This reliably terminates the buffer */
  531. # undef APPEND
  532. # undef APPEND_NUMBER
  533. # undef APPEND_STRING
  534. }
  535. return png_ptr->time_buffer;
  536. }
  537. # endif /* PNG_TIME_RFC1123_SUPPORTED */
  538. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  539. png_const_charp PNGAPI
  540. png_get_copyright(png_const_structp png_ptr)
  541. {
  542. PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
  543. #ifdef PNG_STRING_COPYRIGHT
  544. return PNG_STRING_COPYRIGHT
  545. #else
  546. # ifdef __STDC__
  547. return PNG_STRING_NEWLINE \
  548. "libpng version 1.5.26 - December 17, 2015" PNG_STRING_NEWLINE \
  549. "Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson" \
  550. PNG_STRING_NEWLINE \
  551. "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
  552. "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
  553. PNG_STRING_NEWLINE;
  554. # else
  555. return "libpng version 1.5.26 - December 17, 2015\
  556. Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson\
  557. Copyright (c) 1996-1997 Andreas Dilger\
  558. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.";
  559. # endif
  560. #endif
  561. }
  562. /* The following return the library version as a short string in the
  563. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  564. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  565. * is defined in png.h.
  566. * Note: now there is no difference between png_get_libpng_ver() and
  567. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  568. * it is guaranteed that png.c uses the correct version of png.h.
  569. */
  570. png_const_charp PNGAPI
  571. png_get_libpng_ver(png_const_structp png_ptr)
  572. {
  573. /* Version of *.c files used when building libpng */
  574. return png_get_header_ver(png_ptr);
  575. }
  576. png_const_charp PNGAPI
  577. png_get_header_ver(png_const_structp png_ptr)
  578. {
  579. /* Version of *.h files used when building libpng */
  580. PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
  581. return PNG_LIBPNG_VER_STRING;
  582. }
  583. png_const_charp PNGAPI
  584. png_get_header_version(png_const_structp png_ptr)
  585. {
  586. /* Returns longer string containing both version and date */
  587. PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
  588. #ifdef __STDC__
  589. return PNG_HEADER_VERSION_STRING
  590. # ifndef PNG_READ_SUPPORTED
  591. " (NO READ SUPPORT)"
  592. # endif
  593. PNG_STRING_NEWLINE;
  594. #else
  595. return PNG_HEADER_VERSION_STRING;
  596. #endif
  597. }
  598. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  599. int PNGAPI
  600. png_handle_as_unknown(png_structp png_ptr, png_const_bytep chunk_name)
  601. {
  602. /* Check chunk_name and return "keep" value if it's on the list, else 0 */
  603. png_const_bytep p, p_end;
  604. if (png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list <= 0)
  605. return PNG_HANDLE_CHUNK_AS_DEFAULT;
  606. p_end = png_ptr->chunk_list;
  607. p = p_end + png_ptr->num_chunk_list*5; /* beyond end */
  608. /* The code is the fifth byte after each four byte string. Historically this
  609. * code was always searched from the end of the list, so it should continue
  610. * to do so in case there are duplicated entries.
  611. */
  612. do /* num_chunk_list > 0, so at least one */
  613. {
  614. p -= 5;
  615. if (!png_memcmp(chunk_name, p, 4))
  616. return p[4];
  617. }
  618. while (p > p_end);
  619. return PNG_HANDLE_CHUNK_AS_DEFAULT;
  620. }
  621. int /* PRIVATE */
  622. png_chunk_unknown_handling(png_structp png_ptr, png_uint_32 chunk_name)
  623. {
  624. png_byte chunk_string[5];
  625. PNG_CSTRING_FROM_CHUNK(chunk_string, chunk_name);
  626. return png_handle_as_unknown(png_ptr, chunk_string);
  627. }
  628. #endif
  629. #ifdef PNG_READ_SUPPORTED
  630. /* This function, added to libpng-1.0.6g, is untested. */
  631. int PNGAPI
  632. png_reset_zstream(png_structp png_ptr)
  633. {
  634. if (png_ptr == NULL)
  635. return Z_STREAM_ERROR;
  636. return (inflateReset(&png_ptr->zstream));
  637. }
  638. #endif /* PNG_READ_SUPPORTED */
  639. /* This function was added to libpng-1.0.7 */
  640. png_uint_32 PNGAPI
  641. png_access_version_number(void)
  642. {
  643. /* Version of *.c files used when building libpng */
  644. return((png_uint_32)PNG_LIBPNG_VER);
  645. }
  646. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  647. /* png_convert_size: a PNGAPI but no longer in png.h, so deleted
  648. * at libpng 1.5.5!
  649. */
  650. /* Added at libpng version 1.2.34 and 1.4.0 (moved from pngset.c) */
  651. # ifdef PNG_CHECK_cHRM_SUPPORTED
  652. int /* PRIVATE */
  653. png_check_cHRM_fixed(png_structp png_ptr,
  654. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  655. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  656. png_fixed_point blue_x, png_fixed_point blue_y)
  657. {
  658. int ret = 1;
  659. unsigned long xy_hi,xy_lo,yx_hi,yx_lo;
  660. png_debug(1, "in function png_check_cHRM_fixed");
  661. if (png_ptr == NULL)
  662. return 0;
  663. /* (x,y,z) values are first limited to 0..100000 (PNG_FP_1), the white
  664. * y must also be greater than 0. To test for the upper limit calculate
  665. * (PNG_FP_1-y) - x must be <= to this for z to be >= 0 (and the expression
  666. * cannot overflow.) At this point we know x and y are >= 0 and (x+y) is
  667. * <= PNG_FP_1. The previous test on PNG_MAX_UINT_31 is removed because it
  668. * pointless (and it produces compiler warnings!)
  669. */
  670. if (white_x < 0 || white_y <= 0 ||
  671. red_x < 0 || red_y < 0 ||
  672. green_x < 0 || green_y < 0 ||
  673. blue_x < 0 || blue_y < 0)
  674. {
  675. png_warning(png_ptr,
  676. "Ignoring attempt to set negative chromaticity value");
  677. ret = 0;
  678. }
  679. /* And (x+y) must be <= PNG_FP_1 (so z is >= 0) */
  680. if (white_x > PNG_FP_1 - white_y)
  681. {
  682. png_warning(png_ptr, "Invalid cHRM white point");
  683. ret = 0;
  684. }
  685. if (red_x > PNG_FP_1 - red_y)
  686. {
  687. png_warning(png_ptr, "Invalid cHRM red point");
  688. ret = 0;
  689. }
  690. if (green_x > PNG_FP_1 - green_y)
  691. {
  692. png_warning(png_ptr, "Invalid cHRM green point");
  693. ret = 0;
  694. }
  695. if (blue_x > PNG_FP_1 - blue_y)
  696. {
  697. png_warning(png_ptr, "Invalid cHRM blue point");
  698. ret = 0;
  699. }
  700. png_64bit_product(green_x - red_x, blue_y - red_y, &xy_hi, &xy_lo);
  701. png_64bit_product(green_y - red_y, blue_x - red_x, &yx_hi, &yx_lo);
  702. if (xy_hi == yx_hi && xy_lo == yx_lo)
  703. {
  704. png_warning(png_ptr,
  705. "Ignoring attempt to set cHRM RGB triangle with zero area");
  706. ret = 0;
  707. }
  708. return ret;
  709. }
  710. # endif /* PNG_CHECK_cHRM_SUPPORTED */
  711. #ifdef PNG_cHRM_SUPPORTED
  712. /* Added at libpng-1.5.5 to support read and write of true CIEXYZ values for
  713. * cHRM, as opposed to using chromaticities. These internal APIs return
  714. * non-zero on a parameter error. The X, Y and Z values are required to be
  715. * positive and less than 1.0.
  716. */
  717. int png_xy_from_XYZ(png_xy *xy, png_XYZ XYZ)
  718. {
  719. png_int_32 d, dwhite, whiteX, whiteY;
  720. d = XYZ.redX + XYZ.redY + XYZ.redZ;
  721. if (!png_muldiv(&xy->redx, XYZ.redX, PNG_FP_1, d)) return 1;
  722. if (!png_muldiv(&xy->redy, XYZ.redY, PNG_FP_1, d)) return 1;
  723. dwhite = d;
  724. whiteX = XYZ.redX;
  725. whiteY = XYZ.redY;
  726. d = XYZ.greenX + XYZ.greenY + XYZ.greenZ;
  727. if (!png_muldiv(&xy->greenx, XYZ.greenX, PNG_FP_1, d)) return 1;
  728. if (!png_muldiv(&xy->greeny, XYZ.greenY, PNG_FP_1, d)) return 1;
  729. dwhite += d;
  730. whiteX += XYZ.greenX;
  731. whiteY += XYZ.greenY;
  732. d = XYZ.blueX + XYZ.blueY + XYZ.blueZ;
  733. if (!png_muldiv(&xy->bluex, XYZ.blueX, PNG_FP_1, d)) return 1;
  734. if (!png_muldiv(&xy->bluey, XYZ.blueY, PNG_FP_1, d)) return 1;
  735. dwhite += d;
  736. whiteX += XYZ.blueX;
  737. whiteY += XYZ.blueY;
  738. /* The reference white is simply the same of the end-point (X,Y,Z) vectors,
  739. * thus:
  740. */
  741. if (!png_muldiv(&xy->whitex, whiteX, PNG_FP_1, dwhite)) return 1;
  742. if (!png_muldiv(&xy->whitey, whiteY, PNG_FP_1, dwhite)) return 1;
  743. return 0;
  744. }
  745. int png_XYZ_from_xy(png_XYZ *XYZ, png_xy xy)
  746. {
  747. png_fixed_point red_inverse, green_inverse, blue_scale;
  748. png_fixed_point left, right, denominator;
  749. /* Check xy and, implicitly, z. Note that wide gamut color spaces typically
  750. * have end points with 0 tristimulus values (these are impossible end
  751. * points, but they are used to cover the possible colors). We check
  752. * xy.whitey against 5, not 0, to avoid a possible integer overflow.
  753. */
  754. if (xy.redx < 0 || xy.redx > PNG_FP_1) return 1;
  755. if (xy.redy < 0 || xy.redy > PNG_FP_1-xy.redx) return 1;
  756. if (xy.greenx < 0 || xy.greenx > PNG_FP_1) return 1;
  757. if (xy.greeny < 0 || xy.greeny > PNG_FP_1-xy.greenx) return 1;
  758. if (xy.bluex < 0 || xy.bluex > PNG_FP_1) return 1;
  759. if (xy.bluey < 0 || xy.bluey > PNG_FP_1-xy.bluex) return 1;
  760. if (xy.whitex < 0 || xy.whitex > PNG_FP_1) return 1;
  761. if (xy.whitey < 5 || xy.whitey > PNG_FP_1-xy.whitex) return 1;
  762. /* The reverse calculation is more difficult because the original tristimulus
  763. * value had 9 independent values (red,green,blue)x(X,Y,Z) however only 8
  764. * derived values were recorded in the cHRM chunk;
  765. * (red,green,blue,white)x(x,y). This loses one degree of freedom and
  766. * therefore an arbitrary ninth value has to be introduced to undo the
  767. * original transformations.
  768. *
  769. * Think of the original end-points as points in (X,Y,Z) space. The
  770. * chromaticity values (c) have the property:
  771. *
  772. * C
  773. * c = ---------
  774. * X + Y + Z
  775. *
  776. * For each c (x,y,z) from the corresponding original C (X,Y,Z). Thus the
  777. * three chromaticity values (x,y,z) for each end-point obey the
  778. * relationship:
  779. *
  780. * x + y + z = 1
  781. *
  782. * This describes the plane in (X,Y,Z) space that intersects each axis at the
  783. * value 1.0; call this the chromaticity plane. Thus the chromaticity
  784. * calculation has scaled each end-point so that it is on the x+y+z=1 plane
  785. * and chromaticity is the intersection of the vector from the origin to the
  786. * (X,Y,Z) value with the chromaticity plane.
  787. *
  788. * To fully invert the chromaticity calculation we would need the three
  789. * end-point scale factors, (red-scale, green-scale, blue-scale), but these
  790. * were not recorded. Instead we calculated the reference white (X,Y,Z) and
  791. * recorded the chromaticity of this. The reference white (X,Y,Z) would have
  792. * given all three of the scale factors since:
  793. *
  794. * color-C = color-c * color-scale
  795. * white-C = red-C + green-C + blue-C
  796. * = red-c*red-scale + green-c*green-scale + blue-c*blue-scale
  797. *
  798. * But cHRM records only white-x and white-y, so we have lost the white scale
  799. * factor:
  800. *
  801. * white-C = white-c*white-scale
  802. *
  803. * To handle this the inverse transformation makes an arbitrary assumption
  804. * about white-scale:
  805. *
  806. * Assume: white-Y = 1.0
  807. * Hence: white-scale = 1/white-y
  808. * Or: red-Y + green-Y + blue-Y = 1.0
  809. *
  810. * Notice the last statement of the assumption gives an equation in three of
  811. * the nine values we want to calculate. 8 more equations come from the
  812. * above routine as summarised at the top above (the chromaticity
  813. * calculation):
  814. *
  815. * Given: color-x = color-X / (color-X + color-Y + color-Z)
  816. * Hence: (color-x - 1)*color-X + color.x*color-Y + color.x*color-Z = 0
  817. *
  818. * This is 9 simultaneous equations in the 9 variables "color-C" and can be
  819. * solved by Cramer's rule. Cramer's rule requires calculating 10 9x9 matrix
  820. * determinants, however this is not as bad as it seems because only 28 of
  821. * the total of 90 terms in the various matrices are non-zero. Nevertheless
  822. * Cramer's rule is notoriously numerically unstable because the determinant
  823. * calculation involves the difference of large, but similar, numbers. It is
  824. * difficult to be sure that the calculation is stable for real world values
  825. * and it is certain that it becomes unstable where the end points are close
  826. * together.
  827. *
  828. * So this code uses the perhaps slightly less optimal but more
  829. * understandable and totally obvious approach of calculating color-scale.
  830. *
  831. * This algorithm depends on the precision in white-scale and that is
  832. * (1/white-y), so we can immediately see that as white-y approaches 0 the
  833. * accuracy inherent in the cHRM chunk drops off substantially.
  834. *
  835. * libpng arithmetic: a simple invertion of the above equations
  836. * ------------------------------------------------------------
  837. *
  838. * white_scale = 1/white-y
  839. * white-X = white-x * white-scale
  840. * white-Y = 1.0
  841. * white-Z = (1 - white-x - white-y) * white_scale
  842. *
  843. * white-C = red-C + green-C + blue-C
  844. * = red-c*red-scale + green-c*green-scale + blue-c*blue-scale
  845. *
  846. * This gives us three equations in (red-scale,green-scale,blue-scale) where
  847. * all the coefficients are now known:
  848. *
  849. * red-x*red-scale + green-x*green-scale + blue-x*blue-scale
  850. * = white-x/white-y
  851. * red-y*red-scale + green-y*green-scale + blue-y*blue-scale = 1
  852. * red-z*red-scale + green-z*green-scale + blue-z*blue-scale
  853. * = (1 - white-x - white-y)/white-y
  854. *
  855. * In the last equation color-z is (1 - color-x - color-y) so we can add all
  856. * three equations together to get an alternative third:
  857. *
  858. * red-scale + green-scale + blue-scale = 1/white-y = white-scale
  859. *
  860. * So now we have a Cramer's rule solution where the determinants are just
  861. * 3x3 - far more tractible. Unfortunately 3x3 determinants still involve
  862. * multiplication of three coefficients so we can't guarantee to avoid
  863. * overflow in the libpng fixed point representation. Using Cramer's rule in
  864. * floating point is probably a good choice here, but it's not an option for
  865. * fixed point. Instead proceed to simplify the first two equations by
  866. * eliminating what is likely to be the largest value, blue-scale:
  867. *
  868. * blue-scale = white-scale - red-scale - green-scale
  869. *
  870. * Hence:
  871. *
  872. * (red-x - blue-x)*red-scale + (green-x - blue-x)*green-scale =
  873. * (white-x - blue-x)*white-scale
  874. *
  875. * (red-y - blue-y)*red-scale + (green-y - blue-y)*green-scale =
  876. * 1 - blue-y*white-scale
  877. *
  878. * And now we can trivially solve for (red-scale,green-scale):
  879. *
  880. * green-scale =
  881. * (white-x - blue-x)*white-scale - (red-x - blue-x)*red-scale
  882. * -----------------------------------------------------------
  883. * green-x - blue-x
  884. *
  885. * red-scale =
  886. * 1 - blue-y*white-scale - (green-y - blue-y) * green-scale
  887. * ---------------------------------------------------------
  888. * red-y - blue-y
  889. *
  890. * Hence:
  891. *
  892. * red-scale =
  893. * ( (green-x - blue-x) * (white-y - blue-y) -
  894. * (green-y - blue-y) * (white-x - blue-x) ) / white-y
  895. * -------------------------------------------------------------------------
  896. * (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)
  897. *
  898. * green-scale =
  899. * ( (red-y - blue-y) * (white-x - blue-x) -
  900. * (red-x - blue-x) * (white-y - blue-y) ) / white-y
  901. * -------------------------------------------------------------------------
  902. * (green-x - blue-x)*(red-y - blue-y)-(green-y - blue-y)*(red-x - blue-x)
  903. *
  904. * Accuracy:
  905. * The input values have 5 decimal digits of accuracy. The values are all in
  906. * the range 0 < value < 1, so simple products are in the same range but may
  907. * need up to 10 decimal digits to preserve the original precision and avoid
  908. * underflow. Because we are using a 32-bit signed representation we cannot
  909. * match this; the best is a little over 9 decimal digits, less than 10.
  910. *
  911. * The approach used here is to preserve the maximum precision within the
  912. * signed representation. Because the red-scale calculation above uses the
  913. * difference between two products of values that must be in the range -1..+1
  914. * it is sufficient to divide the product by 7; ceil(100,000/32767*2). The
  915. * factor is irrelevant in the calculation because it is applied to both
  916. * numerator and denominator.
  917. *
  918. * Note that the values of the differences of the products of the
  919. * chromaticities in the above equations tend to be small, for example for
  920. * the sRGB chromaticities they are:
  921. *
  922. * red numerator: -0.04751
  923. * green numerator: -0.08788
  924. * denominator: -0.2241 (without white-y multiplication)
  925. *
  926. * The resultant Y coefficients from the chromaticities of some widely used
  927. * color space definitions are (to 15 decimal places):
  928. *
  929. * sRGB
  930. * 0.212639005871510 0.715168678767756 0.072192315360734
  931. * Kodak ProPhoto
  932. * 0.288071128229293 0.711843217810102 0.000085653960605
  933. * Adobe RGB
  934. * 0.297344975250536 0.627363566255466 0.075291458493998
  935. * Adobe Wide Gamut RGB
  936. * 0.258728243040113 0.724682314948566 0.016589442011321
  937. */
  938. /* By the argument, above overflow should be impossible here. The return
  939. * value of 2 indicates an internal error to the caller.
  940. */
  941. if (!png_muldiv(&left, xy.greenx-xy.bluex, xy.redy - xy.bluey, 7)) return 2;
  942. if (!png_muldiv(&right, xy.greeny-xy.bluey, xy.redx - xy.bluex, 7)) return 2;
  943. denominator = left - right;
  944. /* Now find the red numerator. */
  945. if (!png_muldiv(&left, xy.greenx-xy.bluex, xy.whitey-xy.bluey, 7)) return 2;
  946. if (!png_muldiv(&right, xy.greeny-xy.bluey, xy.whitex-xy.bluex, 7)) return 2;
  947. /* Overflow is possible here and it indicates an extreme set of PNG cHRM
  948. * chunk values. This calculation actually returns the reciprocal of the
  949. * scale value because this allows us to delay the multiplication of white-y
  950. * into the denominator, which tends to produce a small number.
  951. */
  952. if (!png_muldiv(&red_inverse, xy.whitey, denominator, left-right) ||
  953. red_inverse <= xy.whitey /* r+g+b scales = white scale */)
  954. return 1;
  955. /* Similarly for green_inverse: */
  956. if (!png_muldiv(&left, xy.redy-xy.bluey, xy.whitex-xy.bluex, 7)) return 2;
  957. if (!png_muldiv(&right, xy.redx-xy.bluex, xy.whitey-xy.bluey, 7)) return 2;
  958. if (!png_muldiv(&green_inverse, xy.whitey, denominator, left-right) ||
  959. green_inverse <= xy.whitey)
  960. return 1;
  961. /* And the blue scale, the checks above guarantee this can't overflow but it
  962. * can still produce 0 for extreme cHRM values.
  963. */
  964. blue_scale = png_reciprocal(xy.whitey) - png_reciprocal(red_inverse) -
  965. png_reciprocal(green_inverse);
  966. if (blue_scale <= 0) return 1;
  967. /* And fill in the png_XYZ: */
  968. if (!png_muldiv(&XYZ->redX, xy.redx, PNG_FP_1, red_inverse)) return 1;
  969. if (!png_muldiv(&XYZ->redY, xy.redy, PNG_FP_1, red_inverse)) return 1;
  970. if (!png_muldiv(&XYZ->redZ, PNG_FP_1 - xy.redx - xy.redy, PNG_FP_1,
  971. red_inverse))
  972. return 1;
  973. if (!png_muldiv(&XYZ->greenX, xy.greenx, PNG_FP_1, green_inverse)) return 1;
  974. if (!png_muldiv(&XYZ->greenY, xy.greeny, PNG_FP_1, green_inverse)) return 1;
  975. if (!png_muldiv(&XYZ->greenZ, PNG_FP_1 - xy.greenx - xy.greeny, PNG_FP_1,
  976. green_inverse))
  977. return 1;
  978. if (!png_muldiv(&XYZ->blueX, xy.bluex, blue_scale, PNG_FP_1)) return 1;
  979. if (!png_muldiv(&XYZ->blueY, xy.bluey, blue_scale, PNG_FP_1)) return 1;
  980. if (!png_muldiv(&XYZ->blueZ, PNG_FP_1 - xy.bluex - xy.bluey, blue_scale,
  981. PNG_FP_1))
  982. return 1;
  983. return 0; /*success*/
  984. }
  985. int png_XYZ_from_xy_checked(png_structp png_ptr, png_XYZ *XYZ, png_xy xy)
  986. {
  987. switch (png_XYZ_from_xy(XYZ, xy))
  988. {
  989. case 0: /* success */
  990. return 1;
  991. case 1:
  992. /* The chunk may be technically valid, but we got png_fixed_point
  993. * overflow while trying to get XYZ values out of it. This is
  994. * entirely benign - the cHRM chunk is pretty extreme.
  995. */
  996. png_warning(png_ptr,
  997. "extreme cHRM chunk cannot be converted to tristimulus values");
  998. break;
  999. default:
  1000. /* libpng is broken; this should be a warning but if it happens we
  1001. * want error reports so for the moment it is an error.
  1002. */
  1003. png_error(png_ptr, "internal error in png_XYZ_from_xy");
  1004. break;
  1005. }
  1006. /* ERROR RETURN */
  1007. return 0;
  1008. }
  1009. #endif
  1010. #ifdef __GNUC__
  1011. /* This exists solely to work round a warning from GNU C. */
  1012. static int /* PRIVATE */
  1013. png_gt(size_t a, size_t b)
  1014. {
  1015. return a > b;
  1016. }
  1017. #else
  1018. # define png_gt(a,b) ((a) > (b))
  1019. #endif
  1020. void /* PRIVATE */
  1021. png_check_IHDR(png_structp png_ptr,
  1022. png_uint_32 width, png_uint_32 height, int bit_depth,
  1023. int color_type, int interlace_type, int compression_type,
  1024. int filter_type)
  1025. {
  1026. int error = 0;
  1027. /* Check for width and height valid values */
  1028. if (width == 0)
  1029. {
  1030. png_warning(png_ptr, "Image width is zero in IHDR");
  1031. error = 1;
  1032. }
  1033. else if (width > PNG_UINT_31_MAX)
  1034. {
  1035. png_warning(png_ptr, "Invalid image width in IHDR");
  1036. error = 1;
  1037. }
  1038. else if (png_gt(width,
  1039. (PNG_SIZE_MAX >> 3) /* 8-byte RGBA pixels */
  1040. - 48 /* big_row_buf hack */
  1041. - 1 /* filter byte */
  1042. - 7*8 /* rounding width to multiple of 8 pix */
  1043. - 8)) /* extra max_pixel_depth pad */
  1044. {
  1045. /* The size of the row must be within the limits of this architecture.
  1046. * Because the read code can perform arbitrary transformations the
  1047. * maximum size is checked here. Because the code in png_read_start_row
  1048. * adds extra space "for safety's sake" in several places a conservative
  1049. * limit is used here.
  1050. *
  1051. * NOTE: it would be far better to check the size that is actually used,
  1052. * but the effect in the real world is minor and the changes are more
  1053. * extensive, therefore much more dangerous and much more difficult to
  1054. * write in a way that avoids compiler warnings.
  1055. */
  1056. png_warning(png_ptr, "Image width is too large for this architecture");
  1057. error = 1;
  1058. }
  1059. else
  1060. {
  1061. # ifdef PNG_SET_USER_LIMITS_SUPPORTED
  1062. if (width > png_ptr->user_width_max)
  1063. # else
  1064. if (width > PNG_USER_WIDTH_MAX)
  1065. # endif
  1066. {
  1067. png_warning(png_ptr, "Image width exceeds user limit in IHDR");
  1068. error = 1;
  1069. }
  1070. }
  1071. if (height == 0)
  1072. {
  1073. png_warning(png_ptr, "Image height is zero in IHDR");
  1074. error = 1;
  1075. }
  1076. else if (height > PNG_UINT_31_MAX)
  1077. {
  1078. png_warning(png_ptr, "Invalid image height in IHDR");
  1079. error = 1;
  1080. }
  1081. else
  1082. {
  1083. # ifdef PNG_SET_USER_LIMITS_SUPPORTED
  1084. if (height > png_ptr->user_height_max)
  1085. # else
  1086. if (height > PNG_USER_HEIGHT_MAX)
  1087. # endif
  1088. {
  1089. png_warning(png_ptr, "Image height exceeds user limit in IHDR");
  1090. error = 1;
  1091. }
  1092. }
  1093. /* Check other values */
  1094. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  1095. bit_depth != 8 && bit_depth != 16)
  1096. {
  1097. png_warning(png_ptr, "Invalid bit depth in IHDR");
  1098. error = 1;
  1099. }
  1100. if (color_type < 0 || color_type == 1 ||
  1101. color_type == 5 || color_type > 6)
  1102. {
  1103. png_warning(png_ptr, "Invalid color type in IHDR");
  1104. error = 1;
  1105. }
  1106. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  1107. ((color_type == PNG_COLOR_TYPE_RGB ||
  1108. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  1109. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  1110. {
  1111. png_warning(png_ptr, "Invalid color type/bit depth combination in IHDR");
  1112. error = 1;
  1113. }
  1114. if (interlace_type >= PNG_INTERLACE_LAST)
  1115. {
  1116. png_warning(png_ptr, "Unknown interlace method in IHDR");
  1117. error = 1;
  1118. }
  1119. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  1120. {
  1121. png_warning(png_ptr, "Unknown compression method in IHDR");
  1122. error = 1;
  1123. }
  1124. # ifdef PNG_MNG_FEATURES_SUPPORTED
  1125. /* Accept filter_method 64 (intrapixel differencing) only if
  1126. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  1127. * 2. Libpng did not read a PNG signature (this filter_method is only
  1128. * used in PNG datastreams that are embedded in MNG datastreams) and
  1129. * 3. The application called png_permit_mng_features with a mask that
  1130. * included PNG_FLAG_MNG_FILTER_64 and
  1131. * 4. The filter_method is 64 and
  1132. * 5. The color_type is RGB or RGBA
  1133. */
  1134. if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) &&
  1135. png_ptr->mng_features_permitted)
  1136. png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");
  1137. if (filter_type != PNG_FILTER_TYPE_BASE)
  1138. {
  1139. if (!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  1140. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  1141. ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) == 0) &&
  1142. (color_type == PNG_COLOR_TYPE_RGB ||
  1143. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  1144. {
  1145. png_warning(png_ptr, "Unknown filter method in IHDR");
  1146. error = 1;
  1147. }
  1148. if (png_ptr->mode & PNG_HAVE_PNG_SIGNATURE)
  1149. {
  1150. png_warning(png_ptr, "Invalid filter method in IHDR");
  1151. error = 1;
  1152. }
  1153. }
  1154. # else
  1155. if (filter_type != PNG_FILTER_TYPE_BASE)
  1156. {
  1157. png_warning(png_ptr, "Unknown filter method in IHDR");
  1158. error = 1;
  1159. }
  1160. # endif
  1161. if (error == 1)
  1162. png_error(png_ptr, "Invalid IHDR data");
  1163. }
  1164. #if defined(PNG_sCAL_SUPPORTED) || defined(PNG_pCAL_SUPPORTED)
  1165. /* ASCII to fp functions */
  1166. /* Check an ASCII formated floating point value, see the more detailed
  1167. * comments in pngpriv.h
  1168. */
  1169. /* The following is used internally to preserve the sticky flags */
  1170. #define png_fp_add(state, flags) ((state) |= (flags))
  1171. #define png_fp_set(state, value) ((state) = (value) | ((state) & PNG_FP_STICKY))
  1172. int /* PRIVATE */
  1173. png_check_fp_number(png_const_charp string, png_size_t size, int *statep,
  1174. png_size_tp whereami)
  1175. {
  1176. int state = *statep;
  1177. png_size_t i = *whereami;
  1178. while (i < size)
  1179. {
  1180. int type;
  1181. /* First find the type of the next character */
  1182. switch (string[i])
  1183. {
  1184. case 43: type = PNG_FP_SAW_SIGN; break;
  1185. case 45: type = PNG_FP_SAW_SIGN + PNG_FP_NEGATIVE; break;
  1186. case 46: type = PNG_FP_SAW_DOT; break;
  1187. case 48: type = PNG_FP_SAW_DIGIT; break;
  1188. case 49: case 50: case 51: case 52:
  1189. case 53: case 54: case 55: case 56:
  1190. case 57: type = PNG_FP_SAW_DIGIT + PNG_FP_NONZERO; break;
  1191. case 69:
  1192. case 101: type = PNG_FP_SAW_E; break;
  1193. default: goto PNG_FP_End;
  1194. }
  1195. /* Now deal with this type according to the current
  1196. * state, the type is arranged to not overlap the
  1197. * bits of the PNG_FP_STATE.
  1198. */
  1199. switch ((state & PNG_FP_STATE) + (type & PNG_FP_SAW_ANY))
  1200. {
  1201. case PNG_FP_INTEGER + PNG_FP_SAW_SIGN:
  1202. if (state & PNG_FP_SAW_ANY)
  1203. goto PNG_FP_End; /* not a part of the number */
  1204. png_fp_add(state, type);
  1205. break;
  1206. case PNG_FP_INTEGER + PNG_FP_SAW_DOT:
  1207. /* Ok as trailer, ok as lead of fraction. */
  1208. if (state & PNG_FP_SAW_DOT) /* two dots */
  1209. goto PNG_FP_End;
  1210. else if (state & PNG_FP_SAW_DIGIT) /* trailing dot? */
  1211. png_fp_add(state, type);
  1212. else
  1213. png_fp_set(state, PNG_FP_FRACTION | type);
  1214. break;
  1215. case PNG_FP_INTEGER + PNG_FP_SAW_DIGIT:
  1216. if (state & PNG_FP_SAW_DOT) /* delayed fraction */
  1217. png_fp_set(state, PNG_FP_FRACTION | PNG_FP_SAW_DOT);
  1218. png_fp_add(state, type | PNG_FP_WAS_VALID);
  1219. break;
  1220. case PNG_FP_INTEGER + PNG_FP_SAW_E:
  1221. if ((state & PNG_FP_SAW_DIGIT) == 0)
  1222. goto PNG_FP_End;
  1223. png_fp_set(state, PNG_FP_EXPONENT);
  1224. break;
  1225. /* case PNG_FP_FRACTION + PNG_FP_SAW_SIGN:
  1226. goto PNG_FP_End; ** no sign in fraction */
  1227. /* case PNG_FP_FRACTION + PNG_FP_SAW_DOT:
  1228. goto PNG_FP_End; ** Because SAW_DOT is always set */
  1229. case PNG_FP_FRACTION + PNG_FP_SAW_DIGIT:
  1230. png_fp_add(state, type | PNG_FP_WAS_VALID);
  1231. break;
  1232. case PNG_FP_FRACTION + PNG_FP_SAW_E:
  1233. /* This is correct because the trailing '.' on an
  1234. * integer is handled above - so we can only get here
  1235. * with the sequence ".E" (with no preceding digits).
  1236. */
  1237. if ((state & PNG_FP_SAW_DIGIT) == 0)
  1238. goto PNG_FP_End;
  1239. png_fp_set(state, PNG_FP_EXPONENT);
  1240. break;
  1241. case PNG_FP_EXPONENT + PNG_FP_SAW_SIGN:
  1242. if (state & PNG_FP_SAW_ANY)
  1243. goto PNG_FP_End; /* not a part of the number */
  1244. png_fp_add(state, PNG_FP_SAW_SIGN);
  1245. break;
  1246. /* case PNG_FP_EXPONENT + PNG_FP_SAW_DOT:
  1247. goto PNG_FP_End; */
  1248. case PNG_FP_EXPONENT + PNG_FP_SAW_DIGIT:
  1249. png_fp_add(state, PNG_FP_SAW_DIGIT | PNG_FP_WAS_VALID);
  1250. break;
  1251. /* case PNG_FP_EXPONEXT + PNG_FP_SAW_E:
  1252. goto PNG_FP_End; */
  1253. default: goto PNG_FP_End; /* I.e. break 2 */
  1254. }
  1255. /* The character seems ok, continue. */
  1256. ++i;
  1257. }
  1258. PNG_FP_End:
  1259. /* Here at the end, update the state and return the correct
  1260. * return code.
  1261. */
  1262. *statep = state;
  1263. *whereami = i;
  1264. return (state & PNG_FP_SAW_DIGIT) != 0;
  1265. }
  1266. /* The same but for a complete string. */
  1267. int
  1268. png_check_fp_string(png_const_charp string, png_size_t size)
  1269. {
  1270. int state=0;
  1271. png_size_t char_index=0;
  1272. if (png_check_fp_number(string, size, &state, &char_index) &&
  1273. (char_index == size || string[char_index] == 0))
  1274. return state /* must be non-zero - see above */;
  1275. return 0; /* i.e. fail */
  1276. }
  1277. #endif /* pCAL or sCAL */
  1278. #ifdef PNG_sCAL_SUPPORTED
  1279. # ifdef PNG_FLOATING_POINT_SUPPORTED
  1280. /* Utility used below - a simple accurate power of ten from an integral
  1281. * exponent.
  1282. */
  1283. static double
  1284. png_pow10(int power)
  1285. {
  1286. int recip = 0;
  1287. double d = 1.0;
  1288. /* Handle negative exponent with a reciprocal at the end because
  1289. * 10 is exact whereas .1 is inexact in base 2
  1290. */
  1291. if (power < 0)
  1292. {
  1293. if (power < DBL_MIN_10_EXP) return 0;
  1294. recip = 1, power = -power;
  1295. }
  1296. if (power > 0)
  1297. {
  1298. /* Decompose power bitwise. */
  1299. double mult = 10.0;
  1300. do
  1301. {
  1302. if (power & 1) d *= mult;
  1303. mult *= mult;
  1304. power >>= 1;
  1305. }
  1306. while (power > 0);
  1307. if (recip != 0) d = 1/d;
  1308. }
  1309. /* else power is 0 and d is 1 */
  1310. return d;
  1311. }
  1312. /* Function to format a floating point value in ASCII with a given
  1313. * precision.
  1314. */
  1315. void /* PRIVATE */
  1316. png_ascii_from_fp(png_structp png_ptr, png_charp ascii, png_size_t size,
  1317. double fp, unsigned int precision)
  1318. {
  1319. /* We use standard functions from math.h, but not printf because
  1320. * that would require stdio. The caller must supply a buffer of
  1321. * sufficient size or we will png_error. The tests on size and
  1322. * the space in ascii[] consumed are indicated below.
  1323. */
  1324. if (precision < 1)
  1325. precision = DBL_DIG;
  1326. /* Enforce the limit of the implementation precision too. */
  1327. if (precision > DBL_DIG+1)
  1328. precision = DBL_DIG+1;
  1329. /* Basic sanity checks */
  1330. if (size >= precision+5) /* See the requirements below. */
  1331. {
  1332. if (fp < 0)
  1333. {
  1334. fp = -fp;
  1335. *ascii++ = 45; /* '-' PLUS 1 TOTAL 1 */
  1336. --size;
  1337. }
  1338. if (fp >= DBL_MIN && fp <= DBL_MAX)
  1339. {
  1340. int exp_b10; /* A base 10 exponent */
  1341. double base; /* 10^exp_b10 */
  1342. /* First extract a base 10 exponent of the number,
  1343. * the calculation below rounds down when converting
  1344. * from base 2 to base 10 (multiply by log10(2) -
  1345. * 0.3010, but 77/256 is 0.3008, so exp_b10 needs to
  1346. * be increased. Note that the arithmetic shift
  1347. * performs a floor() unlike C arithmetic - using a
  1348. * C multiply would break the following for negative
  1349. * exponents.
  1350. */
  1351. (void)frexp(fp, &exp_b10); /* exponent to base 2 */
  1352. exp_b10 = (exp_b10 * 77) >> 8; /* <= exponent to base 10 */
  1353. /* Avoid underflow here. */
  1354. base = png_pow10(exp_b10); /* May underflow */
  1355. while (base < DBL_MIN || base < fp)
  1356. {
  1357. /* And this may overflow. */
  1358. double test = png_pow10(exp_b10+1);
  1359. if (test <= DBL_MAX)
  1360. ++exp_b10, base = test;
  1361. else
  1362. break;
  1363. }
  1364. /* Normalize fp and correct exp_b10, after this fp is in the
  1365. * range [.1,1) and exp_b10 is both the exponent and the digit
  1366. * *before* which the decimal point should be inserted
  1367. * (starting with 0 for the first digit). Note that this
  1368. * works even if 10^exp_b10 is out of range because of the
  1369. * test on DBL_MAX above.
  1370. */
  1371. fp /= base;
  1372. while (fp >= 1) fp /= 10, ++exp_b10;
  1373. /* Because of the code above fp may, at this point, be
  1374. * less than .1, this is ok because the code below can
  1375. * handle the leading zeros this generates, so no attempt
  1376. * is made to correct that here.
  1377. */
  1378. {
  1379. int czero, clead, cdigits;
  1380. char exponent[10];
  1381. /* Allow up to two leading zeros - this will not lengthen
  1382. * the number compared to using E-n.
  1383. */
  1384. if (exp_b10 < 0 && exp_b10 > -3) /* PLUS 3 TOTAL 4 */
  1385. {
  1386. czero = -exp_b10; /* PLUS 2 digits: TOTAL 3 */
  1387. exp_b10 = 0; /* Dot added below before first output. */
  1388. }
  1389. else
  1390. czero = 0; /* No zeros to add */
  1391. /* Generate the digit list, stripping trailing zeros and
  1392. * inserting a '.' before a digit if the exponent is 0.
  1393. */
  1394. clead = czero; /* Count of leading zeros */
  1395. cdigits = 0; /* Count of digits in list. */
  1396. do
  1397. {
  1398. double d;
  1399. fp *= 10.0;
  1400. /* Use modf here, not floor and subtract, so that
  1401. * the separation is done in one step. At the end
  1402. * of the loop don't break the number into parts so
  1403. * that the final digit is rounded.
  1404. */
  1405. if (cdigits+czero-clead+1 < (int)precision)
  1406. fp = modf(fp, &d);
  1407. else
  1408. {
  1409. d = floor(fp + .5);
  1410. if (d > 9.0)
  1411. {
  1412. /* Rounding up to 10, handle that here. */
  1413. if (czero > 0)
  1414. {
  1415. --czero, d = 1;
  1416. if (cdigits == 0) --clead;
  1417. }
  1418. else
  1419. {
  1420. while (cdigits > 0 && d > 9.0)
  1421. {
  1422. int ch = *--ascii;
  1423. if (exp_b10 != (-1))
  1424. ++exp_b10;
  1425. else if (ch == 46)
  1426. {
  1427. ch = *--ascii, ++size;
  1428. /* Advance exp_b10 to '1', so that the
  1429. * decimal point happens after the
  1430. * previous digit.
  1431. */
  1432. exp_b10 = 1;
  1433. }
  1434. --cdigits;
  1435. d = ch - 47; /* I.e. 1+(ch-48) */
  1436. }
  1437. /* Did we reach the beginning? If so adjust the
  1438. * exponent but take into account the leading
  1439. * decimal point.
  1440. */
  1441. if (d > 9.0) /* cdigits == 0 */
  1442. {
  1443. if (exp_b10 == (-1))
  1444. {
  1445. /* Leading decimal point (plus zeros?), if
  1446. * we lose the decimal point here it must
  1447. * be reentered below.
  1448. */
  1449. int ch = *--ascii;
  1450. if (ch == 46)
  1451. ++size, exp_b10 = 1;
  1452. /* Else lost a leading zero, so 'exp_b10' is
  1453. * still ok at (-1)
  1454. */
  1455. }
  1456. else
  1457. ++exp_b10;
  1458. /* In all cases we output a '1' */
  1459. d = 1.0;
  1460. }
  1461. }
  1462. }
  1463. fp = 0; /* Guarantees termination below. */
  1464. }
  1465. if (d == 0.0)
  1466. {
  1467. ++czero;
  1468. if (cdigits == 0) ++clead;
  1469. }
  1470. else
  1471. {
  1472. /* Included embedded zeros in the digit count. */
  1473. cdigits += czero - clead;
  1474. clead = 0;
  1475. while (czero > 0)
  1476. {
  1477. /* exp_b10 == (-1) means we just output the decimal
  1478. * place - after the DP don't adjust 'exp_b10' any
  1479. * more!
  1480. */
  1481. if (exp_b10 != (-1))
  1482. {
  1483. if (exp_b10 == 0) *ascii++ = 46, --size;
  1484. /* PLUS 1: TOTAL 4 */
  1485. --exp_b10;
  1486. }
  1487. *ascii++ = 48, --czero;
  1488. }
  1489. if (exp_b10 != (-1))
  1490. {
  1491. if (exp_b10 == 0) *ascii++ = 46, --size; /* counted
  1492. above */
  1493. --exp_b10;
  1494. }
  1495. *ascii++ = (char)(48 + (int)d), ++cdigits;
  1496. }
  1497. }
  1498. while (cdigits+czero-clead < (int)precision && fp > DBL_MIN);
  1499. /* The total output count (max) is now 4+precision */
  1500. /* Check for an exponent, if we don't need one we are
  1501. * done and just need to terminate the string. At
  1502. * this point exp_b10==(-1) is effectively if flag - it got
  1503. * to '-1' because of the decrement after outputting
  1504. * the decimal point above (the exponent required is
  1505. * *not* -1!)
  1506. */
  1507. if (exp_b10 >= (-1) && exp_b10 <= 2)
  1508. {
  1509. /* The following only happens if we didn't output the
  1510. * leading zeros above for negative exponent, so this
  1511. * doesn't add to the digit requirement. Note that the
  1512. * two zeros here can only be output if the two leading
  1513. * zeros were *not* output, so this doesn't increase
  1514. * the output count.
  1515. */
  1516. while (--exp_b10 >= 0) *ascii++ = 48;
  1517. *ascii = 0;
  1518. /* Total buffer requirement (including the '\0') is
  1519. * 5+precision - see check at the start.
  1520. */
  1521. return;
  1522. }
  1523. /* Here if an exponent is required, adjust size for
  1524. * the digits we output but did not count. The total
  1525. * digit output here so far is at most 1+precision - no
  1526. * decimal point and no leading or trailing zeros have
  1527. * been output.
  1528. */
  1529. size -= cdigits;
  1530. *ascii++ = 69, --size; /* 'E': PLUS 1 TOTAL 2+precision */
  1531. /* The following use of an unsigned temporary avoids ambiguities in
  1532. * the signed arithmetic on exp_b10 and permits GCC at least to do
  1533. * better optimization.
  1534. */
  1535. {
  1536. unsigned int uexp_b10;
  1537. if (exp_b10 < 0)
  1538. {
  1539. *ascii++ = 45, --size; /* '-': PLUS 1 TOTAL 3+precision */
  1540. uexp_b10 = -exp_b10;
  1541. }
  1542. else
  1543. uexp_b10 = exp_b10;
  1544. cdigits = 0;
  1545. while (uexp_b10 > 0)
  1546. {
  1547. exponent[cdigits++] = (char)(48 + uexp_b10 % 10);
  1548. uexp_b10 /= 10;
  1549. }
  1550. }
  1551. /* Need another size check here for the exponent digits, so
  1552. * this need not be considered above.
  1553. */
  1554. if ((int)size > cdigits)
  1555. {
  1556. while (cdigits > 0) *ascii++ = exponent[--cdigits];
  1557. *ascii = 0;
  1558. return;
  1559. }
  1560. }
  1561. }
  1562. else if (!(fp >= DBL_MIN))
  1563. {
  1564. *ascii++ = 48; /* '0' */
  1565. *ascii = 0;
  1566. return;
  1567. }
  1568. else
  1569. {
  1570. *ascii++ = 105; /* 'i' */
  1571. *ascii++ = 110; /* 'n' */
  1572. *ascii++ = 102; /* 'f' */
  1573. *ascii = 0;
  1574. return;
  1575. }
  1576. }
  1577. /* Here on buffer too small. */
  1578. png_error(png_ptr, "ASCII conversion buffer too small");
  1579. }
  1580. # endif /* FLOATING_POINT */
  1581. # ifdef PNG_FIXED_POINT_SUPPORTED
  1582. /* Function to format a fixed point value in ASCII.
  1583. */
  1584. void /* PRIVATE */
  1585. png_ascii_from_fixed(png_structp png_ptr, png_charp ascii, png_size_t size,
  1586. png_fixed_point fp)
  1587. {
  1588. /* Require space for 10 decimal digits, a decimal point, a minus sign and a
  1589. * trailing \0, 13 characters:
  1590. */
  1591. if (size > 12)
  1592. {
  1593. png_uint_32 num;
  1594. /* Avoid overflow here on the minimum integer. */
  1595. if (fp < 0)
  1596. *ascii++ = 45, --size, num = -fp;
  1597. else
  1598. num = fp;
  1599. if (num <= 0x80000000) /* else overflowed */
  1600. {
  1601. unsigned int ndigits = 0, first = 16 /* flag value */;
  1602. char digits[10];
  1603. while (num)
  1604. {
  1605. /* Split the low digit off num: */
  1606. unsigned int tmp = num/10;
  1607. num -= tmp*10;
  1608. digits[ndigits++] = (char)(48 + num);
  1609. /* Record the first non-zero digit, note that this is a number
  1610. * starting at 1, it's not actually the array index.
  1611. */
  1612. if (first == 16 && num > 0)
  1613. first = ndigits;
  1614. num = tmp;
  1615. }
  1616. if (ndigits > 0)
  1617. {
  1618. while (ndigits > 5) *ascii++ = digits[--ndigits];
  1619. /* The remaining digits are fractional digits, ndigits is '5' or
  1620. * smaller at this point. It is certainly not zero. Check for a
  1621. * non-zero fractional digit:
  1622. */
  1623. if (first <= 5)
  1624. {
  1625. unsigned int i;
  1626. *ascii++ = 46; /* decimal point */
  1627. /* ndigits may be <5 for small numbers, output leading zeros
  1628. * then ndigits digits to first:
  1629. */
  1630. i = 5;
  1631. while (ndigits < i) *ascii++ = 48, --i;
  1632. while (ndigits >= first) *ascii++ = digits[--ndigits];
  1633. /* Don't output the trailing zeros! */
  1634. }
  1635. }
  1636. else
  1637. *ascii++ = 48;
  1638. /* And null terminate the string: */
  1639. *ascii = 0;
  1640. return;
  1641. }
  1642. }
  1643. /* Here on buffer too small. */
  1644. png_error(png_ptr, "ASCII conversion buffer too small");
  1645. }
  1646. # endif /* FIXED_POINT */
  1647. #endif /* READ_SCAL */
  1648. #if defined(PNG_FLOATING_POINT_SUPPORTED) && \
  1649. !defined(PNG_FIXED_POINT_MACRO_SUPPORTED)
  1650. png_fixed_point
  1651. png_fixed(png_structp png_ptr, double fp, png_const_charp text)
  1652. {
  1653. double r = floor(100000 * fp + .5);
  1654. if (r > 2147483647. || r < -2147483648.)
  1655. png_fixed_error(png_ptr, text);
  1656. return (png_fixed_point)r;
  1657. }
  1658. #endif
  1659. #if defined(PNG_READ_GAMMA_SUPPORTED) || \
  1660. defined(PNG_INCH_CONVERSIONS_SUPPORTED) || defined(PNG_READ_pHYs_SUPPORTED)
  1661. /* muldiv functions */
  1662. /* This API takes signed arguments and rounds the result to the nearest
  1663. * integer (or, for a fixed point number - the standard argument - to
  1664. * the nearest .00001). Overflow and divide by zero are signalled in
  1665. * the result, a boolean - true on success, false on overflow.
  1666. */
  1667. int
  1668. png_muldiv(png_fixed_point_p res, png_fixed_point a, png_int_32 times,
  1669. png_int_32 divisor)
  1670. {
  1671. /* Return a * times / divisor, rounded. */
  1672. if (divisor != 0)
  1673. {
  1674. if (a == 0 || times == 0)
  1675. {
  1676. *res = 0;
  1677. return 1;
  1678. }
  1679. else
  1680. {
  1681. #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  1682. double r = a;
  1683. r *= times;
  1684. r /= divisor;
  1685. r = floor(r+.5);
  1686. /* A png_fixed_point is a 32-bit integer. */
  1687. if (r <= 2147483647. && r >= -2147483648.)
  1688. {
  1689. *res = (png_fixed_point)r;
  1690. return 1;
  1691. }
  1692. #else
  1693. int negative = 0;
  1694. png_uint_32 A, T, D;
  1695. png_uint_32 s16, s32, s00;
  1696. if (a < 0)
  1697. negative = 1, A = -a;
  1698. else
  1699. A = a;
  1700. if (times < 0)
  1701. negative = !negative, T = -times;
  1702. else
  1703. T = times;
  1704. if (divisor < 0)
  1705. negative = !negative, D = -divisor;
  1706. else
  1707. D = divisor;
  1708. /* Following can't overflow because the arguments only
  1709. * have 31 bits each, however the result may be 32 bits.
  1710. */
  1711. s16 = (A >> 16) * (T & 0xffff) +
  1712. (A & 0xffff) * (T >> 16);
  1713. /* Can't overflow because the a*times bit is only 30
  1714. * bits at most.
  1715. */
  1716. s32 = (A >> 16) * (T >> 16) + (s16 >> 16);
  1717. s00 = (A & 0xffff) * (T & 0xffff);
  1718. s16 = (s16 & 0xffff) << 16;
  1719. s00 += s16;
  1720. if (s00 < s16)
  1721. ++s32; /* carry */
  1722. if (s32 < D) /* else overflow */
  1723. {
  1724. /* s32.s00 is now the 64-bit product, do a standard
  1725. * division, we know that s32 < D, so the maximum
  1726. * required shift is 31.
  1727. */
  1728. int bitshift = 32;
  1729. png_fixed_point result = 0; /* NOTE: signed */
  1730. while (--bitshift >= 0)
  1731. {
  1732. png_uint_32 d32, d00;
  1733. if (bitshift > 0)
  1734. d32 = D >> (32-bitshift), d00 = D << bitshift;
  1735. else
  1736. d32 = 0, d00 = D;
  1737. if (s32 > d32)
  1738. {
  1739. if (s00 < d00) --s32; /* carry */
  1740. s32 -= d32, s00 -= d00, result += 1<<bitshift;
  1741. }
  1742. else
  1743. if (s32 == d32 && s00 >= d00)
  1744. s32 = 0, s00 -= d00, result += 1<<bitshift;
  1745. }
  1746. /* Handle the rounding. */
  1747. if (s00 >= (D >> 1))
  1748. ++result;
  1749. if (negative != 0)
  1750. result = -result;
  1751. /* Check for overflow. */
  1752. if ((negative && result <= 0) || (!negative && result >= 0))
  1753. {
  1754. *res = result;
  1755. return 1;
  1756. }
  1757. }
  1758. #endif
  1759. }
  1760. }
  1761. return 0;
  1762. }
  1763. #endif /* READ_GAMMA || INCH_CONVERSIONS */
  1764. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_INCH_CONVERSIONS_SUPPORTED)
  1765. /* The following is for when the caller doesn't much care about the
  1766. * result.
  1767. */
  1768. png_fixed_point
  1769. png_muldiv_warn(png_structp png_ptr, png_fixed_point a, png_int_32 times,
  1770. png_int_32 divisor)
  1771. {
  1772. png_fixed_point result;
  1773. if (png_muldiv(&result, a, times, divisor))
  1774. return result;
  1775. png_warning(png_ptr, "fixed point overflow ignored");
  1776. return 0;
  1777. }
  1778. #endif
  1779. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_cHRM_SUPPORTED)
  1780. /* more fixed point functions for gamma and cHRM (xy/XYZ) suport. */
  1781. /* Calculate a reciprocal, return 0 on div-by-zero or overflow. */
  1782. png_fixed_point
  1783. png_reciprocal(png_fixed_point a)
  1784. {
  1785. if (a != 0)
  1786. {
  1787. #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  1788. double r = floor(1E10/a+.5);
  1789. if (r <= 2147483647. && r >= -2147483648.)
  1790. return (png_fixed_point)r;
  1791. #else
  1792. png_fixed_point res;
  1793. if (png_muldiv(&res, 100000, 100000, a))
  1794. return res;
  1795. #endif
  1796. }
  1797. return 0; /* error/overflow */
  1798. }
  1799. #ifdef PNG_READ_GAMMA_SUPPORTED
  1800. /* A local convenience routine. */
  1801. static png_fixed_point
  1802. png_product2(png_fixed_point a, png_fixed_point b)
  1803. {
  1804. /* The required result is 1/a * 1/b; the following preserves accuracy. */
  1805. #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  1806. double r = a * 1E-5;
  1807. r *= b;
  1808. r = floor(r+.5);
  1809. if (r <= 2147483647. && r >= -2147483648.)
  1810. return (png_fixed_point)r;
  1811. #else
  1812. png_fixed_point res;
  1813. if (png_muldiv(&res, a, b, 100000))
  1814. return res;
  1815. #endif
  1816. return 0; /* overflow */
  1817. }
  1818. #endif /* READ_GAMMA */
  1819. /* The inverse of the above. */
  1820. png_fixed_point
  1821. png_reciprocal2(png_fixed_point a, png_fixed_point b)
  1822. {
  1823. /* The required result is 1/a * 1/b; the following preserves accuracy. */
  1824. #ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  1825. if (a != 0 && b != 0)
  1826. {
  1827. double r = 1E15/a;
  1828. r /= b;
  1829. r = floor(r+.5);
  1830. if (r <= 2147483647. && r >= -2147483648.)
  1831. return (png_fixed_point)r;
  1832. }
  1833. #else
  1834. /* This may overflow because the range of png_fixed_point isn't
  1835. * symmetric, but this API is only used for the product of file and
  1836. * screen gamma so it doesn't matter that the smallest number it can
  1837. * produce is 1/21474, not 1/100000
  1838. */
  1839. png_fixed_point res = png_product2(a, b);
  1840. if (res != 0)
  1841. return png_reciprocal(res);
  1842. #endif
  1843. return 0; /* overflow */
  1844. }
  1845. #endif /* READ_GAMMA || cHRM */
  1846. #ifdef PNG_CHECK_cHRM_SUPPORTED
  1847. /* Added at libpng version 1.2.34 (Dec 8, 2008) and 1.4.0 (Jan 2,
  1848. * 2010: moved from pngset.c) */
  1849. /*
  1850. * Multiply two 32-bit numbers, V1 and V2, using 32-bit
  1851. * arithmetic, to produce a 64-bit result in the HI/LO words.
  1852. *
  1853. * A B
  1854. * x C D
  1855. * ------
  1856. * AD || BD
  1857. * AC || CB || 0
  1858. *
  1859. * where A and B are the high and low 16-bit words of V1,
  1860. * C and D are the 16-bit words of V2, AD is the product of
  1861. * A and D, and X || Y is (X << 16) + Y.
  1862. */
  1863. void /* PRIVATE */
  1864. png_64bit_product (long v1, long v2, unsigned long *hi_product,
  1865. unsigned long *lo_product)
  1866. {
  1867. int a, b, c, d;
  1868. long lo, hi, x, y;
  1869. a = (v1 >> 16) & 0xffff;
  1870. b = v1 & 0xffff;
  1871. c = (v2 >> 16) & 0xffff;
  1872. d = v2 & 0xffff;
  1873. lo = b * d; /* BD */
  1874. x = a * d + c * b; /* AD + CB */
  1875. y = ((lo >> 16) & 0xffff) + x;
  1876. lo = (lo & 0xffff) | ((y & 0xffff) << 16);
  1877. hi = (y >> 16) & 0xffff;
  1878. hi += a * c; /* AC */
  1879. *hi_product = (unsigned long)hi;
  1880. *lo_product = (unsigned long)lo;
  1881. }
  1882. #endif /* CHECK_cHRM */
  1883. #ifdef PNG_READ_GAMMA_SUPPORTED /* gamma table code */
  1884. #ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED
  1885. /* Fixed point gamma.
  1886. *
  1887. * To calculate gamma this code implements fast log() and exp() calls using only
  1888. * fixed point arithmetic. This code has sufficient precision for either 8-bit
  1889. * or 16-bit sample values.
  1890. *
  1891. * The tables used here were calculated using simple 'bc' programs, but C double
  1892. * precision floating point arithmetic would work fine. The programs are given
  1893. * at the head of each table.
  1894. *
  1895. * 8-bit log table
  1896. * This is a table of -log(value/255)/log(2) for 'value' in the range 128 to
  1897. * 255, so it's the base 2 logarithm of a normalized 8-bit floating point
  1898. * mantissa. The numbers are 32-bit fractions.
  1899. */
  1900. static png_uint_32
  1901. png_8bit_l2[128] =
  1902. {
  1903. # ifdef PNG_DO_BC
  1904. for (i=128;i<256;++i) { .5 - l(i/255)/l(2)*65536*65536; }
  1905. # else
  1906. 4270715492U, 4222494797U, 4174646467U, 4127164793U, 4080044201U, 4033279239U,
  1907. 3986864580U, 3940795015U, 3895065449U, 3849670902U, 3804606499U, 3759867474U,
  1908. 3715449162U, 3671346997U, 3627556511U, 3584073329U, 3540893168U, 3498011834U,
  1909. 3455425220U, 3413129301U, 3371120137U, 3329393864U, 3287946700U, 3246774933U,
  1910. 3205874930U, 3165243125U, 3124876025U, 3084770202U, 3044922296U, 3005329011U,
  1911. 2965987113U, 2926893432U, 2888044853U, 2849438323U, 2811070844U, 2772939474U,
  1912. 2735041326U, 2697373562U, 2659933400U, 2622718104U, 2585724991U, 2548951424U,
  1913. 2512394810U, 2476052606U, 2439922311U, 2404001468U, 2368287663U, 2332778523U,
  1914. 2297471715U, 2262364947U, 2227455964U, 2192742551U, 2158222529U, 2123893754U,
  1915. 2089754119U, 2055801552U, 2022034013U, 1988449497U, 1955046031U, 1921821672U,
  1916. 1888774511U, 1855902668U, 1823204291U, 1790677560U, 1758320682U, 1726131893U,
  1917. 1694109454U, 1662251657U, 1630556815U, 1599023271U, 1567649391U, 1536433567U,
  1918. 1505374214U, 1474469770U, 1443718700U, 1413119487U, 1382670639U, 1352370686U,
  1919. 1322218179U, 1292211689U, 1262349810U, 1232631153U, 1203054352U, 1173618059U,
  1920. 1144320946U, 1115161701U, 1086139034U, 1057251672U, 1028498358U, 999877854U,
  1921. 971388940U, 943030410U, 914801076U, 886699767U, 858725327U, 830876614U,
  1922. 803152505U, 775551890U, 748073672U, 720716771U, 693480120U, 666362667U,
  1923. 639363374U, 612481215U, 585715177U, 559064263U, 532527486U, 506103872U,
  1924. 479792461U, 453592303U, 427502463U, 401522014U, 375650043U, 349885648U,
  1925. 324227938U, 298676034U, 273229066U, 247886176U, 222646516U, 197509248U,
  1926. 172473545U, 147538590U, 122703574U, 97967701U, 73330182U, 48790236U,
  1927. 24347096U, 0U
  1928. # endif
  1929. #if 0
  1930. /* The following are the values for 16-bit tables - these work fine for the
  1931. * 8-bit conversions but produce very slightly larger errors in the 16-bit
  1932. * log (about 1.2 as opposed to 0.7 absolute error in the final value). To
  1933. * use these all the shifts below must be adjusted appropriately.
  1934. */
  1935. 65166, 64430, 63700, 62976, 62257, 61543, 60835, 60132, 59434, 58741, 58054,
  1936. 57371, 56693, 56020, 55352, 54689, 54030, 53375, 52726, 52080, 51439, 50803,
  1937. 50170, 49542, 48918, 48298, 47682, 47070, 46462, 45858, 45257, 44661, 44068,
  1938. 43479, 42894, 42312, 41733, 41159, 40587, 40020, 39455, 38894, 38336, 37782,
  1939. 37230, 36682, 36137, 35595, 35057, 34521, 33988, 33459, 32932, 32408, 31887,
  1940. 31369, 30854, 30341, 29832, 29325, 28820, 28319, 27820, 27324, 26830, 26339,
  1941. 25850, 25364, 24880, 24399, 23920, 23444, 22970, 22499, 22029, 21562, 21098,
  1942. 20636, 20175, 19718, 19262, 18808, 18357, 17908, 17461, 17016, 16573, 16132,
  1943. 15694, 15257, 14822, 14390, 13959, 13530, 13103, 12678, 12255, 11834, 11415,
  1944. 10997, 10582, 10168, 9756, 9346, 8937, 8531, 8126, 7723, 7321, 6921, 6523,
  1945. 6127, 5732, 5339, 4947, 4557, 4169, 3782, 3397, 3014, 2632, 2251, 1872, 1495,
  1946. 1119, 744, 372
  1947. #endif
  1948. };
  1949. PNG_STATIC png_int_32
  1950. png_log8bit(unsigned int x)
  1951. {
  1952. unsigned int lg2 = 0;
  1953. /* Each time 'x' is multiplied by 2, 1 must be subtracted off the final log,
  1954. * because the log is actually negate that means adding 1. The final
  1955. * returned value thus has the range 0 (for 255 input) to 7.994 (for 1
  1956. * input), return 7.99998 for the overflow (log 0) case - so the result is
  1957. * always at most 19 bits.
  1958. */
  1959. if ((x &= 0xff) == 0)
  1960. return 0xffffffff;
  1961. if ((x & 0xf0) == 0)
  1962. lg2 = 4, x <<= 4;
  1963. if ((x & 0xc0) == 0)
  1964. lg2 += 2, x <<= 2;
  1965. if ((x & 0x80) == 0)
  1966. lg2 += 1, x <<= 1;
  1967. /* result is at most 19 bits, so this cast is safe: */
  1968. return (png_int_32)((lg2 << 16) + ((png_8bit_l2[x-128]+32768)>>16));
  1969. }
  1970. /* The above gives exact (to 16 binary places) log2 values for 8-bit images,
  1971. * for 16-bit images we use the most significant 8 bits of the 16-bit value to
  1972. * get an approximation then multiply the approximation by a correction factor
  1973. * determined by the remaining up to 8 bits. This requires an additional step
  1974. * in the 16-bit case.
  1975. *
  1976. * We want log2(value/65535), we have log2(v'/255), where:
  1977. *
  1978. * value = v' * 256 + v''
  1979. * = v' * f
  1980. *
  1981. * So f is value/v', which is equal to (256+v''/v') since v' is in the range 128
  1982. * to 255 and v'' is in the range 0 to 255 f will be in the range 256 to less
  1983. * than 258. The final factor also needs to correct for the fact that our 8-bit
  1984. * value is scaled by 255, whereas the 16-bit values must be scaled by 65535.
  1985. *
  1986. * This gives a final formula using a calculated value 'x' which is value/v' and
  1987. * scaling by 65536 to match the above table:
  1988. *
  1989. * log2(x/257) * 65536
  1990. *
  1991. * Since these numbers are so close to '1' we can use simple linear
  1992. * interpolation between the two end values 256/257 (result -368.61) and 258/257
  1993. * (result 367.179). The values used below are scaled by a further 64 to give
  1994. * 16-bit precision in the interpolation:
  1995. *
  1996. * Start (256): -23591
  1997. * Zero (257): 0
  1998. * End (258): 23499
  1999. */
  2000. PNG_STATIC png_int_32
  2001. png_log16bit(png_uint_32 x)
  2002. {
  2003. unsigned int lg2 = 0;
  2004. /* As above, but now the input has 16 bits. */
  2005. if ((x &= 0xffff) == 0)
  2006. return 0xffffffff;
  2007. if ((x & 0xff00) == 0)
  2008. lg2 = 8, x <<= 8;
  2009. if ((x & 0xf000) == 0)
  2010. lg2 += 4, x <<= 4;
  2011. if ((x & 0xc000) == 0)
  2012. lg2 += 2, x <<= 2;
  2013. if ((x & 0x8000) == 0)
  2014. lg2 += 1, x <<= 1;
  2015. /* Calculate the base logarithm from the top 8 bits as a 28-bit fractional
  2016. * value.
  2017. */
  2018. lg2 <<= 28;
  2019. lg2 += (png_8bit_l2[(x>>8)-128]+8) >> 4;
  2020. /* Now we need to interpolate the factor, this requires a division by the top
  2021. * 8 bits. Do this with maximum precision.
  2022. */
  2023. x = ((x << 16) + (x >> 9)) / (x >> 8);
  2024. /* Since we divided by the top 8 bits of 'x' there will be a '1' at 1<<24,
  2025. * the value at 1<<16 (ignoring this) will be 0 or 1; this gives us exactly
  2026. * 16 bits to interpolate to get the low bits of the result. Round the
  2027. * answer. Note that the end point values are scaled by 64 to retain overall
  2028. * precision and that 'lg2' is current scaled by an extra 12 bits, so adjust
  2029. * the overall scaling by 6-12. Round at every step.
  2030. */
  2031. x -= 1U << 24;
  2032. if (x <= 65536U) /* <= '257' */
  2033. lg2 += ((23591U * (65536U-x)) + (1U << (16+6-12-1))) >> (16+6-12);
  2034. else
  2035. lg2 -= ((23499U * (x-65536U)) + (1U << (16+6-12-1))) >> (16+6-12);
  2036. /* Safe, because the result can't have more than 20 bits: */
  2037. return (png_int_32)((lg2 + 2048) >> 12);
  2038. }
  2039. /* The 'exp()' case must invert the above, taking a 20-bit fixed point
  2040. * logarithmic value and returning a 16 or 8-bit number as appropriate. In
  2041. * each case only the low 16 bits are relevant - the fraction - since the
  2042. * integer bits (the top 4) simply determine a shift.
  2043. *
  2044. * The worst case is the 16-bit distinction between 65535 and 65534, this
  2045. * requires perhaps spurious accuracy in the decoding of the logarithm to
  2046. * distinguish log2(65535/65534.5) - 10^-5 or 17 bits. There is little chance
  2047. * of getting this accuracy in practice.
  2048. *
  2049. * To deal with this the following exp() function works out the exponent of the
  2050. * frational part of the logarithm by using an accurate 32-bit value from the
  2051. * top four fractional bits then multiplying in the remaining bits.
  2052. */
  2053. static png_uint_32
  2054. png_32bit_exp[16] =
  2055. {
  2056. # ifdef PNG_DO_BC
  2057. for (i=0;i<16;++i) { .5 + e(-i/16*l(2))*2^32; }
  2058. # else
  2059. /* NOTE: the first entry is deliberately set to the maximum 32-bit value. */
  2060. 4294967295U, 4112874773U, 3938502376U, 3771522796U, 3611622603U, 3458501653U,
  2061. 3311872529U, 3171459999U, 3037000500U, 2908241642U, 2784941738U, 2666869345U,
  2062. 2553802834U, 2445529972U, 2341847524U, 2242560872U
  2063. # endif
  2064. };
  2065. /* Adjustment table; provided to explain the numbers in the code below. */
  2066. #ifdef PNG_DO_BC
  2067. for (i=11;i>=0;--i){ print i, " ", (1 - e(-(2^i)/65536*l(2))) * 2^(32-i), "\n"}
  2068. 11 44937.64284865548751208448
  2069. 10 45180.98734845585101160448
  2070. 9 45303.31936980687359311872
  2071. 8 45364.65110595323018870784
  2072. 7 45395.35850361789624614912
  2073. 6 45410.72259715102037508096
  2074. 5 45418.40724413220722311168
  2075. 4 45422.25021786898173001728
  2076. 3 45424.17186732298419044352
  2077. 2 45425.13273269940811464704
  2078. 1 45425.61317555035558641664
  2079. 0 45425.85339951654943850496
  2080. #endif
  2081. PNG_STATIC png_uint_32
  2082. png_exp(png_fixed_point x)
  2083. {
  2084. if (x > 0 && x <= 0xfffff) /* Else overflow or zero (underflow) */
  2085. {
  2086. /* Obtain a 4-bit approximation */
  2087. png_uint_32 e = png_32bit_exp[(x >> 12) & 0xf];
  2088. /* Incorporate the low 12 bits - these decrease the returned value by
  2089. * multiplying by a number less than 1 if the bit is set. The multiplier
  2090. * is determined by the above table and the shift. Notice that the values
  2091. * converge on 45426 and this is used to allow linear interpolation of the
  2092. * low bits.
  2093. */
  2094. if (x & 0x800)
  2095. e -= (((e >> 16) * 44938U) + 16U) >> 5;
  2096. if (x & 0x400)
  2097. e -= (((e >> 16) * 45181U) + 32U) >> 6;
  2098. if (x & 0x200)
  2099. e -= (((e >> 16) * 45303U) + 64U) >> 7;
  2100. if (x & 0x100)
  2101. e -= (((e >> 16) * 45365U) + 128U) >> 8;
  2102. if (x & 0x080)
  2103. e -= (((e >> 16) * 45395U) + 256U) >> 9;
  2104. if (x & 0x040)
  2105. e -= (((e >> 16) * 45410U) + 512U) >> 10;
  2106. /* And handle the low 6 bits in a single block. */
  2107. e -= (((e >> 16) * 355U * (x & 0x3fU)) + 256U) >> 9;
  2108. /* Handle the upper bits of x. */
  2109. e >>= x >> 16;
  2110. return e;
  2111. }
  2112. /* Check for overflow */
  2113. if (x <= 0)
  2114. return png_32bit_exp[0];
  2115. /* Else underflow */
  2116. return 0;
  2117. }
  2118. PNG_STATIC png_byte
  2119. png_exp8bit(png_fixed_point lg2)
  2120. {
  2121. /* Get a 32-bit value: */
  2122. png_uint_32 x = png_exp(lg2);
  2123. /* Convert the 32-bit value to 0..255 by multiplying by 256-1, note that the
  2124. * second, rounding, step can't overflow because of the first, subtraction,
  2125. * step.
  2126. */
  2127. x -= x >> 8;
  2128. return (png_byte)((x + 0x7fffffU) >> 24);
  2129. }
  2130. PNG_STATIC png_uint_16
  2131. png_exp16bit(png_fixed_point lg2)
  2132. {
  2133. /* Get a 32-bit value: */
  2134. png_uint_32 x = png_exp(lg2);
  2135. /* Convert the 32-bit value to 0..65535 by multiplying by 65536-1: */
  2136. x -= x >> 16;
  2137. return (png_uint_16)((x + 32767U) >> 16);
  2138. }
  2139. #endif /* FLOATING_ARITHMETIC */
  2140. png_byte
  2141. png_gamma_8bit_correct(unsigned int value, png_fixed_point gamma_val)
  2142. {
  2143. if (value > 0 && value < 255)
  2144. {
  2145. # ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  2146. double r = floor(255*pow(value/255.,gamma_val*.00001)+.5);
  2147. return (png_byte)r;
  2148. # else
  2149. png_int_32 lg2 = png_log8bit(value);
  2150. png_fixed_point res;
  2151. if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1))
  2152. return png_exp8bit(res);
  2153. /* Overflow. */
  2154. value = 0;
  2155. # endif
  2156. }
  2157. return (png_byte)value;
  2158. }
  2159. png_uint_16
  2160. png_gamma_16bit_correct(unsigned int value, png_fixed_point gamma_val)
  2161. {
  2162. if (value > 0 && value < 65535)
  2163. {
  2164. # ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  2165. double r = floor(65535*pow(value/65535.,gamma_val*.00001)+.5);
  2166. return (png_uint_16)r;
  2167. # else
  2168. png_int_32 lg2 = png_log16bit(value);
  2169. png_fixed_point res;
  2170. if (png_muldiv(&res, gamma_val, lg2, PNG_FP_1))
  2171. return png_exp16bit(res);
  2172. /* Overflow. */
  2173. value = 0;
  2174. # endif
  2175. }
  2176. return (png_uint_16)value;
  2177. }
  2178. /* This does the right thing based on the bit_depth field of the
  2179. * png_struct, interpreting values as 8-bit or 16-bit. While the result
  2180. * is nominally a 16-bit value if bit depth is 8 then the result is
  2181. * 8-bit (as are the arguments.)
  2182. */
  2183. png_uint_16 /* PRIVATE */
  2184. png_gamma_correct(png_structp png_ptr, unsigned int value,
  2185. png_fixed_point gamma_val)
  2186. {
  2187. if (png_ptr->bit_depth == 8)
  2188. return png_gamma_8bit_correct(value, gamma_val);
  2189. else
  2190. return png_gamma_16bit_correct(value, gamma_val);
  2191. }
  2192. /* This is the shared test on whether a gamma value is 'significant' - whether
  2193. * it is worth doing gamma correction.
  2194. */
  2195. int /* PRIVATE */
  2196. png_gamma_significant(png_fixed_point gamma_val)
  2197. {
  2198. return gamma_val < PNG_FP_1 - PNG_GAMMA_THRESHOLD_FIXED ||
  2199. gamma_val > PNG_FP_1 + PNG_GAMMA_THRESHOLD_FIXED;
  2200. }
  2201. #ifdef PNG_16BIT_SUPPORTED
  2202. /* Internal function to build a single 16-bit table - the table consists of
  2203. * 'num' 256-entry subtables, where 'num' is determined by 'shift' - the amount
  2204. * to shift the input values right (or 16-number_of_signifiant_bits).
  2205. *
  2206. * The caller is responsible for ensuring that the table gets cleaned up on
  2207. * png_error (i.e. if one of the mallocs below fails) - i.e. the *table argument
  2208. * should be somewhere that will be cleaned.
  2209. */
  2210. static void
  2211. png_build_16bit_table(png_structp png_ptr, png_uint_16pp *ptable,
  2212. PNG_CONST unsigned int shift, PNG_CONST png_fixed_point gamma_val)
  2213. {
  2214. /* Various values derived from 'shift': */
  2215. PNG_CONST unsigned int num = 1U << (8U - shift);
  2216. PNG_CONST unsigned int max = (1U << (16U - shift))-1U;
  2217. PNG_CONST unsigned int max_by_2 = 1U << (15U-shift);
  2218. unsigned int i;
  2219. png_uint_16pp table = *ptable =
  2220. (png_uint_16pp)png_calloc(png_ptr, num * png_sizeof(png_uint_16p));
  2221. for (i = 0; i < num; i++)
  2222. {
  2223. png_uint_16p sub_table = table[i] =
  2224. (png_uint_16p)png_malloc(png_ptr, 256 * png_sizeof(png_uint_16));
  2225. /* The 'threshold' test is repeated here because it can arise for one of
  2226. * the 16-bit tables even if the others don't hit it.
  2227. */
  2228. if (png_gamma_significant(gamma_val))
  2229. {
  2230. /* The old code would overflow at the end and this would cause the
  2231. * 'pow' function to return a result >1, resulting in an
  2232. * arithmetic error. This code follows the spec exactly; ig is
  2233. * the recovered input sample, it always has 8-16 bits.
  2234. *
  2235. * We want input * 65535/max, rounded, the arithmetic fits in 32
  2236. * bits (unsigned) so long as max <= 32767.
  2237. */
  2238. unsigned int j;
  2239. for (j = 0; j < 256; j++)
  2240. {
  2241. png_uint_32 ig = (j << (8-shift)) + i;
  2242. # ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
  2243. /* Inline the 'max' scaling operation: */
  2244. double d = floor(65535*pow(ig/(double)max, gamma_val*.00001)+.5);
  2245. sub_table[j] = (png_uint_16)d;
  2246. # else
  2247. if (shift != 0)
  2248. ig = (ig * 65535U + max_by_2)/max;
  2249. sub_table[j] = png_gamma_16bit_correct(ig, gamma_val);
  2250. # endif
  2251. }
  2252. }
  2253. else
  2254. {
  2255. /* We must still build a table, but do it the fast way. */
  2256. unsigned int j;
  2257. for (j = 0; j < 256; j++)
  2258. {
  2259. png_uint_32 ig = (j << (8-shift)) + i;
  2260. if (shift != 0)
  2261. ig = (ig * 65535U + max_by_2)/max;
  2262. sub_table[j] = (png_uint_16)ig;
  2263. }
  2264. }
  2265. }
  2266. }
  2267. #endif
  2268. /* NOTE: this function expects the *inverse* of the overall gamma transformation
  2269. * required.
  2270. */
  2271. static void
  2272. png_build_16to8_table(png_structp png_ptr, png_uint_16pp *ptable,
  2273. PNG_CONST unsigned int shift, PNG_CONST png_fixed_point gamma_val)
  2274. {
  2275. PNG_CONST unsigned int num = 1U << (8U - shift);
  2276. PNG_CONST unsigned int max = (1U << (16U - shift))-1U;
  2277. unsigned int i;
  2278. png_uint_32 last;
  2279. png_uint_16pp table = *ptable =
  2280. (png_uint_16pp)png_calloc(png_ptr, num * png_sizeof(png_uint_16p));
  2281. /* 'num' is the number of tables and also the number of low bits of the
  2282. * input 16-bit value used to select a table. Each table is itself indexed
  2283. * by the high 8 bits of the value.
  2284. */
  2285. for (i = 0; i < num; i++)
  2286. table[i] = (png_uint_16p)png_malloc(png_ptr,
  2287. 256 * png_sizeof(png_uint_16));
  2288. /* 'gamma_val' is set to the reciprocal of the value calculated above, so
  2289. * pow(out,g) is an *input* value. 'last' is the last input value set.
  2290. *
  2291. * In the loop 'i' is used to find output values. Since the output is
  2292. * 8-bit there are only 256 possible values. The tables are set up to
  2293. * select the closest possible output value for each input by finding
  2294. * the input value at the boundary between each pair of output values
  2295. * and filling the table up to that boundary with the lower output
  2296. * value.
  2297. *
  2298. * The boundary values are 0.5,1.5..253.5,254.5. Since these are 9-bit
  2299. * values the code below uses a 16-bit value in i; the values start at
  2300. * 128.5 (for 0.5) and step by 257, for a total of 254 values (the last
  2301. * entries are filled with 255). Start i at 128 and fill all 'last'
  2302. * table entries <= 'max'
  2303. */
  2304. last = 0;
  2305. for (i = 0; i < 255; ++i) /* 8-bit output value */
  2306. {
  2307. /* Find the corresponding maximum input value */
  2308. png_uint_16 out = (png_uint_16)(i * 257U); /* 16-bit output value */
  2309. /* Find the boundary value in 16 bits: */
  2310. png_uint_32 bound = png_gamma_16bit_correct(out+128U, gamma_val);
  2311. /* Adjust (round) to (16-shift) bits: */
  2312. bound = (bound * max + 32768U)/65535U + 1U;
  2313. while (last < bound)
  2314. {
  2315. table[last & (0xffU >> shift)][last >> (8U - shift)] = out;
  2316. last++;
  2317. }
  2318. }
  2319. /* And fill in the final entries. */
  2320. while (last < (num << 8))
  2321. {
  2322. table[last & (0xff >> shift)][last >> (8U - shift)] = 65535U;
  2323. last++;
  2324. }
  2325. }
  2326. /* Build a single 8-bit table: same as the 16-bit case but much simpler (and
  2327. * typically much faster). Note that libpng currently does no sBIT processing
  2328. * (apparently contrary to the spec) so a 256-entry table is always generated.
  2329. */
  2330. static void
  2331. png_build_8bit_table(png_structp png_ptr, png_bytepp ptable,
  2332. PNG_CONST png_fixed_point gamma_val)
  2333. {
  2334. unsigned int i;
  2335. png_bytep table = *ptable = (png_bytep)png_malloc(png_ptr, 256);
  2336. if (png_gamma_significant(gamma_val)) for (i=0; i<256; i++)
  2337. table[i] = png_gamma_8bit_correct(i, gamma_val);
  2338. else for (i=0; i<256; ++i)
  2339. table[i] = (png_byte)i;
  2340. }
  2341. /* Used from png_read_destroy and below to release the memory used by the gamma
  2342. * tables.
  2343. */
  2344. void /* PRIVATE */
  2345. png_destroy_gamma_table(png_structp png_ptr)
  2346. {
  2347. png_free(png_ptr, png_ptr->gamma_table);
  2348. png_ptr->gamma_table = NULL;
  2349. if (png_ptr->gamma_16_table != NULL)
  2350. {
  2351. int i;
  2352. int istop = (1 << (8 - png_ptr->gamma_shift));
  2353. for (i = 0; i < istop; i++)
  2354. {
  2355. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  2356. }
  2357. png_free(png_ptr, png_ptr->gamma_16_table);
  2358. png_ptr->gamma_16_table = NULL;
  2359. }
  2360. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  2361. defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \
  2362. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  2363. png_free(png_ptr, png_ptr->gamma_from_1);
  2364. png_ptr->gamma_from_1 = NULL;
  2365. png_free(png_ptr, png_ptr->gamma_to_1);
  2366. png_ptr->gamma_to_1 = NULL;
  2367. if (png_ptr->gamma_16_from_1 != NULL)
  2368. {
  2369. int i;
  2370. int istop = (1 << (8 - png_ptr->gamma_shift));
  2371. for (i = 0; i < istop; i++)
  2372. {
  2373. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  2374. }
  2375. png_free(png_ptr, png_ptr->gamma_16_from_1);
  2376. png_ptr->gamma_16_from_1 = NULL;
  2377. }
  2378. if (png_ptr->gamma_16_to_1 != NULL)
  2379. {
  2380. int i;
  2381. int istop = (1 << (8 - png_ptr->gamma_shift));
  2382. for (i = 0; i < istop; i++)
  2383. {
  2384. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  2385. }
  2386. png_free(png_ptr, png_ptr->gamma_16_to_1);
  2387. png_ptr->gamma_16_to_1 = NULL;
  2388. }
  2389. #endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */
  2390. }
  2391. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  2392. * tables, we don't make a full table if we are reducing to 8-bit in
  2393. * the future. Note also how the gamma_16 tables are segmented so that
  2394. * we don't need to allocate > 64K chunks for a full 16-bit table.
  2395. */
  2396. void /* PRIVATE */
  2397. png_build_gamma_table(png_structp png_ptr, int bit_depth)
  2398. {
  2399. png_debug(1, "in png_build_gamma_table");
  2400. /* Remove any existing table; this copes with multiple calls to
  2401. * png_read_update_info. The warning is because building the gamma tables
  2402. * multiple times is a performance hit - it's harmless but the ability to call
  2403. * png_read_update_info() multiple times is new in 1.5.6 so it seems sensible
  2404. * to warn if the app introduces such a hit.
  2405. */
  2406. if (png_ptr->gamma_table != NULL || png_ptr->gamma_16_table != NULL)
  2407. {
  2408. png_warning(png_ptr, "gamma table being rebuilt");
  2409. png_destroy_gamma_table(png_ptr);
  2410. }
  2411. if (bit_depth <= 8)
  2412. {
  2413. png_build_8bit_table(png_ptr, &png_ptr->gamma_table,
  2414. png_ptr->screen_gamma > 0 ? png_reciprocal2(png_ptr->gamma,
  2415. png_ptr->screen_gamma) : PNG_FP_1);
  2416. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  2417. defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \
  2418. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  2419. if (png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY))
  2420. {
  2421. png_build_8bit_table(png_ptr, &png_ptr->gamma_to_1,
  2422. png_reciprocal(png_ptr->gamma));
  2423. png_build_8bit_table(png_ptr, &png_ptr->gamma_from_1,
  2424. png_ptr->screen_gamma > 0 ? png_reciprocal(png_ptr->screen_gamma) :
  2425. png_ptr->gamma/* Probably doing rgb_to_gray */);
  2426. }
  2427. #endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */
  2428. }
  2429. else
  2430. {
  2431. png_byte shift, sig_bit;
  2432. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  2433. {
  2434. sig_bit = png_ptr->sig_bit.red;
  2435. if (png_ptr->sig_bit.green > sig_bit)
  2436. sig_bit = png_ptr->sig_bit.green;
  2437. if (png_ptr->sig_bit.blue > sig_bit)
  2438. sig_bit = png_ptr->sig_bit.blue;
  2439. }
  2440. else
  2441. sig_bit = png_ptr->sig_bit.gray;
  2442. /* 16-bit gamma code uses this equation:
  2443. *
  2444. * ov = table[(iv & 0xff) >> gamma_shift][iv >> 8]
  2445. *
  2446. * Where 'iv' is the input color value and 'ov' is the output value -
  2447. * pow(iv, gamma).
  2448. *
  2449. * Thus the gamma table consists of up to 256 256-entry tables. The table
  2450. * is selected by the (8-gamma_shift) most significant of the low 8 bits of
  2451. * the color value then indexed by the upper 8 bits:
  2452. *
  2453. * table[low bits][high 8 bits]
  2454. *
  2455. * So the table 'n' corresponds to all those 'iv' of:
  2456. *
  2457. * <all high 8-bit values><n << gamma_shift>..<(n+1 << gamma_shift)-1>
  2458. *
  2459. */
  2460. if (sig_bit > 0 && sig_bit < 16U)
  2461. shift = (png_byte)(16U - sig_bit); /* shift == insignificant bits */
  2462. else
  2463. shift = 0; /* keep all 16 bits */
  2464. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8))
  2465. {
  2466. /* PNG_MAX_GAMMA_8 is the number of bits to keep - effectively
  2467. * the significant bits in the *input* when the output will
  2468. * eventually be 8 bits. By default it is 11.
  2469. */
  2470. if (shift < (16U - PNG_MAX_GAMMA_8))
  2471. shift = (16U - PNG_MAX_GAMMA_8);
  2472. }
  2473. if (shift > 8U)
  2474. shift = 8U; /* Guarantees at least one table! */
  2475. png_ptr->gamma_shift = shift;
  2476. #ifdef PNG_16BIT_SUPPORTED
  2477. /* NOTE: prior to 1.5.4 this test used to include PNG_BACKGROUND (now
  2478. * PNG_COMPOSE). This effectively smashed the background calculation for
  2479. * 16-bit output because the 8-bit table assumes the result will be reduced
  2480. * to 8 bits.
  2481. */
  2482. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_SCALE_16_TO_8))
  2483. #endif
  2484. png_build_16to8_table(png_ptr, &png_ptr->gamma_16_table, shift,
  2485. png_ptr->screen_gamma > 0 ? png_product2(png_ptr->gamma,
  2486. png_ptr->screen_gamma) : PNG_FP_1);
  2487. #ifdef PNG_16BIT_SUPPORTED
  2488. else
  2489. png_build_16bit_table(png_ptr, &png_ptr->gamma_16_table, shift,
  2490. png_ptr->screen_gamma > 0 ? png_reciprocal2(png_ptr->gamma,
  2491. png_ptr->screen_gamma) : PNG_FP_1);
  2492. #endif
  2493. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  2494. defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \
  2495. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  2496. if (png_ptr->transformations & (PNG_COMPOSE | PNG_RGB_TO_GRAY))
  2497. {
  2498. png_build_16bit_table(png_ptr, &png_ptr->gamma_16_to_1, shift,
  2499. png_reciprocal(png_ptr->gamma));
  2500. /* Notice that the '16 from 1' table should be full precision, however
  2501. * the lookup on this table still uses gamma_shift, so it can't be.
  2502. * TODO: fix this.
  2503. */
  2504. png_build_16bit_table(png_ptr, &png_ptr->gamma_16_from_1, shift,
  2505. png_ptr->screen_gamma > 0 ? png_reciprocal(png_ptr->screen_gamma) :
  2506. png_ptr->gamma/* Probably doing rgb_to_gray */);
  2507. }
  2508. #endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */
  2509. }
  2510. }
  2511. #endif /* READ_GAMMA */
  2512. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  2513. /* HARDWARE OPTION SUPPORT */
  2514. #ifdef PNG_SET_OPTION_SUPPORTED
  2515. int PNGAPI
  2516. png_set_option(png_structp png_ptr, int option, int onoff)
  2517. {
  2518. if (png_ptr != NULL && option >= 0 && option < PNG_OPTION_NEXT &&
  2519. (option & 1) == 0)
  2520. {
  2521. int mask = 3 << option;
  2522. int setting = (2 + (onoff != 0)) << option;
  2523. int current = png_ptr->options;
  2524. png_ptr->options = (png_byte)((current & ~mask) | setting);
  2525. return (current & mask) >> option;
  2526. }
  2527. return PNG_OPTION_INVALID;
  2528. }
  2529. #endif