Audio plugin host https://kx.studio/carla
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.

3021 lines
90KB

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