png.c 91 KB

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