PageRenderTime 68ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/src/Image_LibPNG154/png.c

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