Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2362 lines
71 KiB

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