png.c 91 KB

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