/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

Large files are truncated click here to view the full file

  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/…