2 /* pngwutil.c - utilities to write a PNG file
4 * Last changed in libpng 1.4.0 [January 3, 2010]
5 * Copyright (c) 1998-2010 Glenn Randers-Pehrson
6 * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
7 * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
9 * This code is released under the libpng license.
10 * For conditions of distribution and use, see the disclaimer
11 * and license in png.h
14 #define PNG_NO_PEDANTIC_WARNINGS
16 #ifdef PNG_WRITE_SUPPORTED
19 /* Place a 32-bit number into a buffer in PNG byte order. We work
20 * with unsigned numbers for convenience, although one supported
21 * ancillary chunk uses signed (two's complement) numbers.
24 png_save_uint_32(png_bytep buf, png_uint_32 i)
26 buf[0] = (png_byte)((i >> 24) & 0xff);
27 buf[1] = (png_byte)((i >> 16) & 0xff);
28 buf[2] = (png_byte)((i >> 8) & 0xff);
29 buf[3] = (png_byte)(i & 0xff);
32 #ifdef PNG_SAVE_INT_32_SUPPORTED
33 /* The png_save_int_32 function assumes integers are stored in two's
34 * complement format. If this isn't the case, then this routine needs to
35 * be modified to write data in two's complement format.
38 png_save_int_32(png_bytep buf, png_int_32 i)
40 buf[0] = (png_byte)((i >> 24) & 0xff);
41 buf[1] = (png_byte)((i >> 16) & 0xff);
42 buf[2] = (png_byte)((i >> 8) & 0xff);
43 buf[3] = (png_byte)(i & 0xff);
47 /* Place a 16-bit number into a buffer in PNG byte order.
48 * The parameter is declared unsigned int, not png_uint_16,
49 * just to avoid potential problems on pre-ANSI C compilers.
52 png_save_uint_16(png_bytep buf, unsigned int i)
54 buf[0] = (png_byte)((i >> 8) & 0xff);
55 buf[1] = (png_byte)(i & 0xff);
58 /* Simple function to write the signature. If we have already written
59 * the magic bytes of the signature, or more likely, the PNG stream is
60 * being embedded into another stream and doesn't need its own signature,
61 * we should call png_set_sig_bytes() to tell libpng how many of the
62 * bytes have already been written.
65 png_write_sig(png_structp png_ptr)
67 png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
69 #ifdef PNG_IO_STATE_SUPPORTED
70 /* Inform the I/O callback that the signature is being written */
71 png_ptr->io_state = PNG_IO_WRITING | PNG_IO_SIGNATURE;
74 /* Write the rest of the 8 byte signature */
75 png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
76 (png_size_t)(8 - png_ptr->sig_bytes));
77 if (png_ptr->sig_bytes < 3)
78 png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
81 /* Write a PNG chunk all at once. The type is an array of ASCII characters
82 * representing the chunk name. The array must be at least 4 bytes in
83 * length, and does not need to be null terminated. To be safe, pass the
84 * pre-defined chunk names here, and if you need a new one, define it
85 * where the others are defined. The length is the length of the data.
86 * All the data must be present. If that is not possible, use the
87 * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
91 png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
92 png_bytep data, png_size_t length)
96 png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
97 png_write_chunk_data(png_ptr, data, (png_size_t)length);
98 png_write_chunk_end(png_ptr);
101 /* Write the start of a PNG chunk. The type is the chunk type.
102 * The total_length is the sum of the lengths of all the data you will be
103 * passing in png_write_chunk_data().
106 png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
111 png_debug2(0, "Writing %s chunk, length = %lu", chunk_name,
112 (unsigned long)length);
117 #ifdef PNG_IO_STATE_SUPPORTED
118 /* Inform the I/O callback that the chunk header is being written.
119 * PNG_IO_CHUNK_HDR requires a single I/O call.
121 png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_HDR;
124 /* Write the length and the chunk name */
125 png_save_uint_32(buf, length);
126 png_memcpy(buf + 4, chunk_name, 4);
127 png_write_data(png_ptr, buf, (png_size_t)8);
128 /* Put the chunk name into png_ptr->chunk_name */
129 png_memcpy(png_ptr->chunk_name, chunk_name, 4);
130 /* Reset the crc and run it over the chunk name */
131 png_reset_crc(png_ptr);
132 png_calculate_crc(png_ptr, chunk_name, 4);
134 #ifdef PNG_IO_STATE_SUPPORTED
135 /* Inform the I/O callback that chunk data will (possibly) be written.
136 * PNG_IO_CHUNK_DATA does NOT require a specific number of I/O calls.
138 png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_DATA;
142 /* Write the data of a PNG chunk started with png_write_chunk_start().
143 * Note that multiple calls to this function are allowed, and that the
144 * sum of the lengths from these calls *must* add up to the total_length
145 * given to png_write_chunk_start().
148 png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
150 /* Write the data, and run the CRC over it */
153 if (data != NULL && length > 0)
155 png_write_data(png_ptr, data, length);
156 /* Update the CRC after writing the data,
157 * in case that the user I/O routine alters it.
159 png_calculate_crc(png_ptr, data, length);
163 /* Finish a chunk started with png_write_chunk_start(). */
165 png_write_chunk_end(png_structp png_ptr)
169 if (png_ptr == NULL) return;
171 #ifdef PNG_IO_STATE_SUPPORTED
172 /* Inform the I/O callback that the chunk CRC is being written.
173 * PNG_IO_CHUNK_CRC requires a single I/O function call.
175 png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_CRC;
178 /* Write the crc in a single operation */
179 png_save_uint_32(buf, png_ptr->crc);
181 png_write_data(png_ptr, buf, (png_size_t)4);
184 #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
185 /* This pair of functions encapsulates the operation of (a) compressing a
186 * text string, and (b) issuing it later as a series of chunk data writes.
187 * The compression_state structure is shared context for these functions
188 * set up by the caller in order to make the whole mess thread-safe.
193 char *input; /* The uncompressed input data */
194 int input_len; /* Its length */
195 int num_output_ptr; /* Number of output pointers used */
196 int max_output_ptr; /* Size of output_ptr */
197 png_charpp output_ptr; /* Array of pointers to output */
200 /* Compress given text into storage in the png_ptr structure */
201 static int /* PRIVATE */
202 png_text_compress(png_structp png_ptr,
203 png_charp text, png_size_t text_len, int compression,
204 compression_state *comp)
208 comp->num_output_ptr = 0;
209 comp->max_output_ptr = 0;
210 comp->output_ptr = NULL;
214 /* We may just want to pass the text right through */
215 if (compression == PNG_TEXT_COMPRESSION_NONE)
218 comp->input_len = text_len;
219 return((int)text_len);
222 if (compression >= PNG_TEXT_COMPRESSION_LAST)
224 #ifdef PNG_STDIO_SUPPORTED
226 png_snprintf(msg, 50, "Unknown compression type %d", compression);
227 png_warning(png_ptr, msg);
229 png_warning(png_ptr, "Unknown compression type");
233 /* We can't write the chunk until we find out how much data we have,
234 * which means we need to run the compressor first and save the
235 * output. This shouldn't be a problem, as the vast majority of
236 * comments should be reasonable, but we will set up an array of
237 * malloc'd pointers to be sure.
239 * If we knew the application was well behaved, we could simplify this
240 * greatly by assuming we can always malloc an output buffer large
241 * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
242 * and malloc this directly. The only time this would be a bad idea is
243 * if we can't malloc more than 64K and we have 64K of random input
244 * data, or if the input string is incredibly large (although this
245 * wouldn't cause a failure, just a slowdown due to swapping).
248 /* Set up the compression buffers */
249 png_ptr->zstream.avail_in = (uInt)text_len;
250 png_ptr->zstream.next_in = (Bytef *)text;
251 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
252 png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
254 /* This is the same compression loop as in png_write_row() */
257 /* Compress the data */
258 ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
262 if (png_ptr->zstream.msg != NULL)
263 png_error(png_ptr, png_ptr->zstream.msg);
265 png_error(png_ptr, "zlib error");
267 /* Check to see if we need more room */
268 if (!(png_ptr->zstream.avail_out))
270 /* Make sure the output array has room */
271 if (comp->num_output_ptr >= comp->max_output_ptr)
275 old_max = comp->max_output_ptr;
276 comp->max_output_ptr = comp->num_output_ptr + 4;
277 if (comp->output_ptr != NULL)
281 old_ptr = comp->output_ptr;
282 comp->output_ptr = (png_charpp)png_malloc(png_ptr,
284 (comp->max_output_ptr * png_sizeof(png_charpp)));
285 png_memcpy(comp->output_ptr, old_ptr, old_max
286 * png_sizeof(png_charp));
287 png_free(png_ptr, old_ptr);
290 comp->output_ptr = (png_charpp)png_malloc(png_ptr,
292 (comp->max_output_ptr * png_sizeof(png_charp)));
296 comp->output_ptr[comp->num_output_ptr] =
297 (png_charp)png_malloc(png_ptr,
298 (png_alloc_size_t)png_ptr->zbuf_size);
299 png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
301 comp->num_output_ptr++;
303 /* and reset the buffer */
304 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
305 png_ptr->zstream.next_out = png_ptr->zbuf;
307 /* Continue until we don't have any more to compress */
308 } while (png_ptr->zstream.avail_in);
310 /* Finish the compression */
313 /* Tell zlib we are finished */
314 ret = deflate(&png_ptr->zstream, Z_FINISH);
318 /* Check to see if we need more room */
319 if (!(png_ptr->zstream.avail_out))
321 /* Check to make sure our output array has room */
322 if (comp->num_output_ptr >= comp->max_output_ptr)
326 old_max = comp->max_output_ptr;
327 comp->max_output_ptr = comp->num_output_ptr + 4;
328 if (comp->output_ptr != NULL)
332 old_ptr = comp->output_ptr;
333 /* This could be optimized to realloc() */
334 comp->output_ptr = (png_charpp)png_malloc(png_ptr,
335 (png_alloc_size_t)(comp->max_output_ptr *
336 png_sizeof(png_charp)));
337 png_memcpy(comp->output_ptr, old_ptr,
338 old_max * png_sizeof(png_charp));
339 png_free(png_ptr, old_ptr);
342 comp->output_ptr = (png_charpp)png_malloc(png_ptr,
343 (png_alloc_size_t)(comp->max_output_ptr *
344 png_sizeof(png_charp)));
348 comp->output_ptr[comp->num_output_ptr] =
349 (png_charp)png_malloc(png_ptr,
350 (png_alloc_size_t)png_ptr->zbuf_size);
351 png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
353 comp->num_output_ptr++;
355 /* and reset the buffer pointers */
356 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
357 png_ptr->zstream.next_out = png_ptr->zbuf;
360 else if (ret != Z_STREAM_END)
362 /* We got an error */
363 if (png_ptr->zstream.msg != NULL)
364 png_error(png_ptr, png_ptr->zstream.msg);
366 png_error(png_ptr, "zlib error");
368 } while (ret != Z_STREAM_END);
370 /* Text length is number of buffers plus last buffer */
371 text_len = png_ptr->zbuf_size * comp->num_output_ptr;
372 if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
373 text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
375 return((int)text_len);
378 /* Ship the compressed text out via chunk writes */
379 static void /* PRIVATE */
380 png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
384 /* Handle the no-compression case */
387 png_write_chunk_data(png_ptr, (png_bytep)comp->input,
388 (png_size_t)comp->input_len);
392 /* Write saved output buffers, if any */
393 for (i = 0; i < comp->num_output_ptr; i++)
395 png_write_chunk_data(png_ptr, (png_bytep)comp->output_ptr[i],
396 (png_size_t)png_ptr->zbuf_size);
397 png_free(png_ptr, comp->output_ptr[i]);
399 if (comp->max_output_ptr != 0)
400 png_free(png_ptr, comp->output_ptr);
401 /* Write anything left in zbuf */
402 if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
403 png_write_chunk_data(png_ptr, png_ptr->zbuf,
404 (png_size_t)(png_ptr->zbuf_size - png_ptr->zstream.avail_out));
406 /* Reset zlib for another zTXt/iTXt or image data */
407 deflateReset(&png_ptr->zstream);
408 png_ptr->zstream.data_type = Z_BINARY;
412 /* Write the IHDR chunk, and update the png_struct with the necessary
413 * information. Note that the rest of this code depends upon this
414 * information being correct.
417 png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
418 int bit_depth, int color_type, int compression_type, int filter_type,
424 png_byte buf[13]; /* Buffer to store the IHDR info */
426 png_debug(1, "in png_write_IHDR");
428 /* Check that we have valid input data from the application info */
431 case PNG_COLOR_TYPE_GRAY:
438 case 16: png_ptr->channels = 1; break;
439 default: png_error(png_ptr, "Invalid bit depth for grayscale image");
442 case PNG_COLOR_TYPE_RGB:
443 if (bit_depth != 8 && bit_depth != 16)
444 png_error(png_ptr, "Invalid bit depth for RGB image");
445 png_ptr->channels = 3;
447 case PNG_COLOR_TYPE_PALETTE:
453 case 8: png_ptr->channels = 1; break;
454 default: png_error(png_ptr, "Invalid bit depth for paletted image");
457 case PNG_COLOR_TYPE_GRAY_ALPHA:
458 if (bit_depth != 8 && bit_depth != 16)
459 png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
460 png_ptr->channels = 2;
462 case PNG_COLOR_TYPE_RGB_ALPHA:
463 if (bit_depth != 8 && bit_depth != 16)
464 png_error(png_ptr, "Invalid bit depth for RGBA image");
465 png_ptr->channels = 4;
468 png_error(png_ptr, "Invalid image color type specified");
471 if (compression_type != PNG_COMPRESSION_TYPE_BASE)
473 png_warning(png_ptr, "Invalid compression type specified");
474 compression_type = PNG_COMPRESSION_TYPE_BASE;
477 /* Write filter_method 64 (intrapixel differencing) only if
478 * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
479 * 2. Libpng did not write a PNG signature (this filter_method is only
480 * used in PNG datastreams that are embedded in MNG datastreams) and
481 * 3. The application called png_permit_mng_features with a mask that
482 * included PNG_FLAG_MNG_FILTER_64 and
483 * 4. The filter_method is 64 and
484 * 5. The color_type is RGB or RGBA
487 #ifdef PNG_MNG_FEATURES_SUPPORTED
488 !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
489 ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
490 (color_type == PNG_COLOR_TYPE_RGB ||
491 color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
492 (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
494 filter_type != PNG_FILTER_TYPE_BASE)
496 png_warning(png_ptr, "Invalid filter type specified");
497 filter_type = PNG_FILTER_TYPE_BASE;
500 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
501 if (interlace_type != PNG_INTERLACE_NONE &&
502 interlace_type != PNG_INTERLACE_ADAM7)
504 png_warning(png_ptr, "Invalid interlace type specified");
505 interlace_type = PNG_INTERLACE_ADAM7;
508 interlace_type=PNG_INTERLACE_NONE;
511 /* Save the relevent information */
512 png_ptr->bit_depth = (png_byte)bit_depth;
513 png_ptr->color_type = (png_byte)color_type;
514 png_ptr->interlaced = (png_byte)interlace_type;
515 #ifdef PNG_MNG_FEATURES_SUPPORTED
516 png_ptr->filter_type = (png_byte)filter_type;
518 png_ptr->compression_type = (png_byte)compression_type;
519 png_ptr->width = width;
520 png_ptr->height = height;
522 png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
523 png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
524 /* Set the usr info, so any transformations can modify it */
525 png_ptr->usr_width = png_ptr->width;
526 png_ptr->usr_bit_depth = png_ptr->bit_depth;
527 png_ptr->usr_channels = png_ptr->channels;
529 /* Pack the header information into the buffer */
530 png_save_uint_32(buf, width);
531 png_save_uint_32(buf + 4, height);
532 buf[8] = (png_byte)bit_depth;
533 buf[9] = (png_byte)color_type;
534 buf[10] = (png_byte)compression_type;
535 buf[11] = (png_byte)filter_type;
536 buf[12] = (png_byte)interlace_type;
538 /* Write the chunk */
539 png_write_chunk(png_ptr, (png_bytep)png_IHDR, buf, (png_size_t)13);
541 /* Initialize zlib with PNG info */
542 png_ptr->zstream.zalloc = png_zalloc;
543 png_ptr->zstream.zfree = png_zfree;
544 png_ptr->zstream.opaque = (voidpf)png_ptr;
545 if (!(png_ptr->do_filter))
547 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
548 png_ptr->bit_depth < 8)
549 png_ptr->do_filter = PNG_FILTER_NONE;
551 png_ptr->do_filter = PNG_ALL_FILTERS;
553 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
555 if (png_ptr->do_filter != PNG_FILTER_NONE)
556 png_ptr->zlib_strategy = Z_FILTERED;
558 png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
560 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
561 png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
562 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
563 png_ptr->zlib_mem_level = 8;
564 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
565 png_ptr->zlib_window_bits = 15;
566 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
567 png_ptr->zlib_method = 8;
568 ret = deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
569 png_ptr->zlib_method, png_ptr->zlib_window_bits,
570 png_ptr->zlib_mem_level, png_ptr->zlib_strategy);
573 if (ret == Z_VERSION_ERROR) png_error(png_ptr,
574 "zlib failed to initialize compressor -- version error");
575 if (ret == Z_STREAM_ERROR) png_error(png_ptr,
576 "zlib failed to initialize compressor -- stream error");
577 if (ret == Z_MEM_ERROR) png_error(png_ptr,
578 "zlib failed to initialize compressor -- mem error");
579 png_error(png_ptr, "zlib failed to initialize compressor");
581 png_ptr->zstream.next_out = png_ptr->zbuf;
582 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
583 /* libpng is not interested in zstream.data_type */
584 /* Set it to a predefined value, to avoid its evaluation inside zlib */
585 png_ptr->zstream.data_type = Z_BINARY;
587 png_ptr->mode = PNG_HAVE_IHDR;
590 /* Write the palette. We are careful not to trust png_color to be in the
591 * correct order for PNG, so people can redefine it to any convenient
595 png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
602 png_debug(1, "in png_write_PLTE");
605 #ifdef PNG_MNG_FEATURES_SUPPORTED
606 !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
608 num_pal == 0) || num_pal > 256)
610 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
612 png_error(png_ptr, "Invalid number of colors in palette");
616 png_warning(png_ptr, "Invalid number of colors in palette");
621 if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
624 "Ignoring request to write a PLTE chunk in grayscale PNG");
628 png_ptr->num_palette = (png_uint_16)num_pal;
629 png_debug1(3, "num_palette = %d", png_ptr->num_palette);
631 png_write_chunk_start(png_ptr, (png_bytep)png_PLTE,
632 (png_uint_32)(num_pal * 3));
633 #ifdef PNG_POINTER_INDEXING_SUPPORTED
634 for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
636 buf[0] = pal_ptr->red;
637 buf[1] = pal_ptr->green;
638 buf[2] = pal_ptr->blue;
639 png_write_chunk_data(png_ptr, buf, (png_size_t)3);
642 /* This is a little slower but some buggy compilers need to do this instead */
644 for (i = 0; i < num_pal; i++)
646 buf[0] = pal_ptr[i].red;
647 buf[1] = pal_ptr[i].green;
648 buf[2] = pal_ptr[i].blue;
649 png_write_chunk_data(png_ptr, buf, (png_size_t)3);
652 png_write_chunk_end(png_ptr);
653 png_ptr->mode |= PNG_HAVE_PLTE;
656 /* Write an IDAT chunk */
658 png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
662 png_debug(1, "in png_write_IDAT");
664 /* Optimize the CMF field in the zlib stream. */
665 /* This hack of the zlib stream is compliant to the stream specification. */
666 if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
667 png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
669 unsigned int z_cmf = data[0]; /* zlib compression method and flags */
670 if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
672 /* Avoid memory underflows and multiplication overflows.
674 * The conditions below are practically always satisfied;
675 * however, they still must be checked.
678 png_ptr->height < 16384 && png_ptr->width < 16384)
680 png_uint_32 uncompressed_idat_size = png_ptr->height *
682 png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
683 unsigned int z_cinfo = z_cmf >> 4;
684 unsigned int half_z_window_size = 1 << (z_cinfo + 7);
685 while (uncompressed_idat_size <= half_z_window_size &&
686 half_z_window_size >= 256)
689 half_z_window_size >>= 1;
691 z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
692 if (data[0] != (png_byte)z_cmf)
694 data[0] = (png_byte)z_cmf;
696 data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
702 "Invalid zlib compression method or flags in IDAT");
705 png_write_chunk(png_ptr, (png_bytep)png_IDAT, data, length);
706 png_ptr->mode |= PNG_HAVE_IDAT;
709 /* Write an IEND chunk */
711 png_write_IEND(png_structp png_ptr)
715 png_debug(1, "in png_write_IEND");
717 png_write_chunk(png_ptr, (png_bytep)png_IEND, NULL,
719 png_ptr->mode |= PNG_HAVE_IEND;
722 #ifdef PNG_WRITE_gAMA_SUPPORTED
723 /* Write a gAMA chunk */
724 #ifdef PNG_FLOATING_POINT_SUPPORTED
726 png_write_gAMA(png_structp png_ptr, double file_gamma)
732 png_debug(1, "in png_write_gAMA");
734 /* file_gamma is saved in 1/100,000ths */
735 igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
736 png_save_uint_32(buf, igamma);
737 png_write_chunk(png_ptr, (png_bytep)png_gAMA, buf, (png_size_t)4);
740 #ifdef PNG_FIXED_POINT_SUPPORTED
742 png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
747 png_debug(1, "in png_write_gAMA");
749 /* file_gamma is saved in 1/100,000ths */
750 png_save_uint_32(buf, (png_uint_32)file_gamma);
751 png_write_chunk(png_ptr, (png_bytep)png_gAMA, buf, (png_size_t)4);
756 #ifdef PNG_WRITE_sRGB_SUPPORTED
757 /* Write a sRGB chunk */
759 png_write_sRGB(png_structp png_ptr, int srgb_intent)
764 png_debug(1, "in png_write_sRGB");
766 if (srgb_intent >= PNG_sRGB_INTENT_LAST)
768 "Invalid sRGB rendering intent specified");
769 buf[0]=(png_byte)srgb_intent;
770 png_write_chunk(png_ptr, (png_bytep)png_sRGB, buf, (png_size_t)1);
774 #ifdef PNG_WRITE_iCCP_SUPPORTED
775 /* Write an iCCP chunk */
777 png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
778 png_charp profile, int profile_len)
783 compression_state comp;
784 int embedded_profile_len = 0;
786 png_debug(1, "in png_write_iCCP");
788 comp.num_output_ptr = 0;
789 comp.max_output_ptr = 0;
790 comp.output_ptr = NULL;
794 if ((name_len = png_check_keyword(png_ptr, name,
798 if (compression_type != PNG_COMPRESSION_TYPE_BASE)
799 png_warning(png_ptr, "Unknown compression type in iCCP chunk");
805 embedded_profile_len =
806 ((*( (png_bytep)profile ))<<24) |
807 ((*( (png_bytep)profile + 1))<<16) |
808 ((*( (png_bytep)profile + 2))<< 8) |
809 ((*( (png_bytep)profile + 3)) );
811 if (embedded_profile_len < 0)
814 "Embedded profile length in iCCP chunk is negative");
815 png_free(png_ptr, new_name);
819 if (profile_len < embedded_profile_len)
822 "Embedded profile length too large in iCCP chunk");
823 png_free(png_ptr, new_name);
827 if (profile_len > embedded_profile_len)
830 "Truncating profile to actual length in iCCP chunk");
831 profile_len = embedded_profile_len;
835 profile_len = png_text_compress(png_ptr, profile,
836 (png_size_t)profile_len, PNG_COMPRESSION_TYPE_BASE, &comp);
838 /* Make sure we include the NULL after the name and the compression type */
839 png_write_chunk_start(png_ptr, (png_bytep)png_iCCP,
840 (png_uint_32)(name_len + profile_len + 2));
841 new_name[name_len + 1] = 0x00;
842 png_write_chunk_data(png_ptr, (png_bytep)new_name,
843 (png_size_t)(name_len + 2));
846 png_write_compressed_data_out(png_ptr, &comp);
848 png_write_chunk_end(png_ptr);
849 png_free(png_ptr, new_name);
853 #ifdef PNG_WRITE_sPLT_SUPPORTED
854 /* Write a sPLT chunk */
856 png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
861 png_byte entrybuf[10];
862 png_size_t entry_size = (spalette->depth == 8 ? 6 : 10);
863 png_size_t palette_size = entry_size * spalette->nentries;
865 #ifndef PNG_POINTER_INDEXING_SUPPORTED
869 png_debug(1, "in png_write_sPLT");
871 if ((name_len = png_check_keyword(png_ptr,spalette->name, &new_name))==0)
874 /* Make sure we include the NULL after the name */
875 png_write_chunk_start(png_ptr, (png_bytep)png_sPLT,
876 (png_uint_32)(name_len + 2 + palette_size));
877 png_write_chunk_data(png_ptr, (png_bytep)new_name,
878 (png_size_t)(name_len + 1));
879 png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, (png_size_t)1);
881 /* Loop through each palette entry, writing appropriately */
882 #ifdef PNG_POINTER_INDEXING_SUPPORTED
883 for (ep = spalette->entries; ep<spalette->entries + spalette->nentries; ep++)
885 if (spalette->depth == 8)
887 entrybuf[0] = (png_byte)ep->red;
888 entrybuf[1] = (png_byte)ep->green;
889 entrybuf[2] = (png_byte)ep->blue;
890 entrybuf[3] = (png_byte)ep->alpha;
891 png_save_uint_16(entrybuf + 4, ep->frequency);
895 png_save_uint_16(entrybuf + 0, ep->red);
896 png_save_uint_16(entrybuf + 2, ep->green);
897 png_save_uint_16(entrybuf + 4, ep->blue);
898 png_save_uint_16(entrybuf + 6, ep->alpha);
899 png_save_uint_16(entrybuf + 8, ep->frequency);
901 png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
904 ep=spalette->entries;
905 for (i=0; i>spalette->nentries; i++)
907 if (spalette->depth == 8)
909 entrybuf[0] = (png_byte)ep[i].red;
910 entrybuf[1] = (png_byte)ep[i].green;
911 entrybuf[2] = (png_byte)ep[i].blue;
912 entrybuf[3] = (png_byte)ep[i].alpha;
913 png_save_uint_16(entrybuf + 4, ep[i].frequency);
917 png_save_uint_16(entrybuf + 0, ep[i].red);
918 png_save_uint_16(entrybuf + 2, ep[i].green);
919 png_save_uint_16(entrybuf + 4, ep[i].blue);
920 png_save_uint_16(entrybuf + 6, ep[i].alpha);
921 png_save_uint_16(entrybuf + 8, ep[i].frequency);
923 png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
927 png_write_chunk_end(png_ptr);
928 png_free(png_ptr, new_name);
932 #ifdef PNG_WRITE_sBIT_SUPPORTED
933 /* Write the sBIT chunk */
935 png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
941 png_debug(1, "in png_write_sBIT");
943 /* Make sure we don't depend upon the order of PNG_COLOR_8 */
944 if (color_type & PNG_COLOR_MASK_COLOR)
948 maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
949 png_ptr->usr_bit_depth);
950 if (sbit->red == 0 || sbit->red > maxbits ||
951 sbit->green == 0 || sbit->green > maxbits ||
952 sbit->blue == 0 || sbit->blue > maxbits)
954 png_warning(png_ptr, "Invalid sBIT depth specified");
958 buf[1] = sbit->green;
964 if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
966 png_warning(png_ptr, "Invalid sBIT depth specified");
973 if (color_type & PNG_COLOR_MASK_ALPHA)
975 if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
977 png_warning(png_ptr, "Invalid sBIT depth specified");
980 buf[size++] = sbit->alpha;
983 png_write_chunk(png_ptr, (png_bytep)png_sBIT, buf, size);
987 #ifdef PNG_WRITE_cHRM_SUPPORTED
988 /* Write the cHRM chunk */
989 #ifdef PNG_FLOATING_POINT_SUPPORTED
991 png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
992 double red_x, double red_y, double green_x, double green_y,
993 double blue_x, double blue_y)
998 png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y,
999 int_green_x, int_green_y, int_blue_x, int_blue_y;
1001 png_debug(1, "in png_write_cHRM");
1003 int_white_x = (png_uint_32)(white_x * 100000.0 + 0.5);
1004 int_white_y = (png_uint_32)(white_y * 100000.0 + 0.5);
1005 int_red_x = (png_uint_32)(red_x * 100000.0 + 0.5);
1006 int_red_y = (png_uint_32)(red_y * 100000.0 + 0.5);
1007 int_green_x = (png_uint_32)(green_x * 100000.0 + 0.5);
1008 int_green_y = (png_uint_32)(green_y * 100000.0 + 0.5);
1009 int_blue_x = (png_uint_32)(blue_x * 100000.0 + 0.5);
1010 int_blue_y = (png_uint_32)(blue_y * 100000.0 + 0.5);
1012 #ifdef PNG_CHECK_cHRM_SUPPORTED
1013 if (png_check_cHRM_fixed(png_ptr, int_white_x, int_white_y,
1014 int_red_x, int_red_y, int_green_x, int_green_y, int_blue_x, int_blue_y))
1017 /* Each value is saved in 1/100,000ths */
1019 png_save_uint_32(buf, int_white_x);
1020 png_save_uint_32(buf + 4, int_white_y);
1022 png_save_uint_32(buf + 8, int_red_x);
1023 png_save_uint_32(buf + 12, int_red_y);
1025 png_save_uint_32(buf + 16, int_green_x);
1026 png_save_uint_32(buf + 20, int_green_y);
1028 png_save_uint_32(buf + 24, int_blue_x);
1029 png_save_uint_32(buf + 28, int_blue_y);
1031 png_write_chunk(png_ptr, (png_bytep)png_cHRM, buf, (png_size_t)32);
1035 #ifdef PNG_FIXED_POINT_SUPPORTED
1037 png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
1038 png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
1039 png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
1040 png_fixed_point blue_y)
1045 png_debug(1, "in png_write_cHRM");
1047 /* Each value is saved in 1/100,000ths */
1048 #ifdef PNG_CHECK_cHRM_SUPPORTED
1049 if (png_check_cHRM_fixed(png_ptr, white_x, white_y, red_x, red_y,
1050 green_x, green_y, blue_x, blue_y))
1053 png_save_uint_32(buf, (png_uint_32)white_x);
1054 png_save_uint_32(buf + 4, (png_uint_32)white_y);
1056 png_save_uint_32(buf + 8, (png_uint_32)red_x);
1057 png_save_uint_32(buf + 12, (png_uint_32)red_y);
1059 png_save_uint_32(buf + 16, (png_uint_32)green_x);
1060 png_save_uint_32(buf + 20, (png_uint_32)green_y);
1062 png_save_uint_32(buf + 24, (png_uint_32)blue_x);
1063 png_save_uint_32(buf + 28, (png_uint_32)blue_y);
1065 png_write_chunk(png_ptr, (png_bytep)png_cHRM, buf, (png_size_t)32);
1071 #ifdef PNG_WRITE_tRNS_SUPPORTED
1072 /* Write the tRNS chunk */
1074 png_write_tRNS(png_structp png_ptr, png_bytep trans_alpha, png_color_16p tran,
1075 int num_trans, int color_type)
1080 png_debug(1, "in png_write_tRNS");
1082 if (color_type == PNG_COLOR_TYPE_PALETTE)
1084 if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
1086 png_warning(png_ptr, "Invalid number of transparent colors specified");
1089 /* Write the chunk out as it is */
1090 png_write_chunk(png_ptr, (png_bytep)png_tRNS, trans_alpha,
1091 (png_size_t)num_trans);
1093 else if (color_type == PNG_COLOR_TYPE_GRAY)
1095 /* One 16 bit value */
1096 if (tran->gray >= (1 << png_ptr->bit_depth))
1098 png_warning(png_ptr,
1099 "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
1102 png_save_uint_16(buf, tran->gray);
1103 png_write_chunk(png_ptr, (png_bytep)png_tRNS, buf, (png_size_t)2);
1105 else if (color_type == PNG_COLOR_TYPE_RGB)
1107 /* Three 16 bit values */
1108 png_save_uint_16(buf, tran->red);
1109 png_save_uint_16(buf + 2, tran->green);
1110 png_save_uint_16(buf + 4, tran->blue);
1111 if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
1113 png_warning(png_ptr,
1114 "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
1117 png_write_chunk(png_ptr, (png_bytep)png_tRNS, buf, (png_size_t)6);
1121 png_warning(png_ptr, "Can't write tRNS with an alpha channel");
1126 #ifdef PNG_WRITE_bKGD_SUPPORTED
1127 /* Write the background chunk */
1129 png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
1134 png_debug(1, "in png_write_bKGD");
1136 if (color_type == PNG_COLOR_TYPE_PALETTE)
1139 #ifdef PNG_MNG_FEATURES_SUPPORTED
1140 (png_ptr->num_palette ||
1141 (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
1143 back->index >= png_ptr->num_palette)
1145 png_warning(png_ptr, "Invalid background palette index");
1148 buf[0] = back->index;
1149 png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)1);
1151 else if (color_type & PNG_COLOR_MASK_COLOR)
1153 png_save_uint_16(buf, back->red);
1154 png_save_uint_16(buf + 2, back->green);
1155 png_save_uint_16(buf + 4, back->blue);
1156 if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
1158 png_warning(png_ptr,
1159 "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
1162 png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)6);
1166 if (back->gray >= (1 << png_ptr->bit_depth))
1168 png_warning(png_ptr,
1169 "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
1172 png_save_uint_16(buf, back->gray);
1173 png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)2);
1178 #ifdef PNG_WRITE_hIST_SUPPORTED
1179 /* Write the histogram */
1181 png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
1187 png_debug(1, "in png_write_hIST");
1189 if (num_hist > (int)png_ptr->num_palette)
1191 png_debug2(3, "num_hist = %d, num_palette = %d", num_hist,
1192 png_ptr->num_palette);
1193 png_warning(png_ptr, "Invalid number of histogram entries specified");
1197 png_write_chunk_start(png_ptr, (png_bytep)png_hIST,
1198 (png_uint_32)(num_hist * 2));
1199 for (i = 0; i < num_hist; i++)
1201 png_save_uint_16(buf, hist[i]);
1202 png_write_chunk_data(png_ptr, buf, (png_size_t)2);
1204 png_write_chunk_end(png_ptr);
1208 #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
1209 defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
1210 /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
1211 * and if invalid, correct the keyword rather than discarding the entire
1212 * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
1213 * length, forbids leading or trailing whitespace, multiple internal spaces,
1214 * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
1216 * The new_key is allocated to hold the corrected keyword and must be freed
1217 * by the calling routine. This avoids problems with trying to write to
1218 * static keywords without having to have duplicate copies of the strings.
1220 png_size_t /* PRIVATE */
1221 png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
1228 png_debug(1, "in png_check_keyword");
1232 if (key == NULL || (key_len = png_strlen(key)) == 0)
1234 png_warning(png_ptr, "zero length keyword");
1235 return ((png_size_t)0);
1238 png_debug1(2, "Keyword to be checked is '%s'", key);
1240 *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
1241 if (*new_key == NULL)
1243 png_warning(png_ptr, "Out of memory while procesing keyword");
1244 return ((png_size_t)0);
1247 /* Replace non-printing characters with a blank and print a warning */
1248 for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
1250 if ((png_byte)*kp < 0x20 ||
1251 ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
1253 #ifdef PNG_STDIO_SUPPORTED
1256 png_snprintf(msg, 40,
1257 "invalid keyword character 0x%02X", (png_byte)*kp);
1258 png_warning(png_ptr, msg);
1260 png_warning(png_ptr, "invalid character in keyword");
1271 /* Remove any trailing white space. */
1272 kp = *new_key + key_len - 1;
1275 png_warning(png_ptr, "trailing spaces removed from keyword");
1284 /* Remove any leading white space. */
1288 png_warning(png_ptr, "leading spaces removed from keyword");
1297 png_debug1(2, "Checking for multiple internal spaces in '%s'", kp);
1299 /* Remove multiple internal spaces. */
1300 for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
1302 if (*kp == ' ' && kflag == 0)
1307 else if (*kp == ' ')
1320 png_warning(png_ptr, "extra interior spaces removed from keyword");
1324 png_free(png_ptr, *new_key);
1325 png_warning(png_ptr, "Zero length keyword");
1330 png_warning(png_ptr, "keyword length must be 1 - 79 characters");
1331 (*new_key)[79] = '\0';
1339 #ifdef PNG_WRITE_tEXt_SUPPORTED
1340 /* Write a tEXt chunk */
1342 png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
1343 png_size_t text_len)
1349 png_debug(1, "in png_write_tEXt");
1351 if ((key_len = png_check_keyword(png_ptr, key, &new_key))==0)
1354 if (text == NULL || *text == '\0')
1357 text_len = png_strlen(text);
1359 /* Make sure we include the 0 after the key */
1360 png_write_chunk_start(png_ptr, (png_bytep)png_tEXt,
1361 (png_uint_32)(key_len + text_len + 1));
1363 * We leave it to the application to meet PNG-1.0 requirements on the
1364 * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
1365 * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
1366 * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
1368 png_write_chunk_data(png_ptr, (png_bytep)new_key,
1369 (png_size_t)(key_len + 1));
1371 png_write_chunk_data(png_ptr, (png_bytep)text, (png_size_t)text_len);
1373 png_write_chunk_end(png_ptr);
1374 png_free(png_ptr, new_key);
1378 #ifdef PNG_WRITE_zTXt_SUPPORTED
1379 /* Write a compressed text chunk */
1381 png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
1382 png_size_t text_len, int compression)
1388 compression_state comp;
1390 png_debug(1, "in png_write_zTXt");
1392 comp.num_output_ptr = 0;
1393 comp.max_output_ptr = 0;
1394 comp.output_ptr = NULL;
1398 if ((key_len = png_check_keyword(png_ptr, key, &new_key))==0)
1400 png_free(png_ptr, new_key);
1404 if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
1406 png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
1407 png_free(png_ptr, new_key);
1411 text_len = png_strlen(text);
1413 /* Compute the compressed data; do it now for the length */
1414 text_len = png_text_compress(png_ptr, text, text_len, compression,
1417 /* Write start of chunk */
1418 png_write_chunk_start(png_ptr, (png_bytep)png_zTXt,
1419 (png_uint_32)(key_len+text_len + 2));
1421 png_write_chunk_data(png_ptr, (png_bytep)new_key,
1422 (png_size_t)(key_len + 1));
1423 png_free(png_ptr, new_key);
1425 buf[0] = (png_byte)compression;
1426 /* Write compression */
1427 png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
1428 /* Write the compressed data */
1429 png_write_compressed_data_out(png_ptr, &comp);
1431 /* Close the chunk */
1432 png_write_chunk_end(png_ptr);
1436 #ifdef PNG_WRITE_iTXt_SUPPORTED
1437 /* Write an iTXt chunk */
1439 png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
1440 png_charp lang, png_charp lang_key, png_charp text)
1443 png_size_t lang_len, key_len, lang_key_len, text_len;
1445 png_charp new_key = NULL;
1447 compression_state comp;
1449 png_debug(1, "in png_write_iTXt");
1451 comp.num_output_ptr = 0;
1452 comp.max_output_ptr = 0;
1453 comp.output_ptr = NULL;
1456 if ((key_len = png_check_keyword(png_ptr, key, &new_key))==0)
1459 if ((lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
1461 png_warning(png_ptr, "Empty language field in iTXt chunk");
1466 if (lang_key == NULL)
1469 lang_key_len = png_strlen(lang_key);
1474 text_len = png_strlen(text);
1476 /* Compute the compressed data; do it now for the length */
1477 text_len = png_text_compress(png_ptr, text, text_len, compression-2,
1481 /* Make sure we include the compression flag, the compression byte,
1482 * and the NULs after the key, lang, and lang_key parts */
1484 png_write_chunk_start(png_ptr, (png_bytep)png_iTXt,
1486 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
1492 /* We leave it to the application to meet PNG-1.0 requirements on the
1493 * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
1494 * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
1495 * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
1497 png_write_chunk_data(png_ptr, (png_bytep)new_key,
1498 (png_size_t)(key_len + 1));
1500 /* Set the compression flag */
1501 if (compression == PNG_ITXT_COMPRESSION_NONE || \
1502 compression == PNG_TEXT_COMPRESSION_NONE)
1504 else /* compression == PNG_ITXT_COMPRESSION_zTXt */
1506 /* Set the compression method */
1508 png_write_chunk_data(png_ptr, cbuf, (png_size_t)2);
1511 png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf),
1512 (png_size_t)(lang_len + 1));
1513 png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf),
1514 (png_size_t)(lang_key_len + 1));
1515 png_write_compressed_data_out(png_ptr, &comp);
1517 png_write_chunk_end(png_ptr);
1518 png_free(png_ptr, new_key);
1519 png_free(png_ptr, new_lang);
1523 #ifdef PNG_WRITE_oFFs_SUPPORTED
1524 /* Write the oFFs chunk */
1526 png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
1532 png_debug(1, "in png_write_oFFs");
1534 if (unit_type >= PNG_OFFSET_LAST)
1535 png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
1537 png_save_int_32(buf, x_offset);
1538 png_save_int_32(buf + 4, y_offset);
1539 buf[8] = (png_byte)unit_type;
1541 png_write_chunk(png_ptr, (png_bytep)png_oFFs, buf, (png_size_t)9);
1544 #ifdef PNG_WRITE_pCAL_SUPPORTED
1545 /* Write the pCAL chunk (described in the PNG extensions document) */
1547 png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
1548 png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
1551 png_size_t purpose_len, units_len, total_len;
1552 png_uint_32p params_len;
1554 png_charp new_purpose;
1557 png_debug1(1, "in png_write_pCAL (%d parameters)", nparams);
1559 if (type >= PNG_EQUATION_LAST)
1560 png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
1562 purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
1563 png_debug1(3, "pCAL purpose length = %d", (int)purpose_len);
1564 units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
1565 png_debug1(3, "pCAL units length = %d", (int)units_len);
1566 total_len = purpose_len + units_len + 10;
1568 params_len = (png_uint_32p)png_malloc(png_ptr,
1569 (png_alloc_size_t)(nparams * png_sizeof(png_uint_32)));
1571 /* Find the length of each parameter, making sure we don't count the
1572 null terminator for the last parameter. */
1573 for (i = 0; i < nparams; i++)
1575 params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
1576 png_debug2(3, "pCAL parameter %d length = %lu", i,
1577 (unsigned long) params_len[i]);
1578 total_len += (png_size_t)params_len[i];
1581 png_debug1(3, "pCAL total length = %d", (int)total_len);
1582 png_write_chunk_start(png_ptr, (png_bytep)png_pCAL, (png_uint_32)total_len);
1583 png_write_chunk_data(png_ptr, (png_bytep)new_purpose,
1584 (png_size_t)purpose_len);
1585 png_save_int_32(buf, X0);
1586 png_save_int_32(buf + 4, X1);
1587 buf[8] = (png_byte)type;
1588 buf[9] = (png_byte)nparams;
1589 png_write_chunk_data(png_ptr, buf, (png_size_t)10);
1590 png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
1592 png_free(png_ptr, new_purpose);
1594 for (i = 0; i < nparams; i++)
1596 png_write_chunk_data(png_ptr, (png_bytep)params[i],
1597 (png_size_t)params_len[i]);
1600 png_free(png_ptr, params_len);
1601 png_write_chunk_end(png_ptr);
1605 #ifdef PNG_WRITE_sCAL_SUPPORTED
1606 /* Write the sCAL chunk */
1607 #if defined(PNG_FLOATING_POINT_SUPPORTED) && defined(PNG_STDIO_SUPPORTED)
1609 png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
1613 png_size_t total_len;
1615 png_debug(1, "in png_write_sCAL");
1617 buf[0] = (char)unit;
1618 png_snprintf(buf + 1, 63, "%12.12e", width);
1619 total_len = 1 + png_strlen(buf + 1) + 1;
1620 png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
1621 total_len += png_strlen(buf + total_len);
1623 png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);
1624 png_write_chunk(png_ptr, (png_bytep)png_sCAL, (png_bytep)buf, total_len);
1627 #ifdef PNG_FIXED_POINT_SUPPORTED
1629 png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
1634 png_size_t wlen, hlen, total_len;
1636 png_debug(1, "in png_write_sCAL_s");
1638 wlen = png_strlen(width);
1639 hlen = png_strlen(height);
1640 total_len = wlen + hlen + 2;
1643 png_warning(png_ptr, "Can't write sCAL (buffer too small)");
1647 buf[0] = (png_byte)unit;
1648 png_memcpy(buf + 1, width, wlen + 1); /* Append the '\0' here */
1649 png_memcpy(buf + wlen + 2, height, hlen); /* Do NOT append the '\0' here */
1651 png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);
1652 png_write_chunk(png_ptr, (png_bytep)png_sCAL, buf, total_len);
1658 #ifdef PNG_WRITE_pHYs_SUPPORTED
1659 /* Write the pHYs chunk */
1661 png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
1662 png_uint_32 y_pixels_per_unit,
1668 png_debug(1, "in png_write_pHYs");
1670 if (unit_type >= PNG_RESOLUTION_LAST)
1671 png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
1673 png_save_uint_32(buf, x_pixels_per_unit);
1674 png_save_uint_32(buf + 4, y_pixels_per_unit);
1675 buf[8] = (png_byte)unit_type;
1677 png_write_chunk(png_ptr, (png_bytep)png_pHYs, buf, (png_size_t)9);
1681 #ifdef PNG_WRITE_tIME_SUPPORTED
1682 /* Write the tIME chunk. Use either png_convert_from_struct_tm()
1683 * or png_convert_from_time_t(), or fill in the structure yourself.
1686 png_write_tIME(png_structp png_ptr, png_timep mod_time)
1691 png_debug(1, "in png_write_tIME");
1693 if (mod_time->month > 12 || mod_time->month < 1 ||
1694 mod_time->day > 31 || mod_time->day < 1 ||
1695 mod_time->hour > 23 || mod_time->second > 60)
1697 png_warning(png_ptr, "Invalid time specified for tIME chunk");
1701 png_save_uint_16(buf, mod_time->year);
1702 buf[2] = mod_time->month;
1703 buf[3] = mod_time->day;
1704 buf[4] = mod_time->hour;
1705 buf[5] = mod_time->minute;
1706 buf[6] = mod_time->second;
1708 png_write_chunk(png_ptr, (png_bytep)png_tIME, buf, (png_size_t)7);
1712 /* Initializes the row writing capability of libpng */
1714 png_write_start_row(png_structp png_ptr)
1716 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
1717 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1719 /* Start of interlace block */
1720 int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1722 /* Offset to next interlace block */
1723 int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1725 /* Start of interlace block in the y direction */
1726 int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
1728 /* Offset to next interlace block in the y direction */
1729 int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
1732 png_size_t buf_size;
1734 png_debug(1, "in png_write_start_row");
1736 buf_size = (png_size_t)(PNG_ROWBYTES(
1737 png_ptr->usr_channels*png_ptr->usr_bit_depth, png_ptr->width) + 1);
1739 /* Set up row buffer */
1740 png_ptr->row_buf = (png_bytep)png_malloc(png_ptr,
1741 (png_alloc_size_t)buf_size);
1742 png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
1744 #ifdef PNG_WRITE_FILTER_SUPPORTED
1745 /* Set up filtering buffer, if using this filter */
1746 if (png_ptr->do_filter & PNG_FILTER_SUB)
1748 png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
1749 (png_alloc_size_t)(png_ptr->rowbytes + 1));
1750 png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
1753 /* We only need to keep the previous row if we are using one of these. */
1754 if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
1756 /* Set up previous row buffer */
1757 png_ptr->prev_row = (png_bytep)png_calloc(png_ptr,
1758 (png_alloc_size_t)buf_size);
1760 if (png_ptr->do_filter & PNG_FILTER_UP)
1762 png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
1763 (png_size_t)(png_ptr->rowbytes + 1));
1764 png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
1767 if (png_ptr->do_filter & PNG_FILTER_AVG)
1769 png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
1770 (png_alloc_size_t)(png_ptr->rowbytes + 1));
1771 png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
1774 if (png_ptr->do_filter & PNG_FILTER_PAETH)
1776 png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
1777 (png_size_t)(png_ptr->rowbytes + 1));
1778 png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
1781 #endif /* PNG_WRITE_FILTER_SUPPORTED */
1783 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
1784 /* If interlaced, we need to set up width and height of pass */
1785 if (png_ptr->interlaced)
1787 if (!(png_ptr->transformations & PNG_INTERLACE))
1789 png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
1790 png_pass_ystart[0]) / png_pass_yinc[0];
1791 png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
1792 png_pass_start[0]) / png_pass_inc[0];
1796 png_ptr->num_rows = png_ptr->height;
1797 png_ptr->usr_width = png_ptr->width;
1803 png_ptr->num_rows = png_ptr->height;
1804 png_ptr->usr_width = png_ptr->width;
1806 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
1807 png_ptr->zstream.next_out = png_ptr->zbuf;
1810 /* Internal use only. Called when finished processing a row of data. */
1812 png_write_finish_row(png_structp png_ptr)
1814 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
1815 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1817 /* Start of interlace block */
1818 int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1820 /* Offset to next interlace block */
1821 int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1823 /* Start of interlace block in the y direction */
1824 int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
1826 /* Offset to next interlace block in the y direction */
1827 int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
1832 png_debug(1, "in png_write_finish_row");
1835 png_ptr->row_number++;
1837 /* See if we are done */
1838 if (png_ptr->row_number < png_ptr->num_rows)
1841 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
1842 /* If interlaced, go to next pass */
1843 if (png_ptr->interlaced)
1845 png_ptr->row_number = 0;
1846 if (png_ptr->transformations & PNG_INTERLACE)
1852 /* Loop until we find a non-zero width or height pass */
1856 if (png_ptr->pass >= 7)
1858 png_ptr->usr_width = (png_ptr->width +
1859 png_pass_inc[png_ptr->pass] - 1 -
1860 png_pass_start[png_ptr->pass]) /
1861 png_pass_inc[png_ptr->pass];
1862 png_ptr->num_rows = (png_ptr->height +
1863 png_pass_yinc[png_ptr->pass] - 1 -
1864 png_pass_ystart[png_ptr->pass]) /
1865 png_pass_yinc[png_ptr->pass];
1866 if (png_ptr->transformations & PNG_INTERLACE)
1868 } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
1872 /* Reset the row above the image for the next pass */
1873 if (png_ptr->pass < 7)
1875 if (png_ptr->prev_row != NULL)
1876 png_memset(png_ptr->prev_row, 0,
1877 (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
1878 png_ptr->usr_bit_depth, png_ptr->width)) + 1);
1884 /* If we get here, we've just written the last row, so we need
1885 to flush the compressor */
1888 /* Tell the compressor we are done */
1889 ret = deflate(&png_ptr->zstream, Z_FINISH);
1890 /* Check for an error */
1893 /* Check to see if we need more room */
1894 if (!(png_ptr->zstream.avail_out))
1896 png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
1897 png_ptr->zstream.next_out = png_ptr->zbuf;
1898 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
1901 else if (ret != Z_STREAM_END)
1903 if (png_ptr->zstream.msg != NULL)
1904 png_error(png_ptr, png_ptr->zstream.msg);
1906 png_error(png_ptr, "zlib error");
1908 } while (ret != Z_STREAM_END);
1910 /* Write any extra space */
1911 if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
1913 png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
1914 png_ptr->zstream.avail_out);
1917 deflateReset(&png_ptr->zstream);
1918 png_ptr->zstream.data_type = Z_BINARY;
1921 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
1922 /* Pick out the correct pixels for the interlace pass.
1923 * The basic idea here is to go through the row with a source
1924 * pointer and a destination pointer (sp and dp), and copy the
1925 * correct pixels for the pass. As the row gets compacted,
1926 * sp will always be >= dp, so we should never overwrite anything.
1927 * See the default: case for the easiest code to understand.
1930 png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
1932 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1934 /* Start of interlace block */
1935 int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1937 /* Offset to next interlace block */
1938 int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1940 png_debug(1, "in png_do_write_interlace");
1942 /* We don't have to do anything on the last pass (6) */
1945 /* Each pixel depth is handled separately */
1946 switch (row_info->pixel_depth)
1956 png_uint_32 row_width = row_info->width;
1961 for (i = png_pass_start[pass]; i < row_width;
1962 i += png_pass_inc[pass])
1964 sp = row + (png_size_t)(i >> 3);
1965 value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
1966 d |= (value << shift);
1971 *dp++ = (png_byte)d;
1990 png_uint_32 row_width = row_info->width;
1995 for (i = png_pass_start[pass]; i < row_width;
1996 i += png_pass_inc[pass])
1998 sp = row + (png_size_t)(i >> 2);
1999 value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
2000 d |= (value << shift);
2005 *dp++ = (png_byte)d;
2023 png_uint_32 row_width = row_info->width;
2028 for (i = png_pass_start[pass]; i < row_width;
2029 i += png_pass_inc[pass])
2031 sp = row + (png_size_t)(i >> 1);
2032 value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
2033 d |= (value << shift);
2038 *dp++ = (png_byte)d;
2053 png_uint_32 row_width = row_info->width;
2054 png_size_t pixel_bytes;
2056 /* Start at the beginning */
2058 /* Find out how many bytes each pixel takes up */
2059 pixel_bytes = (row_info->pixel_depth >> 3);
2060 /* Loop through the row, only looking at the pixels that
2062 for (i = png_pass_start[pass]; i < row_width;
2063 i += png_pass_inc[pass])
2065 /* Find out where the original pixel is */
2066 sp = row + (png_size_t)i * pixel_bytes;
2067 /* Move the pixel */
2069 png_memcpy(dp, sp, pixel_bytes);
2076 /* Set new row width */
2077 row_info->width = (row_info->width +
2078 png_pass_inc[pass] - 1 -
2079 png_pass_start[pass]) /
2081 row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
2087 /* This filters the row, chooses which filter to use, if it has not already
2088 * been specified by the application, and then writes the row out with the
2091 #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
2092 #define PNG_HISHIFT 10
2093 #define PNG_LOMASK ((png_uint_32)0xffffL)
2094 #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
2096 png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
2099 #ifdef PNG_WRITE_FILTER_SUPPORTED
2100 png_bytep prev_row, row_buf;
2101 png_uint_32 mins, bpp;
2102 png_byte filter_to_do = png_ptr->do_filter;
2103 png_uint_32 row_bytes = row_info->rowbytes;
2104 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2105 int num_p_filters = (int)png_ptr->num_prev_filters;
2108 png_debug(1, "in png_write_find_filter");
2110 #ifndef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2111 if (png_ptr->row_number == 0 && filter_to_do == PNG_ALL_FILTERS)
2113 /* These will never be selected so we need not test them. */
2114 filter_to_do &= ~(PNG_FILTER_UP | PNG_FILTER_PAETH);
2118 /* Find out how many bytes offset each pixel is */
2119 bpp = (row_info->pixel_depth + 7) >> 3;
2121 prev_row = png_ptr->prev_row;
2123 best_row = png_ptr->row_buf;
2124 #ifdef PNG_WRITE_FILTER_SUPPORTED
2128 /* The prediction method we use is to find which method provides the
2129 * smallest value when summing the absolute values of the distances
2130 * from zero, using anything >= 128 as negative numbers. This is known
2131 * as the "minimum sum of absolute differences" heuristic. Other
2132 * heuristics are the "weighted minimum sum of absolute differences"
2133 * (experimental and can in theory improve compression), and the "zlib
2134 * predictive" method (not implemented yet), which does test compressions
2135 * of lines using different filter methods, and then chooses the
2136 * (series of) filter(s) that give minimum compressed data size (VERY
2137 * computationally expensive).
2139 * GRR 980525: consider also
2140 * (1) minimum sum of absolute differences from running average (i.e.,
2141 * keep running sum of non-absolute differences & count of bytes)
2142 * [track dispersion, too? restart average if dispersion too large?]
2143 * (1b) minimum sum of absolute differences from sliding average, probably
2144 * with window size <= deflate window (usually 32K)
2145 * (2) minimum sum of squared differences from zero or running average
2146 * (i.e., ~ root-mean-square approach)
2150 /* We don't need to test the 'no filter' case if this is the only filter
2151 * that has been chosen, as it doesn't actually do anything to the data.
2153 if ((filter_to_do & PNG_FILTER_NONE) &&
2154 filter_to_do != PNG_FILTER_NONE)
2157 png_uint_32 sum = 0;
2161 for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
2164 sum += (v < 128) ? v : 256 - v;
2167 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2168 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2170 png_uint_32 sumhi, sumlo;
2172 sumlo = sum & PNG_LOMASK;
2173 sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
2175 /* Reduce the sum if we match any of the previous rows */
2176 for (j = 0; j < num_p_filters; j++)
2178 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
2180 sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2182 sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2187 /* Factor in the cost of this filter (this is here for completeness,
2188 * but it makes no sense to have a "cost" for the NONE filter, as
2189 * it has the minimum possible computational cost - none).
2191 sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
2193 sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
2196 if (sumhi > PNG_HIMASK)
2199 sum = (sumhi << PNG_HISHIFT) + sumlo;
2206 if (filter_to_do == PNG_FILTER_SUB)
2207 /* It's the only filter so no testing is needed */
2209 png_bytep rp, lp, dp;
2211 for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
2216 for (lp = row_buf + 1; i < row_bytes;
2217 i++, rp++, lp++, dp++)
2219 *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
2221 best_row = png_ptr->sub_row;
2224 else if (filter_to_do & PNG_FILTER_SUB)
2226 png_bytep rp, dp, lp;
2227 png_uint_32 sum = 0, lmins = mins;
2231 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2232 /* We temporarily increase the "minimum sum" by the factor we
2233 * would reduce the sum of this filter, so that we can do the
2234 * early exit comparison without scaling the sum each time.
2236 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2239 png_uint_32 lmhi, lmlo;
2240 lmlo = lmins & PNG_LOMASK;
2241 lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
2243 for (j = 0; j < num_p_filters; j++)
2245 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
2247 lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2249 lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2254 lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2256 lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2259 if (lmhi > PNG_HIMASK)
2262 lmins = (lmhi << PNG_HISHIFT) + lmlo;
2266 for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
2271 sum += (v < 128) ? v : 256 - v;
2273 for (lp = row_buf + 1; i < row_bytes;
2274 i++, rp++, lp++, dp++)
2276 v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
2278 sum += (v < 128) ? v : 256 - v;
2280 if (sum > lmins) /* We are already worse, don't continue. */
2284 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2285 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2288 png_uint_32 sumhi, sumlo;
2289 sumlo = sum & PNG_LOMASK;
2290 sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
2292 for (j = 0; j < num_p_filters; j++)
2294 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
2296 sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
2298 sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
2303 sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2305 sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2308 if (sumhi > PNG_HIMASK)
2311 sum = (sumhi << PNG_HISHIFT) + sumlo;
2318 best_row = png_ptr->sub_row;
2323 if (filter_to_do == PNG_FILTER_UP)
2325 png_bytep rp, dp, pp;
2328 for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
2329 pp = prev_row + 1; i < row_bytes;
2330 i++, rp++, pp++, dp++)
2332 *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
2334 best_row = png_ptr->up_row;
2337 else if (filter_to_do & PNG_FILTER_UP)
2339 png_bytep rp, dp, pp;
2340 png_uint_32 sum = 0, lmins = mins;
2345 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2346 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2349 png_uint_32 lmhi, lmlo;
2350 lmlo = lmins & PNG_LOMASK;
2351 lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
2353 for (j = 0; j < num_p_filters; j++)
2355 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
2357 lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2359 lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2364 lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
2366 lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
2369 if (lmhi > PNG_HIMASK)
2372 lmins = (lmhi << PNG_HISHIFT) + lmlo;
2376 for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
2377 pp = prev_row + 1; i < row_bytes; i++)
2379 v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
2381 sum += (v < 128) ? v : 256 - v;
2383 if (sum > lmins) /* We are already worse, don't continue. */
2387 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2388 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2391 png_uint_32 sumhi, sumlo;
2392 sumlo = sum & PNG_LOMASK;
2393 sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
2395 for (j = 0; j < num_p_filters; j++)
2397 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
2399 sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2401 sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2406 sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
2408 sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
2411 if (sumhi > PNG_HIMASK)
2414 sum = (sumhi << PNG_HISHIFT) + sumlo;
2421 best_row = png_ptr->up_row;
2426 if (filter_to_do == PNG_FILTER_AVG)
2428 png_bytep rp, dp, pp, lp;
2430 for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
2431 pp = prev_row + 1; i < bpp; i++)
2433 *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
2435 for (lp = row_buf + 1; i < row_bytes; i++)
2437 *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
2440 best_row = png_ptr->avg_row;
2443 else if (filter_to_do & PNG_FILTER_AVG)
2445 png_bytep rp, dp, pp, lp;
2446 png_uint_32 sum = 0, lmins = mins;
2450 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2451 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2454 png_uint_32 lmhi, lmlo;
2455 lmlo = lmins & PNG_LOMASK;
2456 lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
2458 for (j = 0; j < num_p_filters; j++)
2460 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
2462 lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2464 lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2469 lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
2471 lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
2474 if (lmhi > PNG_HIMASK)
2477 lmins = (lmhi << PNG_HISHIFT) + lmlo;
2481 for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
2482 pp = prev_row + 1; i < bpp; i++)
2484 v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
2486 sum += (v < 128) ? v : 256 - v;
2488 for (lp = row_buf + 1; i < row_bytes; i++)
2491 (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
2493 sum += (v < 128) ? v : 256 - v;
2495 if (sum > lmins) /* We are already worse, don't continue. */
2499 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2500 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2503 png_uint_32 sumhi, sumlo;
2504 sumlo = sum & PNG_LOMASK;
2505 sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
2507 for (j = 0; j < num_p_filters; j++)
2509 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
2511 sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2513 sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2518 sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
2520 sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
2523 if (sumhi > PNG_HIMASK)
2526 sum = (sumhi << PNG_HISHIFT) + sumlo;
2533 best_row = png_ptr->avg_row;
2538 if (filter_to_do == PNG_FILTER_PAETH)
2540 png_bytep rp, dp, pp, cp, lp;
2542 for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
2543 pp = prev_row + 1; i < bpp; i++)
2545 *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
2548 for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
2550 int a, b, c, pa, pb, pc, p;
2564 pa = p < 0 ? -p : p;
2565 pb = pc < 0 ? -pc : pc;
2566 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
2569 p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
2571 *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
2573 best_row = png_ptr->paeth_row;
2576 else if (filter_to_do & PNG_FILTER_PAETH)
2578 png_bytep rp, dp, pp, cp, lp;
2579 png_uint_32 sum = 0, lmins = mins;
2583 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2584 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2587 png_uint_32 lmhi, lmlo;
2588 lmlo = lmins & PNG_LOMASK;
2589 lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
2591 for (j = 0; j < num_p_filters; j++)
2593 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
2595 lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2597 lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2602 lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2604 lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2607 if (lmhi > PNG_HIMASK)
2610 lmins = (lmhi << PNG_HISHIFT) + lmlo;
2614 for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
2615 pp = prev_row + 1; i < bpp; i++)
2617 v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
2619 sum += (v < 128) ? v : 256 - v;
2622 for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
2624 int a, b, c, pa, pb, pc, p;
2630 #ifndef PNG_SLOW_PAETH
2638 pa = p < 0 ? -p : p;
2639 pb = pc < 0 ? -pc : pc;
2640 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
2642 p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
2643 #else /* PNG_SLOW_PAETH */
2648 if (pa <= pb && pa <= pc)
2654 #endif /* PNG_SLOW_PAETH */
2656 v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
2658 sum += (v < 128) ? v : 256 - v;
2660 if (sum > lmins) /* We are already worse, don't continue. */
2664 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2665 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2668 png_uint_32 sumhi, sumlo;
2669 sumlo = sum & PNG_LOMASK;
2670 sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
2672 for (j = 0; j < num_p_filters; j++)
2674 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
2676 sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2678 sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2683 sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2685 sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2688 if (sumhi > PNG_HIMASK)
2691 sum = (sumhi << PNG_HISHIFT) + sumlo;
2697 best_row = png_ptr->paeth_row;
2700 #endif /* PNG_WRITE_FILTER_SUPPORTED */
2701 /* Do the actual writing of the filtered row data from the chosen filter. */
2703 png_write_filtered_row(png_ptr, best_row);
2705 #ifdef PNG_WRITE_FILTER_SUPPORTED
2706 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2707 /* Save the type of filter we picked this time for future calculations */
2708 if (png_ptr->num_prev_filters > 0)
2711 for (j = 1; j < num_p_filters; j++)
2713 png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
2715 png_ptr->prev_filters[j] = best_row[0];
2718 #endif /* PNG_WRITE_FILTER_SUPPORTED */
2722 /* Do the actual writing of a previously filtered row. */
2724 png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
2726 png_debug(1, "in png_write_filtered_row");
2728 png_debug1(2, "filter = %d", filtered_row[0]);
2729 /* Set up the zlib input buffer */
2731 png_ptr->zstream.next_in = filtered_row;
2732 png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
2733 /* Repeat until we have compressed all the data */
2736 int ret; /* Return of zlib */
2738 /* Compress the data */
2739 ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
2740 /* Check for compression errors */
2743 if (png_ptr->zstream.msg != NULL)
2744 png_error(png_ptr, png_ptr->zstream.msg);
2746 png_error(png_ptr, "zlib error");
2749 /* See if it is time to write another IDAT */
2750 if (!(png_ptr->zstream.avail_out))
2752 /* Write the IDAT and reset the zlib output buffer */
2753 png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
2754 png_ptr->zstream.next_out = png_ptr->zbuf;
2755 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
2757 /* Repeat until all data has been compressed */
2758 } while (png_ptr->zstream.avail_in);
2760 /* Swap the current and previous rows */
2761 if (png_ptr->prev_row != NULL)
2765 tptr = png_ptr->prev_row;
2766 png_ptr->prev_row = png_ptr->row_buf;
2767 png_ptr->row_buf = tptr;
2770 /* Finish row - updates counters and flushes zlib if last row */
2771 png_write_finish_row(png_ptr);
2773 #ifdef PNG_WRITE_FLUSH_SUPPORTED
2774 png_ptr->flush_rows++;
2776 if (png_ptr->flush_dist > 0 &&
2777 png_ptr->flush_rows >= png_ptr->flush_dist)
2779 png_write_flush(png_ptr);
2783 #endif /* PNG_WRITE_SUPPORTED */