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.

2948 lines
82 KiB

  1. /* pngwutil.c - utilities to write a PNG file
  2. *
  3. * Last changed in libpng 1.5.0 [January 6, 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. #ifdef PNG_WRITE_SUPPORTED
  14. #ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED
  15. /* Place a 32-bit number into a buffer in PNG byte order. We work
  16. * with unsigned numbers for convenience, although one supported
  17. * ancillary chunk uses signed (two's complement) numbers.
  18. */
  19. void PNGAPI
  20. png_save_uint_32(png_bytep buf, png_uint_32 i)
  21. {
  22. buf[0] = (png_byte)((i >> 24) & 0xff);
  23. buf[1] = (png_byte)((i >> 16) & 0xff);
  24. buf[2] = (png_byte)((i >> 8) & 0xff);
  25. buf[3] = (png_byte)(i & 0xff);
  26. }
  27. #ifdef PNG_SAVE_INT_32_SUPPORTED
  28. /* The png_save_int_32 function assumes integers are stored in two's
  29. * complement format. If this isn't the case, then this routine needs to
  30. * be modified to write data in two's complement format. Note that,
  31. * the following works correctly even if png_int_32 has more than 32 bits
  32. * (compare the more complex code required on read for sign extention.)
  33. */
  34. void PNGAPI
  35. png_save_int_32(png_bytep buf, png_int_32 i)
  36. {
  37. buf[0] = (png_byte)((i >> 24) & 0xff);
  38. buf[1] = (png_byte)((i >> 16) & 0xff);
  39. buf[2] = (png_byte)((i >> 8) & 0xff);
  40. buf[3] = (png_byte)(i & 0xff);
  41. }
  42. #endif
  43. /* Place a 16-bit number into a buffer in PNG byte order.
  44. * The parameter is declared unsigned int, not png_uint_16,
  45. * just to avoid potential problems on pre-ANSI C compilers.
  46. */
  47. void PNGAPI
  48. png_save_uint_16(png_bytep buf, unsigned int i)
  49. {
  50. buf[0] = (png_byte)((i >> 8) & 0xff);
  51. buf[1] = (png_byte)(i & 0xff);
  52. }
  53. #endif
  54. /* Simple function to write the signature. If we have already written
  55. * the magic bytes of the signature, or more likely, the PNG stream is
  56. * being embedded into another stream and doesn't need its own signature,
  57. * we should call png_set_sig_bytes() to tell libpng how many of the
  58. * bytes have already been written.
  59. */
  60. void PNGAPI
  61. png_write_sig(png_structp png_ptr)
  62. {
  63. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  64. #ifdef PNG_IO_STATE_SUPPORTED
  65. /* Inform the I/O callback that the signature is being written */
  66. png_ptr->io_state = PNG_IO_WRITING | PNG_IO_SIGNATURE;
  67. #endif
  68. /* Write the rest of the 8 byte signature */
  69. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  70. (png_size_t)(8 - png_ptr->sig_bytes));
  71. if (png_ptr->sig_bytes < 3)
  72. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  73. }
  74. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  75. * representing the chunk name. The array must be at least 4 bytes in
  76. * length, and does not need to be null terminated. To be safe, pass the
  77. * pre-defined chunk names here, and if you need a new one, define it
  78. * where the others are defined. The length is the length of the data.
  79. * All the data must be present. If that is not possible, use the
  80. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  81. * functions instead.
  82. */
  83. void PNGAPI
  84. png_write_chunk(png_structp png_ptr, png_const_bytep chunk_name,
  85. png_const_bytep data, png_size_t length)
  86. {
  87. if (png_ptr == NULL)
  88. return;
  89. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  90. png_write_chunk_data(png_ptr, data, (png_size_t)length);
  91. png_write_chunk_end(png_ptr);
  92. }
  93. /* Write the start of a PNG chunk. The type is the chunk type.
  94. * The total_length is the sum of the lengths of all the data you will be
  95. * passing in png_write_chunk_data().
  96. */
  97. void PNGAPI
  98. png_write_chunk_start(png_structp png_ptr, png_const_bytep chunk_name,
  99. png_uint_32 length)
  100. {
  101. png_byte buf[8];
  102. png_debug2(0, "Writing %s chunk, length = %lu", chunk_name,
  103. (unsigned long)length);
  104. if (png_ptr == NULL)
  105. return;
  106. #ifdef PNG_IO_STATE_SUPPORTED
  107. /* Inform the I/O callback that the chunk header is being written.
  108. * PNG_IO_CHUNK_HDR requires a single I/O call.
  109. */
  110. png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_HDR;
  111. #endif
  112. /* Write the length and the chunk name */
  113. png_save_uint_32(buf, length);
  114. png_memcpy(buf + 4, chunk_name, 4);
  115. png_write_data(png_ptr, buf, (png_size_t)8);
  116. /* Put the chunk name into png_ptr->chunk_name */
  117. png_memcpy(png_ptr->chunk_name, chunk_name, 4);
  118. /* Reset the crc and run it over the chunk name */
  119. png_reset_crc(png_ptr);
  120. png_calculate_crc(png_ptr, chunk_name, 4);
  121. #ifdef PNG_IO_STATE_SUPPORTED
  122. /* Inform the I/O callback that chunk data will (possibly) be written.
  123. * PNG_IO_CHUNK_DATA does NOT require a specific number of I/O calls.
  124. */
  125. png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_DATA;
  126. #endif
  127. }
  128. /* Write the data of a PNG chunk started with png_write_chunk_start().
  129. * Note that multiple calls to this function are allowed, and that the
  130. * sum of the lengths from these calls *must* add up to the total_length
  131. * given to png_write_chunk_start().
  132. */
  133. void PNGAPI
  134. png_write_chunk_data(png_structp png_ptr, png_const_bytep data,
  135. png_size_t length)
  136. {
  137. /* Write the data, and run the CRC over it */
  138. if (png_ptr == NULL)
  139. return;
  140. if (data != NULL && length > 0)
  141. {
  142. png_write_data(png_ptr, data, length);
  143. /* Update the CRC after writing the data,
  144. * in case that the user I/O routine alters it.
  145. */
  146. png_calculate_crc(png_ptr, data, length);
  147. }
  148. }
  149. /* Finish a chunk started with png_write_chunk_start(). */
  150. void PNGAPI
  151. png_write_chunk_end(png_structp png_ptr)
  152. {
  153. png_byte buf[4];
  154. if (png_ptr == NULL) return;
  155. #ifdef PNG_IO_STATE_SUPPORTED
  156. /* Inform the I/O callback that the chunk CRC is being written.
  157. * PNG_IO_CHUNK_CRC requires a single I/O function call.
  158. */
  159. png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_CRC;
  160. #endif
  161. /* Write the crc in a single operation */
  162. png_save_uint_32(buf, png_ptr->crc);
  163. png_write_data(png_ptr, buf, (png_size_t)4);
  164. }
  165. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  166. /* This pair of functions encapsulates the operation of (a) compressing a
  167. * text string, and (b) issuing it later as a series of chunk data writes.
  168. * The compression_state structure is shared context for these functions
  169. * set up by the caller in order to make the whole mess thread-safe.
  170. */
  171. typedef struct
  172. {
  173. png_const_bytep input; /* The uncompressed input data */
  174. png_size_t input_len; /* Its length */
  175. int num_output_ptr; /* Number of output pointers used */
  176. int max_output_ptr; /* Size of output_ptr */
  177. png_bytep *output_ptr; /* Array of pointers to output */
  178. } compression_state;
  179. /* Compress given text into storage in the png_ptr structure */
  180. static int /* PRIVATE */
  181. png_text_compress(png_structp png_ptr,
  182. png_const_charp text, png_size_t text_len, int compression,
  183. compression_state *comp)
  184. {
  185. int ret;
  186. comp->num_output_ptr = 0;
  187. comp->max_output_ptr = 0;
  188. comp->output_ptr = NULL;
  189. comp->input = NULL;
  190. comp->input_len = 0;
  191. /* We may just want to pass the text right through */
  192. if (compression == PNG_TEXT_COMPRESSION_NONE)
  193. {
  194. comp->input = (png_const_bytep)text;
  195. comp->input_len = text_len;
  196. return((int)text_len);
  197. }
  198. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  199. {
  200. #ifdef PNG_CONSOLE_IO_SUPPORTED
  201. char msg[50];
  202. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  203. png_warning(png_ptr, msg);
  204. #else
  205. png_warning(png_ptr, "Unknown compression type");
  206. #endif
  207. }
  208. /* We can't write the chunk until we find out how much data we have,
  209. * which means we need to run the compressor first and save the
  210. * output. This shouldn't be a problem, as the vast majority of
  211. * comments should be reasonable, but we will set up an array of
  212. * malloc'd pointers to be sure.
  213. *
  214. * If we knew the application was well behaved, we could simplify this
  215. * greatly by assuming we can always malloc an output buffer large
  216. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  217. * and malloc this directly. The only time this would be a bad idea is
  218. * if we can't malloc more than 64K and we have 64K of random input
  219. * data, or if the input string is incredibly large (although this
  220. * wouldn't cause a failure, just a slowdown due to swapping).
  221. */
  222. /* Set up the compression buffers */
  223. /* TODO: the following cast hides a potential overflow problem. */
  224. png_ptr->zstream.avail_in = (uInt)text_len;
  225. /* NOTE: assume zlib doesn't overwrite the input */
  226. png_ptr->zstream.next_in = (Bytef *)text;
  227. png_ptr->zstream.avail_out = png_ptr->zbuf_size;
  228. png_ptr->zstream.next_out = png_ptr->zbuf;
  229. /* This is the same compression loop as in png_write_row() */
  230. do
  231. {
  232. /* Compress the data */
  233. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  234. if (ret != Z_OK)
  235. {
  236. /* Error */
  237. if (png_ptr->zstream.msg != NULL)
  238. png_error(png_ptr, png_ptr->zstream.msg);
  239. else
  240. png_error(png_ptr, "zlib error");
  241. }
  242. /* Check to see if we need more room */
  243. if (!(png_ptr->zstream.avail_out))
  244. {
  245. /* Make sure the output array has room */
  246. if (comp->num_output_ptr >= comp->max_output_ptr)
  247. {
  248. int old_max;
  249. old_max = comp->max_output_ptr;
  250. comp->max_output_ptr = comp->num_output_ptr + 4;
  251. if (comp->output_ptr != NULL)
  252. {
  253. png_bytepp old_ptr;
  254. old_ptr = comp->output_ptr;
  255. comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
  256. (png_alloc_size_t)
  257. (comp->max_output_ptr * png_sizeof(png_charpp)));
  258. png_memcpy(comp->output_ptr, old_ptr, old_max
  259. * png_sizeof(png_charp));
  260. png_free(png_ptr, old_ptr);
  261. }
  262. else
  263. comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
  264. (png_alloc_size_t)
  265. (comp->max_output_ptr * png_sizeof(png_charp)));
  266. }
  267. /* Save the data */
  268. comp->output_ptr[comp->num_output_ptr] =
  269. (png_bytep)png_malloc(png_ptr,
  270. (png_alloc_size_t)png_ptr->zbuf_size);
  271. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  272. png_ptr->zbuf_size);
  273. comp->num_output_ptr++;
  274. /* and reset the buffer */
  275. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  276. png_ptr->zstream.next_out = png_ptr->zbuf;
  277. }
  278. /* Continue until we don't have any more to compress */
  279. } while (png_ptr->zstream.avail_in);
  280. /* Finish the compression */
  281. do
  282. {
  283. /* Tell zlib we are finished */
  284. ret = deflate(&png_ptr->zstream, Z_FINISH);
  285. if (ret == Z_OK)
  286. {
  287. /* Check to see if we need more room */
  288. if (!(png_ptr->zstream.avail_out))
  289. {
  290. /* Check to make sure our output array has room */
  291. if (comp->num_output_ptr >= comp->max_output_ptr)
  292. {
  293. int old_max;
  294. old_max = comp->max_output_ptr;
  295. comp->max_output_ptr = comp->num_output_ptr + 4;
  296. if (comp->output_ptr != NULL)
  297. {
  298. png_bytepp old_ptr;
  299. old_ptr = comp->output_ptr;
  300. /* This could be optimized to realloc() */
  301. comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
  302. (png_alloc_size_t)(comp->max_output_ptr *
  303. png_sizeof(png_charp)));
  304. png_memcpy(comp->output_ptr, old_ptr,
  305. old_max * png_sizeof(png_charp));
  306. png_free(png_ptr, old_ptr);
  307. }
  308. else
  309. comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
  310. (png_alloc_size_t)(comp->max_output_ptr *
  311. png_sizeof(png_charp)));
  312. }
  313. /* Save the data */
  314. comp->output_ptr[comp->num_output_ptr] =
  315. (png_bytep)png_malloc(png_ptr,
  316. (png_alloc_size_t)png_ptr->zbuf_size);
  317. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  318. png_ptr->zbuf_size);
  319. comp->num_output_ptr++;
  320. /* and reset the buffer pointers */
  321. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  322. png_ptr->zstream.next_out = png_ptr->zbuf;
  323. }
  324. }
  325. else if (ret != Z_STREAM_END)
  326. {
  327. /* We got an error */
  328. if (png_ptr->zstream.msg != NULL)
  329. png_error(png_ptr, png_ptr->zstream.msg);
  330. else
  331. png_error(png_ptr, "zlib error");
  332. }
  333. } while (ret != Z_STREAM_END);
  334. /* Text length is number of buffers plus last buffer */
  335. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  336. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  337. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  338. return((int)text_len);
  339. }
  340. /* Ship the compressed text out via chunk writes */
  341. static void /* PRIVATE */
  342. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  343. {
  344. int i;
  345. /* Handle the no-compression case */
  346. if (comp->input)
  347. {
  348. png_write_chunk_data(png_ptr, comp->input, comp->input_len);
  349. return;
  350. }
  351. /* Write saved output buffers, if any */
  352. for (i = 0; i < comp->num_output_ptr; i++)
  353. {
  354. png_write_chunk_data(png_ptr, comp->output_ptr[i],
  355. (png_size_t)png_ptr->zbuf_size);
  356. png_free(png_ptr, comp->output_ptr[i]);
  357. }
  358. if (comp->max_output_ptr != 0)
  359. png_free(png_ptr, comp->output_ptr);
  360. /* Write anything left in zbuf */
  361. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  362. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  363. (png_size_t)(png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  364. /* Reset zlib for another zTXt/iTXt or image data */
  365. deflateReset(&png_ptr->zstream);
  366. png_ptr->zstream.data_type = Z_BINARY;
  367. }
  368. #endif
  369. /* Write the IHDR chunk, and update the png_struct with the necessary
  370. * information. Note that the rest of this code depends upon this
  371. * information being correct.
  372. */
  373. void /* PRIVATE */
  374. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  375. int bit_depth, int color_type, int compression_type, int filter_type,
  376. int interlace_type)
  377. {
  378. PNG_IHDR;
  379. int ret;
  380. png_byte buf[13]; /* Buffer to store the IHDR info */
  381. png_debug(1, "in png_write_IHDR");
  382. /* Check that we have valid input data from the application info */
  383. switch (color_type)
  384. {
  385. case PNG_COLOR_TYPE_GRAY:
  386. switch (bit_depth)
  387. {
  388. case 1:
  389. case 2:
  390. case 4:
  391. case 8:
  392. #ifdef PNG_WRITE_16BIT_SUPPORTED
  393. case 16:
  394. #endif
  395. png_ptr->channels = 1; break;
  396. default:
  397. png_error(png_ptr,
  398. "Invalid bit depth for grayscale image");
  399. }
  400. break;
  401. case PNG_COLOR_TYPE_RGB:
  402. #ifdef PNG_WRITE_16BIT_SUPPORTED
  403. if (bit_depth != 8 && bit_depth != 16)
  404. #else
  405. if (bit_depth != 8)
  406. #endif
  407. png_error(png_ptr, "Invalid bit depth for RGB image");
  408. png_ptr->channels = 3;
  409. break;
  410. case PNG_COLOR_TYPE_PALETTE:
  411. switch (bit_depth)
  412. {
  413. case 1:
  414. case 2:
  415. case 4:
  416. case 8:
  417. png_ptr->channels = 1;
  418. break;
  419. default:
  420. png_error(png_ptr, "Invalid bit depth for paletted image");
  421. }
  422. break;
  423. case PNG_COLOR_TYPE_GRAY_ALPHA:
  424. if (bit_depth != 8 && bit_depth != 16)
  425. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  426. png_ptr->channels = 2;
  427. break;
  428. case PNG_COLOR_TYPE_RGB_ALPHA:
  429. #ifdef PNG_WRITE_16BIT_SUPPORTED
  430. if (bit_depth != 8 && bit_depth != 16)
  431. #else
  432. if (bit_depth != 8)
  433. #endif
  434. png_error(png_ptr, "Invalid bit depth for RGBA image");
  435. png_ptr->channels = 4;
  436. break;
  437. default:
  438. png_error(png_ptr, "Invalid image color type specified");
  439. }
  440. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  441. {
  442. png_warning(png_ptr, "Invalid compression type specified");
  443. compression_type = PNG_COMPRESSION_TYPE_BASE;
  444. }
  445. /* Write filter_method 64 (intrapixel differencing) only if
  446. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  447. * 2. Libpng did not write a PNG signature (this filter_method is only
  448. * used in PNG datastreams that are embedded in MNG datastreams) and
  449. * 3. The application called png_permit_mng_features with a mask that
  450. * included PNG_FLAG_MNG_FILTER_64 and
  451. * 4. The filter_method is 64 and
  452. * 5. The color_type is RGB or RGBA
  453. */
  454. if (
  455. #ifdef PNG_MNG_FEATURES_SUPPORTED
  456. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  457. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  458. (color_type == PNG_COLOR_TYPE_RGB ||
  459. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  460. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  461. #endif
  462. filter_type != PNG_FILTER_TYPE_BASE)
  463. {
  464. png_warning(png_ptr, "Invalid filter type specified");
  465. filter_type = PNG_FILTER_TYPE_BASE;
  466. }
  467. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  468. if (interlace_type != PNG_INTERLACE_NONE &&
  469. interlace_type != PNG_INTERLACE_ADAM7)
  470. {
  471. png_warning(png_ptr, "Invalid interlace type specified");
  472. interlace_type = PNG_INTERLACE_ADAM7;
  473. }
  474. #else
  475. interlace_type=PNG_INTERLACE_NONE;
  476. #endif
  477. /* Save the relevent information */
  478. png_ptr->bit_depth = (png_byte)bit_depth;
  479. png_ptr->color_type = (png_byte)color_type;
  480. png_ptr->interlaced = (png_byte)interlace_type;
  481. #ifdef PNG_MNG_FEATURES_SUPPORTED
  482. png_ptr->filter_type = (png_byte)filter_type;
  483. #endif
  484. png_ptr->compression_type = (png_byte)compression_type;
  485. png_ptr->width = width;
  486. png_ptr->height = height;
  487. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  488. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  489. /* Set the usr info, so any transformations can modify it */
  490. png_ptr->usr_width = png_ptr->width;
  491. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  492. png_ptr->usr_channels = png_ptr->channels;
  493. /* Pack the header information into the buffer */
  494. png_save_uint_32(buf, width);
  495. png_save_uint_32(buf + 4, height);
  496. buf[8] = (png_byte)bit_depth;
  497. buf[9] = (png_byte)color_type;
  498. buf[10] = (png_byte)compression_type;
  499. buf[11] = (png_byte)filter_type;
  500. buf[12] = (png_byte)interlace_type;
  501. /* Write the chunk */
  502. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  503. /* Initialize zlib with PNG info */
  504. png_ptr->zstream.zalloc = png_zalloc;
  505. png_ptr->zstream.zfree = png_zfree;
  506. png_ptr->zstream.opaque = (voidpf)png_ptr;
  507. if (!(png_ptr->do_filter))
  508. {
  509. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  510. png_ptr->bit_depth < 8)
  511. png_ptr->do_filter = PNG_FILTER_NONE;
  512. else
  513. png_ptr->do_filter = PNG_ALL_FILTERS;
  514. }
  515. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  516. {
  517. if (png_ptr->do_filter != PNG_FILTER_NONE)
  518. png_ptr->zlib_strategy = Z_FILTERED;
  519. else
  520. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  521. }
  522. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  523. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  524. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  525. png_ptr->zlib_mem_level = 8;
  526. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  527. png_ptr->zlib_window_bits = 15;
  528. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  529. png_ptr->zlib_method = 8;
  530. ret = deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  531. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  532. png_ptr->zlib_mem_level, png_ptr->zlib_strategy);
  533. if (ret != Z_OK)
  534. {
  535. if (ret == Z_VERSION_ERROR)
  536. png_error(png_ptr,
  537. "zlib failed to initialize compressor -- version error");
  538. if (ret == Z_STREAM_ERROR)
  539. png_error(png_ptr,
  540. "zlib failed to initialize compressor -- stream error");
  541. if (ret == Z_MEM_ERROR)
  542. png_error(png_ptr,
  543. "zlib failed to initialize compressor -- mem error");
  544. png_error(png_ptr, "zlib failed to initialize compressor");
  545. }
  546. png_ptr->zstream.next_out = png_ptr->zbuf;
  547. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  548. /* libpng is not interested in zstream.data_type, so set it
  549. * to a predefined value, to avoid its evaluation inside zlib
  550. */
  551. png_ptr->zstream.data_type = Z_BINARY;
  552. png_ptr->mode = PNG_HAVE_IHDR;
  553. }
  554. /* Write the palette. We are careful not to trust png_color to be in the
  555. * correct order for PNG, so people can redefine it to any convenient
  556. * structure.
  557. */
  558. void /* PRIVATE */
  559. png_write_PLTE(png_structp png_ptr, png_const_colorp palette,
  560. png_uint_32 num_pal)
  561. {
  562. PNG_PLTE;
  563. png_uint_32 i;
  564. png_const_colorp pal_ptr;
  565. png_byte buf[3];
  566. png_debug(1, "in png_write_PLTE");
  567. if ((
  568. #ifdef PNG_MNG_FEATURES_SUPPORTED
  569. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  570. #endif
  571. num_pal == 0) || num_pal > 256)
  572. {
  573. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  574. {
  575. png_error(png_ptr, "Invalid number of colors in palette");
  576. }
  577. else
  578. {
  579. png_warning(png_ptr, "Invalid number of colors in palette");
  580. return;
  581. }
  582. }
  583. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  584. {
  585. png_warning(png_ptr,
  586. "Ignoring request to write a PLTE chunk in grayscale PNG");
  587. return;
  588. }
  589. png_ptr->num_palette = (png_uint_16)num_pal;
  590. png_debug1(3, "num_palette = %d", png_ptr->num_palette);
  591. png_write_chunk_start(png_ptr, png_PLTE, (png_uint_32)(num_pal * 3));
  592. #ifdef PNG_POINTER_INDEXING_SUPPORTED
  593. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  594. {
  595. buf[0] = pal_ptr->red;
  596. buf[1] = pal_ptr->green;
  597. buf[2] = pal_ptr->blue;
  598. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  599. }
  600. #else
  601. /* This is a little slower but some buggy compilers need to do this
  602. * instead
  603. */
  604. pal_ptr=palette;
  605. for (i = 0; i < num_pal; i++)
  606. {
  607. buf[0] = pal_ptr[i].red;
  608. buf[1] = pal_ptr[i].green;
  609. buf[2] = pal_ptr[i].blue;
  610. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  611. }
  612. #endif
  613. png_write_chunk_end(png_ptr);
  614. png_ptr->mode |= PNG_HAVE_PLTE;
  615. }
  616. /* Write an IDAT chunk */
  617. void /* PRIVATE */
  618. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  619. {
  620. PNG_IDAT;
  621. png_debug(1, "in png_write_IDAT");
  622. /* Optimize the CMF field in the zlib stream. */
  623. /* This hack of the zlib stream is compliant to the stream specification. */
  624. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  625. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  626. {
  627. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  628. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  629. {
  630. /* Avoid memory underflows and multiplication overflows.
  631. *
  632. * The conditions below are practically always satisfied;
  633. * however, they still must be checked.
  634. */
  635. if (length >= 2 &&
  636. png_ptr->height < 16384 && png_ptr->width < 16384)
  637. {
  638. png_uint_32 uncompressed_idat_size = png_ptr->height *
  639. ((png_ptr->width *
  640. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  641. unsigned int z_cinfo = z_cmf >> 4;
  642. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  643. while (uncompressed_idat_size <= half_z_window_size &&
  644. half_z_window_size >= 256)
  645. {
  646. z_cinfo--;
  647. half_z_window_size >>= 1;
  648. }
  649. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  650. if (data[0] != z_cmf)
  651. {
  652. int tmp;
  653. data[0] = (png_byte)z_cmf;
  654. tmp = data[1] & 0xe0;
  655. tmp += 0x1f - ((z_cmf << 8) + tmp) % 0x1f;
  656. data[1] = (png_byte)tmp;
  657. }
  658. }
  659. }
  660. else
  661. png_error(png_ptr,
  662. "Invalid zlib compression method or flags in IDAT");
  663. }
  664. png_write_chunk(png_ptr, png_IDAT, data, length);
  665. png_ptr->mode |= PNG_HAVE_IDAT;
  666. }
  667. /* Write an IEND chunk */
  668. void /* PRIVATE */
  669. png_write_IEND(png_structp png_ptr)
  670. {
  671. PNG_IEND;
  672. png_debug(1, "in png_write_IEND");
  673. png_write_chunk(png_ptr, png_IEND, NULL, (png_size_t)0);
  674. png_ptr->mode |= PNG_HAVE_IEND;
  675. }
  676. #ifdef PNG_WRITE_gAMA_SUPPORTED
  677. /* Write a gAMA chunk */
  678. void /* PRIVATE */
  679. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  680. {
  681. PNG_gAMA;
  682. png_byte buf[4];
  683. png_debug(1, "in png_write_gAMA");
  684. /* file_gamma is saved in 1/100,000ths */
  685. png_save_uint_32(buf, (png_uint_32)file_gamma);
  686. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  687. }
  688. #endif
  689. #ifdef PNG_WRITE_sRGB_SUPPORTED
  690. /* Write a sRGB chunk */
  691. void /* PRIVATE */
  692. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  693. {
  694. PNG_sRGB;
  695. png_byte buf[1];
  696. png_debug(1, "in png_write_sRGB");
  697. if (srgb_intent >= PNG_sRGB_INTENT_LAST)
  698. png_warning(png_ptr,
  699. "Invalid sRGB rendering intent specified");
  700. buf[0]=(png_byte)srgb_intent;
  701. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  702. }
  703. #endif
  704. #ifdef PNG_WRITE_iCCP_SUPPORTED
  705. /* Write an iCCP chunk */
  706. void /* PRIVATE */
  707. png_write_iCCP(png_structp png_ptr, png_const_charp name, int compression_type,
  708. png_const_charp profile, int profile_len)
  709. {
  710. PNG_iCCP;
  711. png_size_t name_len;
  712. png_charp new_name;
  713. compression_state comp;
  714. int embedded_profile_len = 0;
  715. png_debug(1, "in png_write_iCCP");
  716. comp.num_output_ptr = 0;
  717. comp.max_output_ptr = 0;
  718. comp.output_ptr = NULL;
  719. comp.input = NULL;
  720. comp.input_len = 0;
  721. if ((name_len = png_check_keyword(png_ptr, name, &new_name)) == 0)
  722. return;
  723. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  724. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  725. if (profile == NULL)
  726. profile_len = 0;
  727. if (profile_len > 3)
  728. embedded_profile_len =
  729. ((*( (png_const_bytep)profile ))<<24) |
  730. ((*( (png_const_bytep)profile + 1))<<16) |
  731. ((*( (png_const_bytep)profile + 2))<< 8) |
  732. ((*( (png_const_bytep)profile + 3)) );
  733. if (embedded_profile_len < 0)
  734. {
  735. png_warning(png_ptr,
  736. "Embedded profile length in iCCP chunk is negative");
  737. png_free(png_ptr, new_name);
  738. return;
  739. }
  740. if (profile_len < embedded_profile_len)
  741. {
  742. png_warning(png_ptr,
  743. "Embedded profile length too large in iCCP chunk");
  744. png_free(png_ptr, new_name);
  745. return;
  746. }
  747. if (profile_len > embedded_profile_len)
  748. {
  749. png_warning(png_ptr,
  750. "Truncating profile to actual length in iCCP chunk");
  751. profile_len = embedded_profile_len;
  752. }
  753. if (profile_len)
  754. profile_len = png_text_compress(png_ptr, profile,
  755. (png_size_t)profile_len, PNG_COMPRESSION_TYPE_BASE, &comp);
  756. /* Make sure we include the NULL after the name and the compression type */
  757. png_write_chunk_start(png_ptr, png_iCCP,
  758. (png_uint_32)(name_len + profile_len + 2));
  759. new_name[name_len + 1] = 0x00;
  760. png_write_chunk_data(png_ptr, (png_bytep)new_name,
  761. (png_size_t)(name_len + 2));
  762. if (profile_len)
  763. png_write_compressed_data_out(png_ptr, &comp);
  764. png_write_chunk_end(png_ptr);
  765. png_free(png_ptr, new_name);
  766. }
  767. #endif
  768. #ifdef PNG_WRITE_sPLT_SUPPORTED
  769. /* Write a sPLT chunk */
  770. void /* PRIVATE */
  771. png_write_sPLT(png_structp png_ptr, png_const_sPLT_tp spalette)
  772. {
  773. PNG_sPLT;
  774. png_size_t name_len;
  775. png_charp new_name;
  776. png_byte entrybuf[10];
  777. png_size_t entry_size = (spalette->depth == 8 ? 6 : 10);
  778. png_size_t palette_size = entry_size * spalette->nentries;
  779. png_sPLT_entryp ep;
  780. #ifndef PNG_POINTER_INDEXING_SUPPORTED
  781. int i;
  782. #endif
  783. png_debug(1, "in png_write_sPLT");
  784. if ((name_len = png_check_keyword(png_ptr,spalette->name, &new_name))==0)
  785. return;
  786. /* Make sure we include the NULL after the name */
  787. png_write_chunk_start(png_ptr, png_sPLT,
  788. (png_uint_32)(name_len + 2 + palette_size));
  789. png_write_chunk_data(png_ptr, (png_bytep)new_name,
  790. (png_size_t)(name_len + 1));
  791. png_write_chunk_data(png_ptr, &spalette->depth, (png_size_t)1);
  792. /* Loop through each palette entry, writing appropriately */
  793. #ifdef PNG_POINTER_INDEXING_SUPPORTED
  794. for (ep = spalette->entries; ep<spalette->entries + spalette->nentries; ep++)
  795. {
  796. if (spalette->depth == 8)
  797. {
  798. entrybuf[0] = (png_byte)ep->red;
  799. entrybuf[1] = (png_byte)ep->green;
  800. entrybuf[2] = (png_byte)ep->blue;
  801. entrybuf[3] = (png_byte)ep->alpha;
  802. png_save_uint_16(entrybuf + 4, ep->frequency);
  803. }
  804. else
  805. {
  806. png_save_uint_16(entrybuf + 0, ep->red);
  807. png_save_uint_16(entrybuf + 2, ep->green);
  808. png_save_uint_16(entrybuf + 4, ep->blue);
  809. png_save_uint_16(entrybuf + 6, ep->alpha);
  810. png_save_uint_16(entrybuf + 8, ep->frequency);
  811. }
  812. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  813. }
  814. #else
  815. ep=spalette->entries;
  816. for (i = 0; i>spalette->nentries; i++)
  817. {
  818. if (spalette->depth == 8)
  819. {
  820. entrybuf[0] = (png_byte)ep[i].red;
  821. entrybuf[1] = (png_byte)ep[i].green;
  822. entrybuf[2] = (png_byte)ep[i].blue;
  823. entrybuf[3] = (png_byte)ep[i].alpha;
  824. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  825. }
  826. else
  827. {
  828. png_save_uint_16(entrybuf + 0, ep[i].red);
  829. png_save_uint_16(entrybuf + 2, ep[i].green);
  830. png_save_uint_16(entrybuf + 4, ep[i].blue);
  831. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  832. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  833. }
  834. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  835. }
  836. #endif
  837. png_write_chunk_end(png_ptr);
  838. png_free(png_ptr, new_name);
  839. }
  840. #endif
  841. #ifdef PNG_WRITE_sBIT_SUPPORTED
  842. /* Write the sBIT chunk */
  843. void /* PRIVATE */
  844. png_write_sBIT(png_structp png_ptr, png_const_color_8p sbit, int color_type)
  845. {
  846. PNG_sBIT;
  847. png_byte buf[4];
  848. png_size_t size;
  849. png_debug(1, "in png_write_sBIT");
  850. /* Make sure we don't depend upon the order of PNG_COLOR_8 */
  851. if (color_type & PNG_COLOR_MASK_COLOR)
  852. {
  853. png_byte maxbits;
  854. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  855. png_ptr->usr_bit_depth);
  856. if (sbit->red == 0 || sbit->red > maxbits ||
  857. sbit->green == 0 || sbit->green > maxbits ||
  858. sbit->blue == 0 || sbit->blue > maxbits)
  859. {
  860. png_warning(png_ptr, "Invalid sBIT depth specified");
  861. return;
  862. }
  863. buf[0] = sbit->red;
  864. buf[1] = sbit->green;
  865. buf[2] = sbit->blue;
  866. size = 3;
  867. }
  868. else
  869. {
  870. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  871. {
  872. png_warning(png_ptr, "Invalid sBIT depth specified");
  873. return;
  874. }
  875. buf[0] = sbit->gray;
  876. size = 1;
  877. }
  878. if (color_type & PNG_COLOR_MASK_ALPHA)
  879. {
  880. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  881. {
  882. png_warning(png_ptr, "Invalid sBIT depth specified");
  883. return;
  884. }
  885. buf[size++] = sbit->alpha;
  886. }
  887. png_write_chunk(png_ptr, png_sBIT, buf, size);
  888. }
  889. #endif
  890. #ifdef PNG_WRITE_cHRM_SUPPORTED
  891. /* Write the cHRM chunk */
  892. void /* PRIVATE */
  893. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  894. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  895. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  896. png_fixed_point blue_y)
  897. {
  898. PNG_cHRM;
  899. png_byte buf[32];
  900. png_debug(1, "in png_write_cHRM");
  901. /* Each value is saved in 1/100,000ths */
  902. #ifdef PNG_CHECK_cHRM_SUPPORTED
  903. if (png_check_cHRM_fixed(png_ptr, white_x, white_y, red_x, red_y,
  904. green_x, green_y, blue_x, blue_y))
  905. #endif
  906. {
  907. png_save_uint_32(buf, (png_uint_32)white_x);
  908. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  909. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  910. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  911. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  912. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  913. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  914. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  915. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  916. }
  917. }
  918. #endif
  919. #ifdef PNG_WRITE_tRNS_SUPPORTED
  920. /* Write the tRNS chunk */
  921. void /* PRIVATE */
  922. png_write_tRNS(png_structp png_ptr, png_const_bytep trans_alpha,
  923. png_const_color_16p tran, int num_trans, int color_type)
  924. {
  925. PNG_tRNS;
  926. png_byte buf[6];
  927. png_debug(1, "in png_write_tRNS");
  928. if (color_type == PNG_COLOR_TYPE_PALETTE)
  929. {
  930. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  931. {
  932. png_warning(png_ptr, "Invalid number of transparent colors specified");
  933. return;
  934. }
  935. /* Write the chunk out as it is */
  936. png_write_chunk(png_ptr, png_tRNS, trans_alpha, (png_size_t)num_trans);
  937. }
  938. else if (color_type == PNG_COLOR_TYPE_GRAY)
  939. {
  940. /* One 16 bit value */
  941. if (tran->gray >= (1 << png_ptr->bit_depth))
  942. {
  943. png_warning(png_ptr,
  944. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  945. return;
  946. }
  947. png_save_uint_16(buf, tran->gray);
  948. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  949. }
  950. else if (color_type == PNG_COLOR_TYPE_RGB)
  951. {
  952. /* Three 16 bit values */
  953. png_save_uint_16(buf, tran->red);
  954. png_save_uint_16(buf + 2, tran->green);
  955. png_save_uint_16(buf + 4, tran->blue);
  956. #ifdef PNG_WRITE_16BIT_SUPPORTED
  957. if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  958. #else
  959. if (buf[0] | buf[2] | buf[4])
  960. #endif
  961. {
  962. png_warning(png_ptr,
  963. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  964. return;
  965. }
  966. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  967. }
  968. else
  969. {
  970. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  971. }
  972. }
  973. #endif
  974. #ifdef PNG_WRITE_bKGD_SUPPORTED
  975. /* Write the background chunk */
  976. void /* PRIVATE */
  977. png_write_bKGD(png_structp png_ptr, png_const_color_16p back, int color_type)
  978. {
  979. PNG_bKGD;
  980. png_byte buf[6];
  981. png_debug(1, "in png_write_bKGD");
  982. if (color_type == PNG_COLOR_TYPE_PALETTE)
  983. {
  984. if (
  985. #ifdef PNG_MNG_FEATURES_SUPPORTED
  986. (png_ptr->num_palette ||
  987. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  988. #endif
  989. back->index >= png_ptr->num_palette)
  990. {
  991. png_warning(png_ptr, "Invalid background palette index");
  992. return;
  993. }
  994. buf[0] = back->index;
  995. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  996. }
  997. else if (color_type & PNG_COLOR_MASK_COLOR)
  998. {
  999. png_save_uint_16(buf, back->red);
  1000. png_save_uint_16(buf + 2, back->green);
  1001. png_save_uint_16(buf + 4, back->blue);
  1002. #ifdef PNG_WRITE_16BIT_SUPPORTED
  1003. if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  1004. #else
  1005. if (buf[0] | buf[2] | buf[4])
  1006. #endif
  1007. {
  1008. png_warning(png_ptr,
  1009. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  1010. return;
  1011. }
  1012. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  1013. }
  1014. else
  1015. {
  1016. if (back->gray >= (1 << png_ptr->bit_depth))
  1017. {
  1018. png_warning(png_ptr,
  1019. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  1020. return;
  1021. }
  1022. png_save_uint_16(buf, back->gray);
  1023. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  1024. }
  1025. }
  1026. #endif
  1027. #ifdef PNG_WRITE_hIST_SUPPORTED
  1028. /* Write the histogram */
  1029. void /* PRIVATE */
  1030. png_write_hIST(png_structp png_ptr, png_const_uint_16p hist, int num_hist)
  1031. {
  1032. PNG_hIST;
  1033. int i;
  1034. png_byte buf[3];
  1035. png_debug(1, "in png_write_hIST");
  1036. if (num_hist > (int)png_ptr->num_palette)
  1037. {
  1038. png_debug2(3, "num_hist = %d, num_palette = %d", num_hist,
  1039. png_ptr->num_palette);
  1040. png_warning(png_ptr, "Invalid number of histogram entries specified");
  1041. return;
  1042. }
  1043. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  1044. for (i = 0; i < num_hist; i++)
  1045. {
  1046. png_save_uint_16(buf, hist[i]);
  1047. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  1048. }
  1049. png_write_chunk_end(png_ptr);
  1050. }
  1051. #endif
  1052. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  1053. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  1054. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  1055. * and if invalid, correct the keyword rather than discarding the entire
  1056. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  1057. * length, forbids leading or trailing whitespace, multiple internal spaces,
  1058. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  1059. *
  1060. * The new_key is allocated to hold the corrected keyword and must be freed
  1061. * by the calling routine. This avoids problems with trying to write to
  1062. * static keywords without having to have duplicate copies of the strings.
  1063. */
  1064. png_size_t /* PRIVATE */
  1065. png_check_keyword(png_structp png_ptr, png_const_charp key, png_charpp new_key)
  1066. {
  1067. png_size_t key_len;
  1068. png_const_charp ikp;
  1069. png_charp kp, dp;
  1070. int kflag;
  1071. int kwarn=0;
  1072. png_debug(1, "in png_check_keyword");
  1073. *new_key = NULL;
  1074. if (key == NULL || (key_len = png_strlen(key)) == 0)
  1075. {
  1076. png_warning(png_ptr, "zero length keyword");
  1077. return ((png_size_t)0);
  1078. }
  1079. png_debug1(2, "Keyword to be checked is '%s'", key);
  1080. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  1081. if (*new_key == NULL)
  1082. {
  1083. png_warning(png_ptr, "Out of memory while procesing keyword");
  1084. return ((png_size_t)0);
  1085. }
  1086. /* Replace non-printing characters with a blank and print a warning */
  1087. for (ikp = key, dp = *new_key; *ikp != '\0'; ikp++, dp++)
  1088. {
  1089. if ((png_byte)*ikp < 0x20 ||
  1090. ((png_byte)*ikp > 0x7E && (png_byte)*ikp < 0xA1))
  1091. {
  1092. #ifdef PNG_CONSOLE_IO_SUPPORTED
  1093. char msg[40];
  1094. png_snprintf(msg, 40,
  1095. "invalid keyword character 0x%02X", (png_byte)*ikp);
  1096. png_warning(png_ptr, msg);
  1097. #else
  1098. png_warning(png_ptr, "invalid character in keyword");
  1099. #endif
  1100. *dp = ' ';
  1101. }
  1102. else
  1103. {
  1104. *dp = *ikp;
  1105. }
  1106. }
  1107. *dp = '\0';
  1108. /* Remove any trailing white space. */
  1109. kp = *new_key + key_len - 1;
  1110. if (*kp == ' ')
  1111. {
  1112. png_warning(png_ptr, "trailing spaces removed from keyword");
  1113. while (*kp == ' ')
  1114. {
  1115. *(kp--) = '\0';
  1116. key_len--;
  1117. }
  1118. }
  1119. /* Remove any leading white space. */
  1120. kp = *new_key;
  1121. if (*kp == ' ')
  1122. {
  1123. png_warning(png_ptr, "leading spaces removed from keyword");
  1124. while (*kp == ' ')
  1125. {
  1126. kp++;
  1127. key_len--;
  1128. }
  1129. }
  1130. png_debug1(2, "Checking for multiple internal spaces in '%s'", kp);
  1131. /* Remove multiple internal spaces. */
  1132. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  1133. {
  1134. if (*kp == ' ' && kflag == 0)
  1135. {
  1136. *(dp++) = *kp;
  1137. kflag = 1;
  1138. }
  1139. else if (*kp == ' ')
  1140. {
  1141. key_len--;
  1142. kwarn = 1;
  1143. }
  1144. else
  1145. {
  1146. *(dp++) = *kp;
  1147. kflag = 0;
  1148. }
  1149. }
  1150. *dp = '\0';
  1151. if (kwarn)
  1152. png_warning(png_ptr, "extra interior spaces removed from keyword");
  1153. if (key_len == 0)
  1154. {
  1155. png_free(png_ptr, *new_key);
  1156. png_warning(png_ptr, "Zero length keyword");
  1157. }
  1158. if (key_len > 79)
  1159. {
  1160. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  1161. (*new_key)[79] = '\0';
  1162. key_len = 79;
  1163. }
  1164. return (key_len);
  1165. }
  1166. #endif
  1167. #ifdef PNG_WRITE_tEXt_SUPPORTED
  1168. /* Write a tEXt chunk */
  1169. void /* PRIVATE */
  1170. png_write_tEXt(png_structp png_ptr, png_const_charp key, png_const_charp text,
  1171. png_size_t text_len)
  1172. {
  1173. PNG_tEXt;
  1174. png_size_t key_len;
  1175. png_charp new_key;
  1176. png_debug(1, "in png_write_tEXt");
  1177. if ((key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  1178. return;
  1179. if (text == NULL || *text == '\0')
  1180. text_len = 0;
  1181. else
  1182. text_len = png_strlen(text);
  1183. /* Make sure we include the 0 after the key */
  1184. png_write_chunk_start(png_ptr, png_tEXt,
  1185. (png_uint_32)(key_len + text_len + 1));
  1186. /*
  1187. * We leave it to the application to meet PNG-1.0 requirements on the
  1188. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  1189. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  1190. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  1191. */
  1192. png_write_chunk_data(png_ptr, (png_bytep)new_key,
  1193. (png_size_t)(key_len + 1));
  1194. if (text_len)
  1195. png_write_chunk_data(png_ptr, (png_const_bytep)text,
  1196. (png_size_t)text_len);
  1197. png_write_chunk_end(png_ptr);
  1198. png_free(png_ptr, new_key);
  1199. }
  1200. #endif
  1201. #ifdef PNG_WRITE_zTXt_SUPPORTED
  1202. /* Write a compressed text chunk */
  1203. void /* PRIVATE */
  1204. png_write_zTXt(png_structp png_ptr, png_const_charp key, png_const_charp text,
  1205. png_size_t text_len, int compression)
  1206. {
  1207. PNG_zTXt;
  1208. png_size_t key_len;
  1209. png_byte buf;
  1210. png_charp new_key;
  1211. compression_state comp;
  1212. png_debug(1, "in png_write_zTXt");
  1213. comp.num_output_ptr = 0;
  1214. comp.max_output_ptr = 0;
  1215. comp.output_ptr = NULL;
  1216. comp.input = NULL;
  1217. comp.input_len = 0;
  1218. if ((key_len = png_check_keyword(png_ptr, key, &new_key)) == 0)
  1219. {
  1220. png_free(png_ptr, new_key);
  1221. return;
  1222. }
  1223. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  1224. {
  1225. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  1226. png_free(png_ptr, new_key);
  1227. return;
  1228. }
  1229. text_len = png_strlen(text);
  1230. /* Compute the compressed data; do it now for the length */
  1231. text_len = png_text_compress(png_ptr, text, text_len, compression,
  1232. &comp);
  1233. /* Write start of chunk */
  1234. png_write_chunk_start(png_ptr, png_zTXt,
  1235. (png_uint_32)(key_len+text_len + 2));
  1236. /* Write key */
  1237. png_write_chunk_data(png_ptr, (png_bytep)new_key,
  1238. (png_size_t)(key_len + 1));
  1239. png_free(png_ptr, new_key);
  1240. buf = (png_byte)compression;
  1241. /* Write compression */
  1242. png_write_chunk_data(png_ptr, &buf, (png_size_t)1);
  1243. /* Write the compressed data */
  1244. png_write_compressed_data_out(png_ptr, &comp);
  1245. /* Close the chunk */
  1246. png_write_chunk_end(png_ptr);
  1247. }
  1248. #endif
  1249. #ifdef PNG_WRITE_iTXt_SUPPORTED
  1250. /* Write an iTXt chunk */
  1251. void /* PRIVATE */
  1252. png_write_iTXt(png_structp png_ptr, int compression, png_const_charp key,
  1253. png_const_charp lang, png_const_charp lang_key, png_const_charp text)
  1254. {
  1255. PNG_iTXt;
  1256. png_size_t lang_len, key_len, lang_key_len, text_len;
  1257. png_charp new_lang;
  1258. png_charp new_key = NULL;
  1259. png_byte cbuf[2];
  1260. compression_state comp;
  1261. png_debug(1, "in png_write_iTXt");
  1262. comp.num_output_ptr = 0;
  1263. comp.max_output_ptr = 0;
  1264. comp.output_ptr = NULL;
  1265. comp.input = NULL;
  1266. if ((key_len = png_check_keyword(png_ptr, key, &new_key)) == 0)
  1267. return;
  1268. if ((lang_len = png_check_keyword(png_ptr, lang, &new_lang)) == 0)
  1269. {
  1270. png_warning(png_ptr, "Empty language field in iTXt chunk");
  1271. new_lang = NULL;
  1272. lang_len = 0;
  1273. }
  1274. if (lang_key == NULL)
  1275. lang_key_len = 0;
  1276. else
  1277. lang_key_len = png_strlen(lang_key);
  1278. if (text == NULL)
  1279. text_len = 0;
  1280. else
  1281. text_len = png_strlen(text);
  1282. /* Compute the compressed data; do it now for the length */
  1283. text_len = png_text_compress(png_ptr, text, text_len, compression - 2,
  1284. &comp);
  1285. /* Make sure we include the compression flag, the compression byte,
  1286. * and the NULs after the key, lang, and lang_key parts
  1287. */
  1288. png_write_chunk_start(png_ptr, png_iTXt, (png_uint_32)(
  1289. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  1290. + key_len
  1291. + lang_len
  1292. + lang_key_len
  1293. + text_len));
  1294. /* We leave it to the application to meet PNG-1.0 requirements on the
  1295. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  1296. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  1297. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  1298. */
  1299. png_write_chunk_data(png_ptr, (png_bytep)new_key, (png_size_t)(key_len + 1));
  1300. /* Set the compression flag */
  1301. if (compression == PNG_ITXT_COMPRESSION_NONE ||
  1302. compression == PNG_TEXT_COMPRESSION_NONE)
  1303. cbuf[0] = 0;
  1304. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  1305. cbuf[0] = 1;
  1306. /* Set the compression method */
  1307. cbuf[1] = 0;
  1308. png_write_chunk_data(png_ptr, cbuf, (png_size_t)2);
  1309. cbuf[0] = 0;
  1310. png_write_chunk_data(png_ptr, (new_lang ? (png_const_bytep)new_lang : cbuf),
  1311. (png_size_t)(lang_len + 1));
  1312. png_write_chunk_data(png_ptr, (lang_key ? (png_const_bytep)lang_key : cbuf),
  1313. (png_size_t)(lang_key_len + 1));
  1314. png_write_compressed_data_out(png_ptr, &comp);
  1315. png_write_chunk_end(png_ptr);
  1316. png_free(png_ptr, new_key);
  1317. png_free(png_ptr, new_lang);
  1318. }
  1319. #endif
  1320. #ifdef PNG_WRITE_oFFs_SUPPORTED
  1321. /* Write the oFFs chunk */
  1322. void /* PRIVATE */
  1323. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  1324. int unit_type)
  1325. {
  1326. PNG_oFFs;
  1327. png_byte buf[9];
  1328. png_debug(1, "in png_write_oFFs");
  1329. if (unit_type >= PNG_OFFSET_LAST)
  1330. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  1331. png_save_int_32(buf, x_offset);
  1332. png_save_int_32(buf + 4, y_offset);
  1333. buf[8] = (png_byte)unit_type;
  1334. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  1335. }
  1336. #endif
  1337. #ifdef PNG_WRITE_pCAL_SUPPORTED
  1338. /* Write the pCAL chunk (described in the PNG extensions document) */
  1339. void /* PRIVATE */
  1340. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  1341. png_int_32 X1, int type, int nparams, png_const_charp units,
  1342. png_charpp params)
  1343. {
  1344. PNG_pCAL;
  1345. png_size_t purpose_len, units_len, total_len;
  1346. png_uint_32p params_len;
  1347. png_byte buf[10];
  1348. png_charp new_purpose;
  1349. int i;
  1350. png_debug1(1, "in png_write_pCAL (%d parameters)", nparams);
  1351. if (type >= PNG_EQUATION_LAST)
  1352. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  1353. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  1354. png_debug1(3, "pCAL purpose length = %d", (int)purpose_len);
  1355. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  1356. png_debug1(3, "pCAL units length = %d", (int)units_len);
  1357. total_len = purpose_len + units_len + 10;
  1358. params_len = (png_uint_32p)png_malloc(png_ptr,
  1359. (png_alloc_size_t)(nparams * png_sizeof(png_uint_32)));
  1360. /* Find the length of each parameter, making sure we don't count the
  1361. * null terminator for the last parameter.
  1362. */
  1363. for (i = 0; i < nparams; i++)
  1364. {
  1365. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  1366. png_debug2(3, "pCAL parameter %d length = %lu", i,
  1367. (unsigned long)params_len[i]);
  1368. total_len += (png_size_t)params_len[i];
  1369. }
  1370. png_debug1(3, "pCAL total length = %d", (int)total_len);
  1371. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  1372. png_write_chunk_data(png_ptr, (png_const_bytep)new_purpose,
  1373. (png_size_t)purpose_len);
  1374. png_save_int_32(buf, X0);
  1375. png_save_int_32(buf + 4, X1);
  1376. buf[8] = (png_byte)type;
  1377. buf[9] = (png_byte)nparams;
  1378. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  1379. png_write_chunk_data(png_ptr, (png_const_bytep)units, (png_size_t)units_len);
  1380. png_free(png_ptr, new_purpose);
  1381. for (i = 0; i < nparams; i++)
  1382. {
  1383. png_write_chunk_data(png_ptr, (png_const_bytep)params[i],
  1384. (png_size_t)params_len[i]);
  1385. }
  1386. png_free(png_ptr, params_len);
  1387. png_write_chunk_end(png_ptr);
  1388. }
  1389. #endif
  1390. #ifdef PNG_WRITE_sCAL_SUPPORTED
  1391. /* Write the sCAL chunk */
  1392. void /* PRIVATE */
  1393. png_write_sCAL_s(png_structp png_ptr, int unit, png_const_charp width,
  1394. png_const_charp height)
  1395. {
  1396. PNG_sCAL;
  1397. png_byte buf[64];
  1398. png_size_t wlen, hlen, total_len;
  1399. png_debug(1, "in png_write_sCAL_s");
  1400. wlen = png_strlen(width);
  1401. hlen = png_strlen(height);
  1402. total_len = wlen + hlen + 2;
  1403. if (total_len > 64)
  1404. {
  1405. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  1406. return;
  1407. }
  1408. buf[0] = (png_byte)unit;
  1409. png_memcpy(buf + 1, width, wlen + 1); /* Append the '\0' here */
  1410. png_memcpy(buf + wlen + 2, height, hlen); /* Do NOT append the '\0' here */
  1411. png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);
  1412. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  1413. }
  1414. #endif
  1415. #ifdef PNG_WRITE_pHYs_SUPPORTED
  1416. /* Write the pHYs chunk */
  1417. void /* PRIVATE */
  1418. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  1419. png_uint_32 y_pixels_per_unit,
  1420. int unit_type)
  1421. {
  1422. PNG_pHYs;
  1423. png_byte buf[9];
  1424. png_debug(1, "in png_write_pHYs");
  1425. if (unit_type >= PNG_RESOLUTION_LAST)
  1426. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  1427. png_save_uint_32(buf, x_pixels_per_unit);
  1428. png_save_uint_32(buf + 4, y_pixels_per_unit);
  1429. buf[8] = (png_byte)unit_type;
  1430. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  1431. }
  1432. #endif
  1433. #ifdef PNG_WRITE_tIME_SUPPORTED
  1434. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  1435. * or png_convert_from_time_t(), or fill in the structure yourself.
  1436. */
  1437. void /* PRIVATE */
  1438. png_write_tIME(png_structp png_ptr, png_const_timep mod_time)
  1439. {
  1440. PNG_tIME;
  1441. png_byte buf[7];
  1442. png_debug(1, "in png_write_tIME");
  1443. if (mod_time->month > 12 || mod_time->month < 1 ||
  1444. mod_time->day > 31 || mod_time->day < 1 ||
  1445. mod_time->hour > 23 || mod_time->second > 60)
  1446. {
  1447. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  1448. return;
  1449. }
  1450. png_save_uint_16(buf, mod_time->year);
  1451. buf[2] = mod_time->month;
  1452. buf[3] = mod_time->day;
  1453. buf[4] = mod_time->hour;
  1454. buf[5] = mod_time->minute;
  1455. buf[6] = mod_time->second;
  1456. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  1457. }
  1458. #endif
  1459. /* Initializes the row writing capability of libpng */
  1460. void /* PRIVATE */
  1461. png_write_start_row(png_structp png_ptr)
  1462. {
  1463. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  1464. /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  1465. /* Start of interlace block */
  1466. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  1467. /* Offset to next interlace block */
  1468. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  1469. /* Start of interlace block in the y direction */
  1470. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  1471. /* Offset to next interlace block in the y direction */
  1472. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  1473. #endif
  1474. png_size_t buf_size;
  1475. png_debug(1, "in png_write_start_row");
  1476. buf_size = (png_size_t)(PNG_ROWBYTES(
  1477. png_ptr->usr_channels*png_ptr->usr_bit_depth, png_ptr->width) + 1);
  1478. /* Set up row buffer */
  1479. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr,
  1480. (png_alloc_size_t)buf_size);
  1481. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  1482. #ifdef PNG_WRITE_FILTER_SUPPORTED
  1483. /* Set up filtering buffer, if using this filter */
  1484. if (png_ptr->do_filter & PNG_FILTER_SUB)
  1485. {
  1486. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr, png_ptr->rowbytes + 1);
  1487. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  1488. }
  1489. /* We only need to keep the previous row if we are using one of these. */
  1490. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  1491. {
  1492. /* Set up previous row buffer */
  1493. png_ptr->prev_row = (png_bytep)png_calloc(png_ptr,
  1494. (png_alloc_size_t)buf_size);
  1495. if (png_ptr->do_filter & PNG_FILTER_UP)
  1496. {
  1497. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  1498. png_ptr->rowbytes + 1);
  1499. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  1500. }
  1501. if (png_ptr->do_filter & PNG_FILTER_AVG)
  1502. {
  1503. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  1504. png_ptr->rowbytes + 1);
  1505. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  1506. }
  1507. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  1508. {
  1509. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  1510. png_ptr->rowbytes + 1);
  1511. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  1512. }
  1513. }
  1514. #endif /* PNG_WRITE_FILTER_SUPPORTED */
  1515. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  1516. /* If interlaced, we need to set up width and height of pass */
  1517. if (png_ptr->interlaced)
  1518. {
  1519. if (!(png_ptr->transformations & PNG_INTERLACE))
  1520. {
  1521. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  1522. png_pass_ystart[0]) / png_pass_yinc[0];
  1523. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  1524. png_pass_start[0]) / png_pass_inc[0];
  1525. }
  1526. else
  1527. {
  1528. png_ptr->num_rows = png_ptr->height;
  1529. png_ptr->usr_width = png_ptr->width;
  1530. }
  1531. }
  1532. else
  1533. #endif
  1534. {
  1535. png_ptr->num_rows = png_ptr->height;
  1536. png_ptr->usr_width = png_ptr->width;
  1537. }
  1538. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  1539. png_ptr->zstream.next_out = png_ptr->zbuf;
  1540. }
  1541. /* Internal use only. Called when finished processing a row of data. */
  1542. void /* PRIVATE */
  1543. png_write_finish_row(png_structp png_ptr)
  1544. {
  1545. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  1546. /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  1547. /* Start of interlace block */
  1548. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  1549. /* Offset to next interlace block */
  1550. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  1551. /* Start of interlace block in the y direction */
  1552. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  1553. /* Offset to next interlace block in the y direction */
  1554. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  1555. #endif
  1556. int ret;
  1557. png_debug(1, "in png_write_finish_row");
  1558. /* Next row */
  1559. png_ptr->row_number++;
  1560. /* See if we are done */
  1561. if (png_ptr->row_number < png_ptr->num_rows)
  1562. return;
  1563. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  1564. /* If interlaced, go to next pass */
  1565. if (png_ptr->interlaced)
  1566. {
  1567. png_ptr->row_number = 0;
  1568. if (png_ptr->transformations & PNG_INTERLACE)
  1569. {
  1570. png_ptr->pass++;
  1571. }
  1572. else
  1573. {
  1574. /* Loop until we find a non-zero width or height pass */
  1575. do
  1576. {
  1577. png_ptr->pass++;
  1578. if (png_ptr->pass >= 7)
  1579. break;
  1580. png_ptr->usr_width = (png_ptr->width +
  1581. png_pass_inc[png_ptr->pass] - 1 -
  1582. png_pass_start[png_ptr->pass]) /
  1583. png_pass_inc[png_ptr->pass];
  1584. png_ptr->num_rows = (png_ptr->height +
  1585. png_pass_yinc[png_ptr->pass] - 1 -
  1586. png_pass_ystart[png_ptr->pass]) /
  1587. png_pass_yinc[png_ptr->pass];
  1588. if (png_ptr->transformations & PNG_INTERLACE)
  1589. break;
  1590. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  1591. }
  1592. /* Reset the row above the image for the next pass */
  1593. if (png_ptr->pass < 7)
  1594. {
  1595. if (png_ptr->prev_row != NULL)
  1596. png_memset(png_ptr->prev_row, 0,
  1597. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  1598. png_ptr->usr_bit_depth, png_ptr->width)) + 1);
  1599. return;
  1600. }
  1601. }
  1602. #endif
  1603. /* If we get here, we've just written the last row, so we need
  1604. to flush the compressor */
  1605. do
  1606. {
  1607. /* Tell the compressor we are done */
  1608. ret = deflate(&png_ptr->zstream, Z_FINISH);
  1609. /* Check for an error */
  1610. if (ret == Z_OK)
  1611. {
  1612. /* Check to see if we need more room */
  1613. if (!(png_ptr->zstream.avail_out))
  1614. {
  1615. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  1616. png_ptr->zstream.next_out = png_ptr->zbuf;
  1617. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  1618. }
  1619. }
  1620. else if (ret != Z_STREAM_END)
  1621. {
  1622. if (png_ptr->zstream.msg != NULL)
  1623. png_error(png_ptr, png_ptr->zstream.msg);
  1624. else
  1625. png_error(png_ptr, "zlib error");
  1626. }
  1627. } while (ret != Z_STREAM_END);
  1628. /* Write any extra space */
  1629. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  1630. {
  1631. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  1632. png_ptr->zstream.avail_out);
  1633. }
  1634. deflateReset(&png_ptr->zstream);
  1635. png_ptr->zstream.data_type = Z_BINARY;
  1636. }
  1637. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  1638. /* Pick out the correct pixels for the interlace pass.
  1639. * The basic idea here is to go through the row with a source
  1640. * pointer and a destination pointer (sp and dp), and copy the
  1641. * correct pixels for the pass. As the row gets compacted,
  1642. * sp will always be >= dp, so we should never overwrite anything.
  1643. * See the default: case for the easiest code to understand.
  1644. */
  1645. void /* PRIVATE */
  1646. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  1647. {
  1648. /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  1649. /* Start of interlace block */
  1650. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  1651. /* Offset to next interlace block */
  1652. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  1653. png_debug(1, "in png_do_write_interlace");
  1654. /* We don't have to do anything on the last pass (6) */
  1655. if (pass < 6)
  1656. {
  1657. /* Each pixel depth is handled separately */
  1658. switch (row_info->pixel_depth)
  1659. {
  1660. case 1:
  1661. {
  1662. png_bytep sp;
  1663. png_bytep dp;
  1664. int shift;
  1665. int d;
  1666. int value;
  1667. png_uint_32 i;
  1668. png_uint_32 row_width = row_info->width;
  1669. dp = row;
  1670. d = 0;
  1671. shift = 7;
  1672. for (i = png_pass_start[pass]; i < row_width;
  1673. i += png_pass_inc[pass])
  1674. {
  1675. sp = row + (png_size_t)(i >> 3);
  1676. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  1677. d |= (value << shift);
  1678. if (shift == 0)
  1679. {
  1680. shift = 7;
  1681. *dp++ = (png_byte)d;
  1682. d = 0;
  1683. }
  1684. else
  1685. shift--;
  1686. }
  1687. if (shift != 7)
  1688. *dp = (png_byte)d;
  1689. break;
  1690. }
  1691. case 2:
  1692. {
  1693. png_bytep sp;
  1694. png_bytep dp;
  1695. int shift;
  1696. int d;
  1697. int value;
  1698. png_uint_32 i;
  1699. png_uint_32 row_width = row_info->width;
  1700. dp = row;
  1701. shift = 6;
  1702. d = 0;
  1703. for (i = png_pass_start[pass]; i < row_width;
  1704. i += png_pass_inc[pass])
  1705. {
  1706. sp = row + (png_size_t)(i >> 2);
  1707. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  1708. d |= (value << shift);
  1709. if (shift == 0)
  1710. {
  1711. shift = 6;
  1712. *dp++ = (png_byte)d;
  1713. d = 0;
  1714. }
  1715. else
  1716. shift -= 2;
  1717. }
  1718. if (shift != 6)
  1719. *dp = (png_byte)d;
  1720. break;
  1721. }
  1722. case 4:
  1723. {
  1724. png_bytep sp;
  1725. png_bytep dp;
  1726. int shift;
  1727. int d;
  1728. int value;
  1729. png_uint_32 i;
  1730. png_uint_32 row_width = row_info->width;
  1731. dp = row;
  1732. shift = 4;
  1733. d = 0;
  1734. for (i = png_pass_start[pass]; i < row_width;
  1735. i += png_pass_inc[pass])
  1736. {
  1737. sp = row + (png_size_t)(i >> 1);
  1738. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  1739. d |= (value << shift);
  1740. if (shift == 0)
  1741. {
  1742. shift = 4;
  1743. *dp++ = (png_byte)d;
  1744. d = 0;
  1745. }
  1746. else
  1747. shift -= 4;
  1748. }
  1749. if (shift != 4)
  1750. *dp = (png_byte)d;
  1751. break;
  1752. }
  1753. default:
  1754. {
  1755. png_bytep sp;
  1756. png_bytep dp;
  1757. png_uint_32 i;
  1758. png_uint_32 row_width = row_info->width;
  1759. png_size_t pixel_bytes;
  1760. /* Start at the beginning */
  1761. dp = row;
  1762. /* Find out how many bytes each pixel takes up */
  1763. pixel_bytes = (row_info->pixel_depth >> 3);
  1764. /* Loop through the row, only looking at the pixels that matter */
  1765. for (i = png_pass_start[pass]; i < row_width;
  1766. i += png_pass_inc[pass])
  1767. {
  1768. /* Find out where the original pixel is */
  1769. sp = row + (png_size_t)i * pixel_bytes;
  1770. /* Move the pixel */
  1771. if (dp != sp)
  1772. png_memcpy(dp, sp, pixel_bytes);
  1773. /* Next pixel */
  1774. dp += pixel_bytes;
  1775. }
  1776. break;
  1777. }
  1778. }
  1779. /* Set new row width */
  1780. row_info->width = (row_info->width +
  1781. png_pass_inc[pass] - 1 -
  1782. png_pass_start[pass]) /
  1783. png_pass_inc[pass];
  1784. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  1785. row_info->width);
  1786. }
  1787. }
  1788. #endif
  1789. /* This filters the row, chooses which filter to use, if it has not already
  1790. * been specified by the application, and then writes the row out with the
  1791. * chosen filter.
  1792. */
  1793. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  1794. #define PNG_HISHIFT 10
  1795. #define PNG_LOMASK ((png_uint_32)0xffffL)
  1796. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  1797. void /* PRIVATE */
  1798. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  1799. {
  1800. png_bytep best_row;
  1801. #ifdef PNG_WRITE_FILTER_SUPPORTED
  1802. png_bytep prev_row, row_buf;
  1803. png_uint_32 mins, bpp;
  1804. png_byte filter_to_do = png_ptr->do_filter;
  1805. png_size_t row_bytes = row_info->rowbytes;
  1806. #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  1807. int num_p_filters = (int)png_ptr->num_prev_filters;
  1808. #endif
  1809. png_debug(1, "in png_write_find_filter");
  1810. #ifndef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  1811. if (png_ptr->row_number == 0 && filter_to_do == PNG_ALL_FILTERS)
  1812. {
  1813. /* These will never be selected so we need not test them. */
  1814. filter_to_do &= ~(PNG_FILTER_UP | PNG_FILTER_PAETH);
  1815. }
  1816. #endif
  1817. /* Find out how many bytes offset each pixel is */
  1818. bpp = (row_info->pixel_depth + 7) >> 3;
  1819. prev_row = png_ptr->prev_row;
  1820. #endif
  1821. best_row = png_ptr->row_buf;
  1822. #ifdef PNG_WRITE_FILTER_SUPPORTED
  1823. row_buf = best_row;
  1824. mins = PNG_MAXSUM;
  1825. /* The prediction method we use is to find which method provides the
  1826. * smallest value when summing the absolute values of the distances
  1827. * from zero, using anything >= 128 as negative numbers. This is known
  1828. * as the "minimum sum of absolute differences" heuristic. Other
  1829. * heuristics are the "weighted minimum sum of absolute differences"
  1830. * (experimental and can in theory improve compression), and the "zlib
  1831. * predictive" method (not implemented yet), which does test compressions
  1832. * of lines using different filter methods, and then chooses the
  1833. * (series of) filter(s) that give minimum compressed data size (VERY
  1834. * computationally expensive).
  1835. *
  1836. * GRR 980525: consider also
  1837. *
  1838. * (1) minimum sum of absolute differences from running average (i.e.,
  1839. * keep running sum of non-absolute differences & count of bytes)
  1840. * [track dispersion, too? restart average if dispersion too large?]
  1841. *
  1842. * (1b) minimum sum of absolute differences from sliding average, probably
  1843. * with window size <= deflate window (usually 32K)
  1844. *
  1845. * (2) minimum sum of squared differences from zero or running average
  1846. * (i.e., ~ root-mean-square approach)
  1847. */
  1848. /* We don't need to test the 'no filter' case if this is the only filter
  1849. * that has been chosen, as it doesn't actually do anything to the data.
  1850. */
  1851. if ((filter_to_do & PNG_FILTER_NONE) && filter_to_do != PNG_FILTER_NONE)
  1852. {
  1853. png_bytep rp;
  1854. png_uint_32 sum = 0;
  1855. png_size_t i;
  1856. int v;
  1857. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  1858. {
  1859. v = *rp;
  1860. sum += (v < 128) ? v : 256 - v;
  1861. }
  1862. #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  1863. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  1864. {
  1865. png_uint_32 sumhi, sumlo;
  1866. int j;
  1867. sumlo = sum & PNG_LOMASK;
  1868. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  1869. /* Reduce the sum if we match any of the previous rows */
  1870. for (j = 0; j < num_p_filters; j++)
  1871. {
  1872. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  1873. {
  1874. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  1875. PNG_WEIGHT_SHIFT;
  1876. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  1877. PNG_WEIGHT_SHIFT;
  1878. }
  1879. }
  1880. /* Factor in the cost of this filter (this is here for completeness,
  1881. * but it makes no sense to have a "cost" for the NONE filter, as
  1882. * it has the minimum possible computational cost - none).
  1883. */
  1884. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  1885. PNG_COST_SHIFT;
  1886. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  1887. PNG_COST_SHIFT;
  1888. if (sumhi > PNG_HIMASK)
  1889. sum = PNG_MAXSUM;
  1890. else
  1891. sum = (sumhi << PNG_HISHIFT) + sumlo;
  1892. }
  1893. #endif
  1894. mins = sum;
  1895. }
  1896. /* Sub filter */
  1897. if (filter_to_do == PNG_FILTER_SUB)
  1898. /* It's the only filter so no testing is needed */
  1899. {
  1900. png_bytep rp, lp, dp;
  1901. png_size_t i;
  1902. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  1903. i++, rp++, dp++)
  1904. {
  1905. *dp = *rp;
  1906. }
  1907. for (lp = row_buf + 1; i < row_bytes;
  1908. i++, rp++, lp++, dp++)
  1909. {
  1910. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  1911. }
  1912. best_row = png_ptr->sub_row;
  1913. }
  1914. else if (filter_to_do & PNG_FILTER_SUB)
  1915. {
  1916. png_bytep rp, dp, lp;
  1917. png_uint_32 sum = 0, lmins = mins;
  1918. png_size_t i;
  1919. int v;
  1920. #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  1921. /* We temporarily increase the "minimum sum" by the factor we
  1922. * would reduce the sum of this filter, so that we can do the
  1923. * early exit comparison without scaling the sum each time.
  1924. */
  1925. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  1926. {
  1927. int j;
  1928. png_uint_32 lmhi, lmlo;
  1929. lmlo = lmins & PNG_LOMASK;
  1930. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  1931. for (j = 0; j < num_p_filters; j++)
  1932. {
  1933. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  1934. {
  1935. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  1936. PNG_WEIGHT_SHIFT;
  1937. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  1938. PNG_WEIGHT_SHIFT;
  1939. }
  1940. }
  1941. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  1942. PNG_COST_SHIFT;
  1943. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  1944. PNG_COST_SHIFT;
  1945. if (lmhi > PNG_HIMASK)
  1946. lmins = PNG_MAXSUM;
  1947. else
  1948. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  1949. }
  1950. #endif
  1951. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  1952. i++, rp++, dp++)
  1953. {
  1954. v = *dp = *rp;
  1955. sum += (v < 128) ? v : 256 - v;
  1956. }
  1957. for (lp = row_buf + 1; i < row_bytes;
  1958. i++, rp++, lp++, dp++)
  1959. {
  1960. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  1961. sum += (v < 128) ? v : 256 - v;
  1962. if (sum > lmins) /* We are already worse, don't continue. */
  1963. break;
  1964. }
  1965. #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  1966. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  1967. {
  1968. int j;
  1969. png_uint_32 sumhi, sumlo;
  1970. sumlo = sum & PNG_LOMASK;
  1971. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  1972. for (j = 0; j < num_p_filters; j++)
  1973. {
  1974. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  1975. {
  1976. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  1977. PNG_WEIGHT_SHIFT;
  1978. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  1979. PNG_WEIGHT_SHIFT;
  1980. }
  1981. }
  1982. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  1983. PNG_COST_SHIFT;
  1984. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  1985. PNG_COST_SHIFT;
  1986. if (sumhi > PNG_HIMASK)
  1987. sum = PNG_MAXSUM;
  1988. else
  1989. sum = (sumhi << PNG_HISHIFT) + sumlo;
  1990. }
  1991. #endif
  1992. if (sum < mins)
  1993. {
  1994. mins = sum;
  1995. best_row = png_ptr->sub_row;
  1996. }
  1997. }
  1998. /* Up filter */
  1999. if (filter_to_do == PNG_FILTER_UP)
  2000. {
  2001. png_bytep rp, dp, pp;
  2002. png_size_t i;
  2003. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  2004. pp = prev_row + 1; i < row_bytes;
  2005. i++, rp++, pp++, dp++)
  2006. {
  2007. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  2008. }
  2009. best_row = png_ptr->up_row;
  2010. }
  2011. else if (filter_to_do & PNG_FILTER_UP)
  2012. {
  2013. png_bytep rp, dp, pp;
  2014. png_uint_32 sum = 0, lmins = mins;
  2015. png_size_t i;
  2016. int v;
  2017. #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  2018. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  2019. {
  2020. int j;
  2021. png_uint_32 lmhi, lmlo;
  2022. lmlo = lmins & PNG_LOMASK;
  2023. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  2024. for (j = 0; j < num_p_filters; j++)
  2025. {
  2026. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  2027. {
  2028. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  2029. PNG_WEIGHT_SHIFT;
  2030. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  2031. PNG_WEIGHT_SHIFT;
  2032. }
  2033. }
  2034. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  2035. PNG_COST_SHIFT;
  2036. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  2037. PNG_COST_SHIFT;
  2038. if (lmhi > PNG_HIMASK)
  2039. lmins = PNG_MAXSUM;
  2040. else
  2041. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  2042. }
  2043. #endif
  2044. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  2045. pp = prev_row + 1; i < row_bytes; i++)
  2046. {
  2047. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  2048. sum += (v < 128) ? v : 256 - v;
  2049. if (sum > lmins) /* We are already worse, don't continue. */
  2050. break;
  2051. }
  2052. #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  2053. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  2054. {
  2055. int j;
  2056. png_uint_32 sumhi, sumlo;
  2057. sumlo = sum & PNG_LOMASK;
  2058. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  2059. for (j = 0; j < num_p_filters; j++)
  2060. {
  2061. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  2062. {
  2063. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  2064. PNG_WEIGHT_SHIFT;
  2065. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  2066. PNG_WEIGHT_SHIFT;
  2067. }
  2068. }
  2069. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  2070. PNG_COST_SHIFT;
  2071. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  2072. PNG_COST_SHIFT;
  2073. if (sumhi > PNG_HIMASK)
  2074. sum = PNG_MAXSUM;
  2075. else
  2076. sum = (sumhi << PNG_HISHIFT) + sumlo;
  2077. }
  2078. #endif
  2079. if (sum < mins)
  2080. {
  2081. mins = sum;
  2082. best_row = png_ptr->up_row;
  2083. }
  2084. }
  2085. /* Avg filter */
  2086. if (filter_to_do == PNG_FILTER_AVG)
  2087. {
  2088. png_bytep rp, dp, pp, lp;
  2089. png_uint_32 i;
  2090. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  2091. pp = prev_row + 1; i < bpp; i++)
  2092. {
  2093. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  2094. }
  2095. for (lp = row_buf + 1; i < row_bytes; i++)
  2096. {
  2097. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  2098. & 0xff);
  2099. }
  2100. best_row = png_ptr->avg_row;
  2101. }
  2102. else if (filter_to_do & PNG_FILTER_AVG)
  2103. {
  2104. png_bytep rp, dp, pp, lp;
  2105. png_uint_32 sum = 0, lmins = mins;
  2106. png_size_t i;
  2107. int v;
  2108. #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  2109. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  2110. {
  2111. int j;
  2112. png_uint_32 lmhi, lmlo;
  2113. lmlo = lmins & PNG_LOMASK;
  2114. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  2115. for (j = 0; j < num_p_filters; j++)
  2116. {
  2117. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  2118. {
  2119. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  2120. PNG_WEIGHT_SHIFT;
  2121. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  2122. PNG_WEIGHT_SHIFT;
  2123. }
  2124. }
  2125. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  2126. PNG_COST_SHIFT;
  2127. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  2128. PNG_COST_SHIFT;
  2129. if (lmhi > PNG_HIMASK)
  2130. lmins = PNG_MAXSUM;
  2131. else
  2132. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  2133. }
  2134. #endif
  2135. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  2136. pp = prev_row + 1; i < bpp; i++)
  2137. {
  2138. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  2139. sum += (v < 128) ? v : 256 - v;
  2140. }
  2141. for (lp = row_buf + 1; i < row_bytes; i++)
  2142. {
  2143. v = *dp++ =
  2144. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  2145. sum += (v < 128) ? v : 256 - v;
  2146. if (sum > lmins) /* We are already worse, don't continue. */
  2147. break;
  2148. }
  2149. #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  2150. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  2151. {
  2152. int j;
  2153. png_uint_32 sumhi, sumlo;
  2154. sumlo = sum & PNG_LOMASK;
  2155. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  2156. for (j = 0; j < num_p_filters; j++)
  2157. {
  2158. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  2159. {
  2160. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  2161. PNG_WEIGHT_SHIFT;
  2162. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  2163. PNG_WEIGHT_SHIFT;
  2164. }
  2165. }
  2166. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  2167. PNG_COST_SHIFT;
  2168. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  2169. PNG_COST_SHIFT;
  2170. if (sumhi > PNG_HIMASK)
  2171. sum = PNG_MAXSUM;
  2172. else
  2173. sum = (sumhi << PNG_HISHIFT) + sumlo;
  2174. }
  2175. #endif
  2176. if (sum < mins)
  2177. {
  2178. mins = sum;
  2179. best_row = png_ptr->avg_row;
  2180. }
  2181. }
  2182. /* Paeth filter */
  2183. if (filter_to_do == PNG_FILTER_PAETH)
  2184. {
  2185. png_bytep rp, dp, pp, cp, lp;
  2186. png_size_t i;
  2187. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  2188. pp = prev_row + 1; i < bpp; i++)
  2189. {
  2190. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  2191. }
  2192. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  2193. {
  2194. int a, b, c, pa, pb, pc, p;
  2195. b = *pp++;
  2196. c = *cp++;
  2197. a = *lp++;
  2198. p = b - c;
  2199. pc = a - c;
  2200. #ifdef PNG_USE_ABS
  2201. pa = abs(p);
  2202. pb = abs(pc);
  2203. pc = abs(p + pc);
  2204. #else
  2205. pa = p < 0 ? -p : p;
  2206. pb = pc < 0 ? -pc : pc;
  2207. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  2208. #endif
  2209. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  2210. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  2211. }
  2212. best_row = png_ptr->paeth_row;
  2213. }
  2214. else if (filter_to_do & PNG_FILTER_PAETH)
  2215. {
  2216. png_bytep rp, dp, pp, cp, lp;
  2217. png_uint_32 sum = 0, lmins = mins;
  2218. png_size_t i;
  2219. int v;
  2220. #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  2221. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  2222. {
  2223. int j;
  2224. png_uint_32 lmhi, lmlo;
  2225. lmlo = lmins & PNG_LOMASK;
  2226. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  2227. for (j = 0; j < num_p_filters; j++)
  2228. {
  2229. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  2230. {
  2231. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  2232. PNG_WEIGHT_SHIFT;
  2233. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  2234. PNG_WEIGHT_SHIFT;
  2235. }
  2236. }
  2237. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  2238. PNG_COST_SHIFT;
  2239. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  2240. PNG_COST_SHIFT;
  2241. if (lmhi > PNG_HIMASK)
  2242. lmins = PNG_MAXSUM;
  2243. else
  2244. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  2245. }
  2246. #endif
  2247. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  2248. pp = prev_row + 1; i < bpp; i++)
  2249. {
  2250. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  2251. sum += (v < 128) ? v : 256 - v;
  2252. }
  2253. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  2254. {
  2255. int a, b, c, pa, pb, pc, p;
  2256. b = *pp++;
  2257. c = *cp++;
  2258. a = *lp++;
  2259. #ifndef PNG_SLOW_PAETH
  2260. p = b - c;
  2261. pc = a - c;
  2262. #ifdef PNG_USE_ABS
  2263. pa = abs(p);
  2264. pb = abs(pc);
  2265. pc = abs(p + pc);
  2266. #else
  2267. pa = p < 0 ? -p : p;
  2268. pb = pc < 0 ? -pc : pc;
  2269. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  2270. #endif
  2271. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  2272. #else /* PNG_SLOW_PAETH */
  2273. p = a + b - c;
  2274. pa = abs(p - a);
  2275. pb = abs(p - b);
  2276. pc = abs(p - c);
  2277. if (pa <= pb && pa <= pc)
  2278. p = a;
  2279. else if (pb <= pc)
  2280. p = b;
  2281. else
  2282. p = c;
  2283. #endif /* PNG_SLOW_PAETH */
  2284. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  2285. sum += (v < 128) ? v : 256 - v;
  2286. if (sum > lmins) /* We are already worse, don't continue. */
  2287. break;
  2288. }
  2289. #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  2290. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  2291. {
  2292. int j;
  2293. png_uint_32 sumhi, sumlo;
  2294. sumlo = sum & PNG_LOMASK;
  2295. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  2296. for (j = 0; j < num_p_filters; j++)
  2297. {
  2298. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  2299. {
  2300. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  2301. PNG_WEIGHT_SHIFT;
  2302. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  2303. PNG_WEIGHT_SHIFT;
  2304. }
  2305. }
  2306. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  2307. PNG_COST_SHIFT;
  2308. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  2309. PNG_COST_SHIFT;
  2310. if (sumhi > PNG_HIMASK)
  2311. sum = PNG_MAXSUM;
  2312. else
  2313. sum = (sumhi << PNG_HISHIFT) + sumlo;
  2314. }
  2315. #endif
  2316. if (sum < mins)
  2317. {
  2318. best_row = png_ptr->paeth_row;
  2319. }
  2320. }
  2321. #endif /* PNG_WRITE_FILTER_SUPPORTED */
  2322. /* Do the actual writing of the filtered row data from the chosen filter. */
  2323. png_write_filtered_row(png_ptr, best_row);
  2324. #ifdef PNG_WRITE_FILTER_SUPPORTED
  2325. #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  2326. /* Save the type of filter we picked this time for future calculations */
  2327. if (png_ptr->num_prev_filters > 0)
  2328. {
  2329. int j;
  2330. for (j = 1; j < num_p_filters; j++)
  2331. {
  2332. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  2333. }
  2334. png_ptr->prev_filters[j] = best_row[0];
  2335. }
  2336. #endif
  2337. #endif /* PNG_WRITE_FILTER_SUPPORTED */
  2338. }
  2339. /* Do the actual writing of a previously filtered row. */
  2340. void /* PRIVATE */
  2341. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  2342. {
  2343. png_size_t avail;
  2344. png_debug(1, "in png_write_filtered_row");
  2345. png_debug1(2, "filter = %d", filtered_row[0]);
  2346. /* Set up the zlib input buffer */
  2347. png_ptr->zstream.next_in = filtered_row;
  2348. png_ptr->zstream.avail_in = 0;
  2349. avail = png_ptr->row_info.rowbytes + 1;
  2350. /* Repeat until we have compressed all the data */
  2351. do
  2352. {
  2353. int ret; /* Return of zlib */
  2354. /* Record the number of bytes available - zlib supports at least 65535
  2355. * bytes at one step, depending on the size of the zlib type 'uInt', the
  2356. * maximum size zlib can write at once is ZLIB_IO_MAX (from pngpriv.h).
  2357. * Use this because on 16 bit systems 'rowbytes' can be up to 65536 (i.e.
  2358. * one more than 16 bits) and, in this case 'rowbytes+1' can overflow a
  2359. * uInt. ZLIB_IO_MAX can be safely reduced to cause zlib to be called
  2360. * with smaller chunks of data.
  2361. */
  2362. if (png_ptr->zstream.avail_in == 0)
  2363. {
  2364. if (avail > ZLIB_IO_MAX)
  2365. {
  2366. png_ptr->zstream.avail_in = ZLIB_IO_MAX;
  2367. avail -= ZLIB_IO_MAX;
  2368. }
  2369. else
  2370. {
  2371. /* So this will fit in the available uInt space: */
  2372. png_ptr->zstream.avail_in = (uInt)avail;
  2373. avail = 0;
  2374. }
  2375. }
  2376. /* Compress the data */
  2377. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  2378. /* Check for compression errors */
  2379. if (ret != Z_OK)
  2380. {
  2381. if (png_ptr->zstream.msg != NULL)
  2382. png_error(png_ptr, png_ptr->zstream.msg);
  2383. else
  2384. png_error(png_ptr, "zlib error");
  2385. }
  2386. /* See if it is time to write another IDAT */
  2387. if (!(png_ptr->zstream.avail_out))
  2388. {
  2389. /* Write the IDAT and reset the zlib output buffer */
  2390. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  2391. png_ptr->zstream.next_out = png_ptr->zbuf;
  2392. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  2393. }
  2394. /* Repeat until all data has been compressed */
  2395. } while (avail > 0 || png_ptr->zstream.avail_in > 0);
  2396. /* Swap the current and previous rows */
  2397. if (png_ptr->prev_row != NULL)
  2398. {
  2399. png_bytep tptr;
  2400. tptr = png_ptr->prev_row;
  2401. png_ptr->prev_row = png_ptr->row_buf;
  2402. png_ptr->row_buf = tptr;
  2403. }
  2404. /* Finish row - updates counters and flushes zlib if last row */
  2405. png_write_finish_row(png_ptr);
  2406. #ifdef PNG_WRITE_FLUSH_SUPPORTED
  2407. png_ptr->flush_rows++;
  2408. if (png_ptr->flush_dist > 0 &&
  2409. png_ptr->flush_rows >= png_ptr->flush_dist)
  2410. {
  2411. png_write_flush(png_ptr);
  2412. }
  2413. #endif
  2414. }
  2415. #endif /* PNG_WRITE_SUPPORTED */