png.c 95 KB

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