2 /* pngwutil.c - utilities to write a PNG file
4 * Last changed in libpng 1.5.0 [January 6, 2011]
5 * Copyright (c) 1998-2011 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
16 #ifdef PNG_WRITE_SUPPORTED
18 #ifdef PNG_WRITE_INT_FUNCTIONS_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. Note that,
36 * the following works correctly even if png_int_32 has more than 32 bits
37 * (compare the more complex code required on read for sign extention.)
40 png_save_int_32(png_bytep buf, png_int_32 i)
42 buf[0] = (png_byte)((i >> 24) & 0xff);
43 buf[1] = (png_byte)((i >> 16) & 0xff);
44 buf[2] = (png_byte)((i >> 8) & 0xff);
45 buf[3] = (png_byte)(i & 0xff);
49 /* Place a 16-bit number into a buffer in PNG byte order.
50 * The parameter is declared unsigned int, not png_uint_16,
51 * just to avoid potential problems on pre-ANSI C compilers.
54 png_save_uint_16(png_bytep buf, unsigned int i)
56 buf[0] = (png_byte)((i >> 8) & 0xff);
57 buf[1] = (png_byte)(i & 0xff);
61 /* Simple function to write the signature. If we have already written
62 * the magic bytes of the signature, or more likely, the PNG stream is
63 * being embedded into another stream and doesn't need its own signature,
64 * we should call png_set_sig_bytes() to tell libpng how many of the
65 * bytes have already been written.
68 png_write_sig(png_structp png_ptr)
70 png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
72 #ifdef PNG_IO_STATE_SUPPORTED
73 /* Inform the I/O callback that the signature is being written */
74 png_ptr->io_state = PNG_IO_WRITING | PNG_IO_SIGNATURE;
77 /* Write the rest of the 8 byte signature */
78 png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
79 (png_size_t)(8 - png_ptr->sig_bytes));
81 if (png_ptr->sig_bytes < 3)
82 png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
85 /* Write a PNG chunk all at once. The type is an array of ASCII characters
86 * representing the chunk name. The array must be at least 4 bytes in
87 * length, and does not need to be null terminated. To be safe, pass the
88 * pre-defined chunk names here, and if you need a new one, define it
89 * where the others are defined. The length is the length of the data.
90 * All the data must be present. If that is not possible, use the
91 * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
95 png_write_chunk(png_structp png_ptr, png_const_bytep chunk_name,
96 png_const_bytep data, png_size_t length)
101 png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
102 png_write_chunk_data(png_ptr, data, (png_size_t)length);
103 png_write_chunk_end(png_ptr);
106 /* Write the start of a PNG chunk. The type is the chunk type.
107 * The total_length is the sum of the lengths of all the data you will be
108 * passing in png_write_chunk_data().
111 png_write_chunk_start(png_structp png_ptr, png_const_bytep chunk_name,
116 png_debug2(0, "Writing %s chunk, length = %lu", chunk_name,
117 (unsigned long)length);
122 #ifdef PNG_IO_STATE_SUPPORTED
123 /* Inform the I/O callback that the chunk header is being written.
124 * PNG_IO_CHUNK_HDR requires a single I/O call.
126 png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_HDR;
129 /* Write the length and the chunk name */
130 png_save_uint_32(buf, length);
131 png_memcpy(buf + 4, chunk_name, 4);
132 png_write_data(png_ptr, buf, (png_size_t)8);
134 /* Put the chunk name into png_ptr->chunk_name */
135 png_memcpy(png_ptr->chunk_name, chunk_name, 4);
137 /* Reset the crc and run it over the chunk name */
138 png_reset_crc(png_ptr);
140 png_calculate_crc(png_ptr, chunk_name, 4);
142 #ifdef PNG_IO_STATE_SUPPORTED
143 /* Inform the I/O callback that chunk data will (possibly) be written.
144 * PNG_IO_CHUNK_DATA does NOT require a specific number of I/O calls.
146 png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_DATA;
150 /* Write the data of a PNG chunk started with png_write_chunk_start().
151 * Note that multiple calls to this function are allowed, and that the
152 * sum of the lengths from these calls *must* add up to the total_length
153 * given to png_write_chunk_start().
156 png_write_chunk_data(png_structp png_ptr, png_const_bytep data,
159 /* Write the data, and run the CRC over it */
163 if (data != NULL && length > 0)
165 png_write_data(png_ptr, data, length);
167 /* Update the CRC after writing the data,
168 * in case that the user I/O routine alters it.
170 png_calculate_crc(png_ptr, data, length);
174 /* Finish a chunk started with png_write_chunk_start(). */
176 png_write_chunk_end(png_structp png_ptr)
180 if (png_ptr == NULL) return;
182 #ifdef PNG_IO_STATE_SUPPORTED
183 /* Inform the I/O callback that the chunk CRC is being written.
184 * PNG_IO_CHUNK_CRC requires a single I/O function call.
186 png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_CRC;
189 /* Write the crc in a single operation */
190 png_save_uint_32(buf, png_ptr->crc);
192 png_write_data(png_ptr, buf, (png_size_t)4);
195 #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
196 /* This pair of functions encapsulates the operation of (a) compressing a
197 * text string, and (b) issuing it later as a series of chunk data writes.
198 * The compression_state structure is shared context for these functions
199 * set up by the caller in order to make the whole mess thread-safe.
204 png_const_bytep input; /* The uncompressed input data */
205 png_size_t input_len; /* Its length */
206 int num_output_ptr; /* Number of output pointers used */
207 int max_output_ptr; /* Size of output_ptr */
208 png_bytep *output_ptr; /* Array of pointers to output */
211 /* Compress given text into storage in the png_ptr structure */
212 static int /* PRIVATE */
213 png_text_compress(png_structp png_ptr,
214 png_const_charp text, png_size_t text_len, int compression,
215 compression_state *comp)
219 comp->num_output_ptr = 0;
220 comp->max_output_ptr = 0;
221 comp->output_ptr = NULL;
225 /* We may just want to pass the text right through */
226 if (compression == PNG_TEXT_COMPRESSION_NONE)
228 comp->input = (png_const_bytep)text;
229 comp->input_len = text_len;
230 return((int)text_len);
233 if (compression >= PNG_TEXT_COMPRESSION_LAST)
235 #ifdef PNG_CONSOLE_IO_SUPPORTED
237 png_snprintf(msg, 50, "Unknown compression type %d", compression);
238 png_warning(png_ptr, msg);
240 png_warning(png_ptr, "Unknown compression type");
244 /* We can't write the chunk until we find out how much data we have,
245 * which means we need to run the compressor first and save the
246 * output. This shouldn't be a problem, as the vast majority of
247 * comments should be reasonable, but we will set up an array of
248 * malloc'd pointers to be sure.
250 * If we knew the application was well behaved, we could simplify this
251 * greatly by assuming we can always malloc an output buffer large
252 * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
253 * and malloc this directly. The only time this would be a bad idea is
254 * if we can't malloc more than 64K and we have 64K of random input
255 * data, or if the input string is incredibly large (although this
256 * wouldn't cause a failure, just a slowdown due to swapping).
259 /* Set up the compression buffers */
260 /* TODO: the following cast hides a potential overflow problem. */
261 png_ptr->zstream.avail_in = (uInt)text_len;
262 /* NOTE: assume zlib doesn't overwrite the input */
263 png_ptr->zstream.next_in = (Bytef *)text;
264 png_ptr->zstream.avail_out = png_ptr->zbuf_size;
265 png_ptr->zstream.next_out = png_ptr->zbuf;
267 /* This is the same compression loop as in png_write_row() */
270 /* Compress the data */
271 ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
276 if (png_ptr->zstream.msg != NULL)
277 png_error(png_ptr, png_ptr->zstream.msg);
280 png_error(png_ptr, "zlib error");
283 /* Check to see if we need more room */
284 if (!(png_ptr->zstream.avail_out))
286 /* Make sure the output array has room */
287 if (comp->num_output_ptr >= comp->max_output_ptr)
291 old_max = comp->max_output_ptr;
292 comp->max_output_ptr = comp->num_output_ptr + 4;
293 if (comp->output_ptr != NULL)
297 old_ptr = comp->output_ptr;
299 comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
301 (comp->max_output_ptr * png_sizeof(png_charpp)));
303 png_memcpy(comp->output_ptr, old_ptr, old_max
304 * png_sizeof(png_charp));
306 png_free(png_ptr, old_ptr);
309 comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
311 (comp->max_output_ptr * png_sizeof(png_charp)));
315 comp->output_ptr[comp->num_output_ptr] =
316 (png_bytep)png_malloc(png_ptr,
317 (png_alloc_size_t)png_ptr->zbuf_size);
319 png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
322 comp->num_output_ptr++;
324 /* and reset the buffer */
325 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
326 png_ptr->zstream.next_out = png_ptr->zbuf;
328 /* Continue until we don't have any more to compress */
329 } while (png_ptr->zstream.avail_in);
331 /* Finish the compression */
334 /* Tell zlib we are finished */
335 ret = deflate(&png_ptr->zstream, Z_FINISH);
339 /* Check to see if we need more room */
340 if (!(png_ptr->zstream.avail_out))
342 /* Check to make sure our output array has room */
343 if (comp->num_output_ptr >= comp->max_output_ptr)
347 old_max = comp->max_output_ptr;
348 comp->max_output_ptr = comp->num_output_ptr + 4;
349 if (comp->output_ptr != NULL)
353 old_ptr = comp->output_ptr;
355 /* This could be optimized to realloc() */
356 comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
357 (png_alloc_size_t)(comp->max_output_ptr *
358 png_sizeof(png_charp)));
360 png_memcpy(comp->output_ptr, old_ptr,
361 old_max * png_sizeof(png_charp));
363 png_free(png_ptr, old_ptr);
367 comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
368 (png_alloc_size_t)(comp->max_output_ptr *
369 png_sizeof(png_charp)));
373 comp->output_ptr[comp->num_output_ptr] =
374 (png_bytep)png_malloc(png_ptr,
375 (png_alloc_size_t)png_ptr->zbuf_size);
377 png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
380 comp->num_output_ptr++;
382 /* and reset the buffer pointers */
383 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
384 png_ptr->zstream.next_out = png_ptr->zbuf;
387 else if (ret != Z_STREAM_END)
389 /* We got an error */
390 if (png_ptr->zstream.msg != NULL)
391 png_error(png_ptr, png_ptr->zstream.msg);
394 png_error(png_ptr, "zlib error");
396 } while (ret != Z_STREAM_END);
398 /* Text length is number of buffers plus last buffer */
399 text_len = png_ptr->zbuf_size * comp->num_output_ptr;
401 if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
402 text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
404 return((int)text_len);
407 /* Ship the compressed text out via chunk writes */
408 static void /* PRIVATE */
409 png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
413 /* Handle the no-compression case */
416 png_write_chunk_data(png_ptr, comp->input, comp->input_len);
421 /* Write saved output buffers, if any */
422 for (i = 0; i < comp->num_output_ptr; i++)
424 png_write_chunk_data(png_ptr, comp->output_ptr[i],
425 (png_size_t)png_ptr->zbuf_size);
427 png_free(png_ptr, comp->output_ptr[i]);
430 if (comp->max_output_ptr != 0)
431 png_free(png_ptr, comp->output_ptr);
433 /* Write anything left in zbuf */
434 if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
435 png_write_chunk_data(png_ptr, png_ptr->zbuf,
436 (png_size_t)(png_ptr->zbuf_size - png_ptr->zstream.avail_out));
438 /* Reset zlib for another zTXt/iTXt or image data */
439 deflateReset(&png_ptr->zstream);
440 png_ptr->zstream.data_type = Z_BINARY;
444 /* Write the IHDR chunk, and update the png_struct with the necessary
445 * information. Note that the rest of this code depends upon this
446 * information being correct.
449 png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
450 int bit_depth, int color_type, int compression_type, int filter_type,
456 png_byte buf[13]; /* Buffer to store the IHDR info */
458 png_debug(1, "in png_write_IHDR");
460 /* Check that we have valid input data from the application info */
463 case PNG_COLOR_TYPE_GRAY:
470 #ifdef PNG_WRITE_16BIT_SUPPORTED
473 png_ptr->channels = 1; break;
477 "Invalid bit depth for grayscale image");
481 case PNG_COLOR_TYPE_RGB:
482 #ifdef PNG_WRITE_16BIT_SUPPORTED
483 if (bit_depth != 8 && bit_depth != 16)
487 png_error(png_ptr, "Invalid bit depth for RGB image");
489 png_ptr->channels = 3;
492 case PNG_COLOR_TYPE_PALETTE:
499 png_ptr->channels = 1;
503 png_error(png_ptr, "Invalid bit depth for paletted image");
507 case PNG_COLOR_TYPE_GRAY_ALPHA:
508 if (bit_depth != 8 && bit_depth != 16)
509 png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
511 png_ptr->channels = 2;
514 case PNG_COLOR_TYPE_RGB_ALPHA:
515 #ifdef PNG_WRITE_16BIT_SUPPORTED
516 if (bit_depth != 8 && bit_depth != 16)
520 png_error(png_ptr, "Invalid bit depth for RGBA image");
522 png_ptr->channels = 4;
526 png_error(png_ptr, "Invalid image color type specified");
529 if (compression_type != PNG_COMPRESSION_TYPE_BASE)
531 png_warning(png_ptr, "Invalid compression type specified");
532 compression_type = PNG_COMPRESSION_TYPE_BASE;
535 /* Write filter_method 64 (intrapixel differencing) only if
536 * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
537 * 2. Libpng did not write a PNG signature (this filter_method is only
538 * used in PNG datastreams that are embedded in MNG datastreams) and
539 * 3. The application called png_permit_mng_features with a mask that
540 * included PNG_FLAG_MNG_FILTER_64 and
541 * 4. The filter_method is 64 and
542 * 5. The color_type is RGB or RGBA
545 #ifdef PNG_MNG_FEATURES_SUPPORTED
546 !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
547 ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
548 (color_type == PNG_COLOR_TYPE_RGB ||
549 color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
550 (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
552 filter_type != PNG_FILTER_TYPE_BASE)
554 png_warning(png_ptr, "Invalid filter type specified");
555 filter_type = PNG_FILTER_TYPE_BASE;
558 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
559 if (interlace_type != PNG_INTERLACE_NONE &&
560 interlace_type != PNG_INTERLACE_ADAM7)
562 png_warning(png_ptr, "Invalid interlace type specified");
563 interlace_type = PNG_INTERLACE_ADAM7;
566 interlace_type=PNG_INTERLACE_NONE;
569 /* Save the relevent information */
570 png_ptr->bit_depth = (png_byte)bit_depth;
571 png_ptr->color_type = (png_byte)color_type;
572 png_ptr->interlaced = (png_byte)interlace_type;
573 #ifdef PNG_MNG_FEATURES_SUPPORTED
574 png_ptr->filter_type = (png_byte)filter_type;
576 png_ptr->compression_type = (png_byte)compression_type;
577 png_ptr->width = width;
578 png_ptr->height = height;
580 png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
581 png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
582 /* Set the usr info, so any transformations can modify it */
583 png_ptr->usr_width = png_ptr->width;
584 png_ptr->usr_bit_depth = png_ptr->bit_depth;
585 png_ptr->usr_channels = png_ptr->channels;
587 /* Pack the header information into the buffer */
588 png_save_uint_32(buf, width);
589 png_save_uint_32(buf + 4, height);
590 buf[8] = (png_byte)bit_depth;
591 buf[9] = (png_byte)color_type;
592 buf[10] = (png_byte)compression_type;
593 buf[11] = (png_byte)filter_type;
594 buf[12] = (png_byte)interlace_type;
596 /* Write the chunk */
597 png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
599 /* Initialize zlib with PNG info */
600 png_ptr->zstream.zalloc = png_zalloc;
601 png_ptr->zstream.zfree = png_zfree;
602 png_ptr->zstream.opaque = (voidpf)png_ptr;
604 if (!(png_ptr->do_filter))
606 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
607 png_ptr->bit_depth < 8)
608 png_ptr->do_filter = PNG_FILTER_NONE;
611 png_ptr->do_filter = PNG_ALL_FILTERS;
614 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
616 if (png_ptr->do_filter != PNG_FILTER_NONE)
617 png_ptr->zlib_strategy = Z_FILTERED;
620 png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
623 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
624 png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
626 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
627 png_ptr->zlib_mem_level = 8;
629 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
630 png_ptr->zlib_window_bits = 15;
632 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
633 png_ptr->zlib_method = 8;
635 ret = deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
636 png_ptr->zlib_method, png_ptr->zlib_window_bits,
637 png_ptr->zlib_mem_level, png_ptr->zlib_strategy);
641 if (ret == Z_VERSION_ERROR)
643 "zlib failed to initialize compressor -- version error");
645 if (ret == Z_STREAM_ERROR)
647 "zlib failed to initialize compressor -- stream error");
649 if (ret == Z_MEM_ERROR)
651 "zlib failed to initialize compressor -- mem error");
653 png_error(png_ptr, "zlib failed to initialize compressor");
656 png_ptr->zstream.next_out = png_ptr->zbuf;
657 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
658 /* libpng is not interested in zstream.data_type, so set it
659 * to a predefined value, to avoid its evaluation inside zlib
661 png_ptr->zstream.data_type = Z_BINARY;
663 png_ptr->mode = PNG_HAVE_IHDR;
666 /* Write the palette. We are careful not to trust png_color to be in the
667 * correct order for PNG, so people can redefine it to any convenient
671 png_write_PLTE(png_structp png_ptr, png_const_colorp palette,
676 png_const_colorp pal_ptr;
679 png_debug(1, "in png_write_PLTE");
682 #ifdef PNG_MNG_FEATURES_SUPPORTED
683 !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
685 num_pal == 0) || num_pal > 256)
687 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
689 png_error(png_ptr, "Invalid number of colors in palette");
694 png_warning(png_ptr, "Invalid number of colors in palette");
699 if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
702 "Ignoring request to write a PLTE chunk in grayscale PNG");
707 png_ptr->num_palette = (png_uint_16)num_pal;
708 png_debug1(3, "num_palette = %d", png_ptr->num_palette);
710 png_write_chunk_start(png_ptr, png_PLTE, (png_uint_32)(num_pal * 3));
711 #ifdef PNG_POINTER_INDEXING_SUPPORTED
713 for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
715 buf[0] = pal_ptr->red;
716 buf[1] = pal_ptr->green;
717 buf[2] = pal_ptr->blue;
718 png_write_chunk_data(png_ptr, buf, (png_size_t)3);
722 /* This is a little slower but some buggy compilers need to do this
727 for (i = 0; i < num_pal; i++)
729 buf[0] = pal_ptr[i].red;
730 buf[1] = pal_ptr[i].green;
731 buf[2] = pal_ptr[i].blue;
732 png_write_chunk_data(png_ptr, buf, (png_size_t)3);
736 png_write_chunk_end(png_ptr);
737 png_ptr->mode |= PNG_HAVE_PLTE;
740 /* Write an IDAT chunk */
742 png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
746 png_debug(1, "in png_write_IDAT");
748 /* Optimize the CMF field in the zlib stream. */
749 /* This hack of the zlib stream is compliant to the stream specification. */
750 if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
751 png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
753 unsigned int z_cmf = data[0]; /* zlib compression method and flags */
754 if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
756 /* Avoid memory underflows and multiplication overflows.
758 * The conditions below are practically always satisfied;
759 * however, they still must be checked.
762 png_ptr->height < 16384 && png_ptr->width < 16384)
764 png_uint_32 uncompressed_idat_size = png_ptr->height *
766 png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
767 unsigned int z_cinfo = z_cmf >> 4;
768 unsigned int half_z_window_size = 1 << (z_cinfo + 7);
769 while (uncompressed_idat_size <= half_z_window_size &&
770 half_z_window_size >= 256)
773 half_z_window_size >>= 1;
776 z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
778 if (data[0] != z_cmf)
781 data[0] = (png_byte)z_cmf;
782 tmp = data[1] & 0xe0;
783 tmp += 0x1f - ((z_cmf << 8) + tmp) % 0x1f;
784 data[1] = (png_byte)tmp;
791 "Invalid zlib compression method or flags in IDAT");
794 png_write_chunk(png_ptr, png_IDAT, data, length);
795 png_ptr->mode |= PNG_HAVE_IDAT;
798 /* Write an IEND chunk */
800 png_write_IEND(png_structp png_ptr)
804 png_debug(1, "in png_write_IEND");
806 png_write_chunk(png_ptr, png_IEND, NULL, (png_size_t)0);
807 png_ptr->mode |= PNG_HAVE_IEND;
810 #ifdef PNG_WRITE_gAMA_SUPPORTED
811 /* Write a gAMA chunk */
813 png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
818 png_debug(1, "in png_write_gAMA");
820 /* file_gamma is saved in 1/100,000ths */
821 png_save_uint_32(buf, (png_uint_32)file_gamma);
822 png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
826 #ifdef PNG_WRITE_sRGB_SUPPORTED
827 /* Write a sRGB chunk */
829 png_write_sRGB(png_structp png_ptr, int srgb_intent)
834 png_debug(1, "in png_write_sRGB");
836 if (srgb_intent >= PNG_sRGB_INTENT_LAST)
838 "Invalid sRGB rendering intent specified");
840 buf[0]=(png_byte)srgb_intent;
841 png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
845 #ifdef PNG_WRITE_iCCP_SUPPORTED
846 /* Write an iCCP chunk */
848 png_write_iCCP(png_structp png_ptr, png_const_charp name, int compression_type,
849 png_const_charp profile, int profile_len)
854 compression_state comp;
855 int embedded_profile_len = 0;
857 png_debug(1, "in png_write_iCCP");
859 comp.num_output_ptr = 0;
860 comp.max_output_ptr = 0;
861 comp.output_ptr = NULL;
865 if ((name_len = png_check_keyword(png_ptr, name, &new_name)) == 0)
868 if (compression_type != PNG_COMPRESSION_TYPE_BASE)
869 png_warning(png_ptr, "Unknown compression type in iCCP chunk");
875 embedded_profile_len =
876 ((*( (png_const_bytep)profile ))<<24) |
877 ((*( (png_const_bytep)profile + 1))<<16) |
878 ((*( (png_const_bytep)profile + 2))<< 8) |
879 ((*( (png_const_bytep)profile + 3)) );
881 if (embedded_profile_len < 0)
884 "Embedded profile length in iCCP chunk is negative");
886 png_free(png_ptr, new_name);
890 if (profile_len < embedded_profile_len)
893 "Embedded profile length too large in iCCP chunk");
895 png_free(png_ptr, new_name);
899 if (profile_len > embedded_profile_len)
902 "Truncating profile to actual length in iCCP chunk");
904 profile_len = embedded_profile_len;
908 profile_len = png_text_compress(png_ptr, profile,
909 (png_size_t)profile_len, PNG_COMPRESSION_TYPE_BASE, &comp);
911 /* Make sure we include the NULL after the name and the compression type */
912 png_write_chunk_start(png_ptr, png_iCCP,
913 (png_uint_32)(name_len + profile_len + 2));
915 new_name[name_len + 1] = 0x00;
917 png_write_chunk_data(png_ptr, (png_bytep)new_name,
918 (png_size_t)(name_len + 2));
921 png_write_compressed_data_out(png_ptr, &comp);
923 png_write_chunk_end(png_ptr);
924 png_free(png_ptr, new_name);
928 #ifdef PNG_WRITE_sPLT_SUPPORTED
929 /* Write a sPLT chunk */
931 png_write_sPLT(png_structp png_ptr, png_const_sPLT_tp spalette)
936 png_byte entrybuf[10];
937 png_size_t entry_size = (spalette->depth == 8 ? 6 : 10);
938 png_size_t palette_size = entry_size * spalette->nentries;
940 #ifndef PNG_POINTER_INDEXING_SUPPORTED
944 png_debug(1, "in png_write_sPLT");
946 if ((name_len = png_check_keyword(png_ptr,spalette->name, &new_name))==0)
949 /* Make sure we include the NULL after the name */
950 png_write_chunk_start(png_ptr, png_sPLT,
951 (png_uint_32)(name_len + 2 + palette_size));
953 png_write_chunk_data(png_ptr, (png_bytep)new_name,
954 (png_size_t)(name_len + 1));
956 png_write_chunk_data(png_ptr, &spalette->depth, (png_size_t)1);
958 /* Loop through each palette entry, writing appropriately */
959 #ifdef PNG_POINTER_INDEXING_SUPPORTED
960 for (ep = spalette->entries; ep<spalette->entries + spalette->nentries; ep++)
962 if (spalette->depth == 8)
964 entrybuf[0] = (png_byte)ep->red;
965 entrybuf[1] = (png_byte)ep->green;
966 entrybuf[2] = (png_byte)ep->blue;
967 entrybuf[3] = (png_byte)ep->alpha;
968 png_save_uint_16(entrybuf + 4, ep->frequency);
973 png_save_uint_16(entrybuf + 0, ep->red);
974 png_save_uint_16(entrybuf + 2, ep->green);
975 png_save_uint_16(entrybuf + 4, ep->blue);
976 png_save_uint_16(entrybuf + 6, ep->alpha);
977 png_save_uint_16(entrybuf + 8, ep->frequency);
980 png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
983 ep=spalette->entries;
984 for (i = 0; i>spalette->nentries; i++)
986 if (spalette->depth == 8)
988 entrybuf[0] = (png_byte)ep[i].red;
989 entrybuf[1] = (png_byte)ep[i].green;
990 entrybuf[2] = (png_byte)ep[i].blue;
991 entrybuf[3] = (png_byte)ep[i].alpha;
992 png_save_uint_16(entrybuf + 4, ep[i].frequency);
997 png_save_uint_16(entrybuf + 0, ep[i].red);
998 png_save_uint_16(entrybuf + 2, ep[i].green);
999 png_save_uint_16(entrybuf + 4, ep[i].blue);
1000 png_save_uint_16(entrybuf + 6, ep[i].alpha);
1001 png_save_uint_16(entrybuf + 8, ep[i].frequency);
1004 png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
1008 png_write_chunk_end(png_ptr);
1009 png_free(png_ptr, new_name);
1013 #ifdef PNG_WRITE_sBIT_SUPPORTED
1014 /* Write the sBIT chunk */
1016 png_write_sBIT(png_structp png_ptr, png_const_color_8p sbit, int color_type)
1022 png_debug(1, "in png_write_sBIT");
1024 /* Make sure we don't depend upon the order of PNG_COLOR_8 */
1025 if (color_type & PNG_COLOR_MASK_COLOR)
1029 maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
1030 png_ptr->usr_bit_depth);
1032 if (sbit->red == 0 || sbit->red > maxbits ||
1033 sbit->green == 0 || sbit->green > maxbits ||
1034 sbit->blue == 0 || sbit->blue > maxbits)
1036 png_warning(png_ptr, "Invalid sBIT depth specified");
1041 buf[1] = sbit->green;
1042 buf[2] = sbit->blue;
1048 if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
1050 png_warning(png_ptr, "Invalid sBIT depth specified");
1054 buf[0] = sbit->gray;
1058 if (color_type & PNG_COLOR_MASK_ALPHA)
1060 if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
1062 png_warning(png_ptr, "Invalid sBIT depth specified");
1066 buf[size++] = sbit->alpha;
1069 png_write_chunk(png_ptr, png_sBIT, buf, size);
1073 #ifdef PNG_WRITE_cHRM_SUPPORTED
1074 /* Write the cHRM chunk */
1076 png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
1077 png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
1078 png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
1079 png_fixed_point blue_y)
1084 png_debug(1, "in png_write_cHRM");
1086 /* Each value is saved in 1/100,000ths */
1087 #ifdef PNG_CHECK_cHRM_SUPPORTED
1088 if (png_check_cHRM_fixed(png_ptr, white_x, white_y, red_x, red_y,
1089 green_x, green_y, blue_x, blue_y))
1092 png_save_uint_32(buf, (png_uint_32)white_x);
1093 png_save_uint_32(buf + 4, (png_uint_32)white_y);
1095 png_save_uint_32(buf + 8, (png_uint_32)red_x);
1096 png_save_uint_32(buf + 12, (png_uint_32)red_y);
1098 png_save_uint_32(buf + 16, (png_uint_32)green_x);
1099 png_save_uint_32(buf + 20, (png_uint_32)green_y);
1101 png_save_uint_32(buf + 24, (png_uint_32)blue_x);
1102 png_save_uint_32(buf + 28, (png_uint_32)blue_y);
1104 png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
1109 #ifdef PNG_WRITE_tRNS_SUPPORTED
1110 /* Write the tRNS chunk */
1112 png_write_tRNS(png_structp png_ptr, png_const_bytep trans_alpha,
1113 png_const_color_16p tran, int num_trans, int color_type)
1118 png_debug(1, "in png_write_tRNS");
1120 if (color_type == PNG_COLOR_TYPE_PALETTE)
1122 if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
1124 png_warning(png_ptr, "Invalid number of transparent colors specified");
1128 /* Write the chunk out as it is */
1129 png_write_chunk(png_ptr, png_tRNS, trans_alpha, (png_size_t)num_trans);
1132 else if (color_type == PNG_COLOR_TYPE_GRAY)
1134 /* One 16 bit value */
1135 if (tran->gray >= (1 << png_ptr->bit_depth))
1137 png_warning(png_ptr,
1138 "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
1143 png_save_uint_16(buf, tran->gray);
1144 png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
1147 else if (color_type == PNG_COLOR_TYPE_RGB)
1149 /* Three 16 bit values */
1150 png_save_uint_16(buf, tran->red);
1151 png_save_uint_16(buf + 2, tran->green);
1152 png_save_uint_16(buf + 4, tran->blue);
1153 #ifdef PNG_WRITE_16BIT_SUPPORTED
1154 if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
1156 if (buf[0] | buf[2] | buf[4])
1159 png_warning(png_ptr,
1160 "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
1164 png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
1169 png_warning(png_ptr, "Can't write tRNS with an alpha channel");
1174 #ifdef PNG_WRITE_bKGD_SUPPORTED
1175 /* Write the background chunk */
1177 png_write_bKGD(png_structp png_ptr, png_const_color_16p back, int color_type)
1182 png_debug(1, "in png_write_bKGD");
1184 if (color_type == PNG_COLOR_TYPE_PALETTE)
1187 #ifdef PNG_MNG_FEATURES_SUPPORTED
1188 (png_ptr->num_palette ||
1189 (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
1191 back->index >= png_ptr->num_palette)
1193 png_warning(png_ptr, "Invalid background palette index");
1197 buf[0] = back->index;
1198 png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
1201 else if (color_type & PNG_COLOR_MASK_COLOR)
1203 png_save_uint_16(buf, back->red);
1204 png_save_uint_16(buf + 2, back->green);
1205 png_save_uint_16(buf + 4, back->blue);
1206 #ifdef PNG_WRITE_16BIT_SUPPORTED
1207 if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
1209 if (buf[0] | buf[2] | buf[4])
1212 png_warning(png_ptr,
1213 "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
1218 png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
1223 if (back->gray >= (1 << png_ptr->bit_depth))
1225 png_warning(png_ptr,
1226 "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
1231 png_save_uint_16(buf, back->gray);
1232 png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
1237 #ifdef PNG_WRITE_hIST_SUPPORTED
1238 /* Write the histogram */
1240 png_write_hIST(png_structp png_ptr, png_const_uint_16p hist, int num_hist)
1246 png_debug(1, "in png_write_hIST");
1248 if (num_hist > (int)png_ptr->num_palette)
1250 png_debug2(3, "num_hist = %d, num_palette = %d", num_hist,
1251 png_ptr->num_palette);
1253 png_warning(png_ptr, "Invalid number of histogram entries specified");
1257 png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
1259 for (i = 0; i < num_hist; i++)
1261 png_save_uint_16(buf, hist[i]);
1262 png_write_chunk_data(png_ptr, buf, (png_size_t)2);
1265 png_write_chunk_end(png_ptr);
1269 #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
1270 defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
1271 /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
1272 * and if invalid, correct the keyword rather than discarding the entire
1273 * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
1274 * length, forbids leading or trailing whitespace, multiple internal spaces,
1275 * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
1277 * The new_key is allocated to hold the corrected keyword and must be freed
1278 * by the calling routine. This avoids problems with trying to write to
1279 * static keywords without having to have duplicate copies of the strings.
1281 png_size_t /* PRIVATE */
1282 png_check_keyword(png_structp png_ptr, png_const_charp key, png_charpp new_key)
1285 png_const_charp ikp;
1290 png_debug(1, "in png_check_keyword");
1294 if (key == NULL || (key_len = png_strlen(key)) == 0)
1296 png_warning(png_ptr, "zero length keyword");
1297 return ((png_size_t)0);
1300 png_debug1(2, "Keyword to be checked is '%s'", key);
1302 *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
1304 if (*new_key == NULL)
1306 png_warning(png_ptr, "Out of memory while procesing keyword");
1307 return ((png_size_t)0);
1310 /* Replace non-printing characters with a blank and print a warning */
1311 for (ikp = key, dp = *new_key; *ikp != '\0'; ikp++, dp++)
1313 if ((png_byte)*ikp < 0x20 ||
1314 ((png_byte)*ikp > 0x7E && (png_byte)*ikp < 0xA1))
1316 #ifdef PNG_CONSOLE_IO_SUPPORTED
1319 png_snprintf(msg, 40,
1320 "invalid keyword character 0x%02X", (png_byte)*ikp);
1321 png_warning(png_ptr, msg);
1323 png_warning(png_ptr, "invalid character in keyword");
1335 /* Remove any trailing white space. */
1336 kp = *new_key + key_len - 1;
1339 png_warning(png_ptr, "trailing spaces removed from keyword");
1348 /* Remove any leading white space. */
1352 png_warning(png_ptr, "leading spaces removed from keyword");
1361 png_debug1(2, "Checking for multiple internal spaces in '%s'", kp);
1363 /* Remove multiple internal spaces. */
1364 for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
1366 if (*kp == ' ' && kflag == 0)
1372 else if (*kp == ' ')
1386 png_warning(png_ptr, "extra interior spaces removed from keyword");
1390 png_free(png_ptr, *new_key);
1391 png_warning(png_ptr, "Zero length keyword");
1396 png_warning(png_ptr, "keyword length must be 1 - 79 characters");
1397 (*new_key)[79] = '\0';
1405 #ifdef PNG_WRITE_tEXt_SUPPORTED
1406 /* Write a tEXt chunk */
1408 png_write_tEXt(png_structp png_ptr, png_const_charp key, png_const_charp text,
1409 png_size_t text_len)
1415 png_debug(1, "in png_write_tEXt");
1417 if ((key_len = png_check_keyword(png_ptr, key, &new_key))==0)
1420 if (text == NULL || *text == '\0')
1424 text_len = png_strlen(text);
1426 /* Make sure we include the 0 after the key */
1427 png_write_chunk_start(png_ptr, png_tEXt,
1428 (png_uint_32)(key_len + text_len + 1));
1430 * We leave it to the application to meet PNG-1.0 requirements on the
1431 * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
1432 * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
1433 * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
1435 png_write_chunk_data(png_ptr, (png_bytep)new_key,
1436 (png_size_t)(key_len + 1));
1439 png_write_chunk_data(png_ptr, (png_const_bytep)text,
1440 (png_size_t)text_len);
1442 png_write_chunk_end(png_ptr);
1443 png_free(png_ptr, new_key);
1447 #ifdef PNG_WRITE_zTXt_SUPPORTED
1448 /* Write a compressed text chunk */
1450 png_write_zTXt(png_structp png_ptr, png_const_charp key, png_const_charp text,
1451 png_size_t text_len, int compression)
1457 compression_state comp;
1459 png_debug(1, "in png_write_zTXt");
1461 comp.num_output_ptr = 0;
1462 comp.max_output_ptr = 0;
1463 comp.output_ptr = NULL;
1467 if ((key_len = png_check_keyword(png_ptr, key, &new_key)) == 0)
1469 png_free(png_ptr, new_key);
1473 if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
1475 png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
1476 png_free(png_ptr, new_key);
1480 text_len = png_strlen(text);
1482 /* Compute the compressed data; do it now for the length */
1483 text_len = png_text_compress(png_ptr, text, text_len, compression,
1486 /* Write start of chunk */
1487 png_write_chunk_start(png_ptr, png_zTXt,
1488 (png_uint_32)(key_len+text_len + 2));
1491 png_write_chunk_data(png_ptr, (png_bytep)new_key,
1492 (png_size_t)(key_len + 1));
1494 png_free(png_ptr, new_key);
1496 buf = (png_byte)compression;
1498 /* Write compression */
1499 png_write_chunk_data(png_ptr, &buf, (png_size_t)1);
1501 /* Write the compressed data */
1502 png_write_compressed_data_out(png_ptr, &comp);
1504 /* Close the chunk */
1505 png_write_chunk_end(png_ptr);
1509 #ifdef PNG_WRITE_iTXt_SUPPORTED
1510 /* Write an iTXt chunk */
1512 png_write_iTXt(png_structp png_ptr, int compression, png_const_charp key,
1513 png_const_charp lang, png_const_charp lang_key, png_const_charp text)
1516 png_size_t lang_len, key_len, lang_key_len, text_len;
1518 png_charp new_key = NULL;
1520 compression_state comp;
1522 png_debug(1, "in png_write_iTXt");
1524 comp.num_output_ptr = 0;
1525 comp.max_output_ptr = 0;
1526 comp.output_ptr = NULL;
1529 if ((key_len = png_check_keyword(png_ptr, key, &new_key)) == 0)
1532 if ((lang_len = png_check_keyword(png_ptr, lang, &new_lang)) == 0)
1534 png_warning(png_ptr, "Empty language field in iTXt chunk");
1539 if (lang_key == NULL)
1543 lang_key_len = png_strlen(lang_key);
1549 text_len = png_strlen(text);
1551 /* Compute the compressed data; do it now for the length */
1552 text_len = png_text_compress(png_ptr, text, text_len, compression - 2,
1556 /* Make sure we include the compression flag, the compression byte,
1557 * and the NULs after the key, lang, and lang_key parts
1560 png_write_chunk_start(png_ptr, png_iTXt, (png_uint_32)(
1561 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
1567 /* We leave it to the application to meet PNG-1.0 requirements on the
1568 * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
1569 * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
1570 * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
1572 png_write_chunk_data(png_ptr, (png_bytep)new_key, (png_size_t)(key_len + 1));
1574 /* Set the compression flag */
1575 if (compression == PNG_ITXT_COMPRESSION_NONE ||
1576 compression == PNG_TEXT_COMPRESSION_NONE)
1579 else /* compression == PNG_ITXT_COMPRESSION_zTXt */
1582 /* Set the compression method */
1585 png_write_chunk_data(png_ptr, cbuf, (png_size_t)2);
1588 png_write_chunk_data(png_ptr, (new_lang ? (png_const_bytep)new_lang : cbuf),
1589 (png_size_t)(lang_len + 1));
1591 png_write_chunk_data(png_ptr, (lang_key ? (png_const_bytep)lang_key : cbuf),
1592 (png_size_t)(lang_key_len + 1));
1594 png_write_compressed_data_out(png_ptr, &comp);
1596 png_write_chunk_end(png_ptr);
1598 png_free(png_ptr, new_key);
1599 png_free(png_ptr, new_lang);
1603 #ifdef PNG_WRITE_oFFs_SUPPORTED
1604 /* Write the oFFs chunk */
1606 png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
1612 png_debug(1, "in png_write_oFFs");
1614 if (unit_type >= PNG_OFFSET_LAST)
1615 png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
1617 png_save_int_32(buf, x_offset);
1618 png_save_int_32(buf + 4, y_offset);
1619 buf[8] = (png_byte)unit_type;
1621 png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
1624 #ifdef PNG_WRITE_pCAL_SUPPORTED
1625 /* Write the pCAL chunk (described in the PNG extensions document) */
1627 png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
1628 png_int_32 X1, int type, int nparams, png_const_charp units,
1632 png_size_t purpose_len, units_len, total_len;
1633 png_uint_32p params_len;
1635 png_charp new_purpose;
1638 png_debug1(1, "in png_write_pCAL (%d parameters)", nparams);
1640 if (type >= PNG_EQUATION_LAST)
1641 png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
1643 purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
1644 png_debug1(3, "pCAL purpose length = %d", (int)purpose_len);
1645 units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
1646 png_debug1(3, "pCAL units length = %d", (int)units_len);
1647 total_len = purpose_len + units_len + 10;
1649 params_len = (png_uint_32p)png_malloc(png_ptr,
1650 (png_alloc_size_t)(nparams * png_sizeof(png_uint_32)));
1652 /* Find the length of each parameter, making sure we don't count the
1653 * null terminator for the last parameter.
1655 for (i = 0; i < nparams; i++)
1657 params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
1658 png_debug2(3, "pCAL parameter %d length = %lu", i,
1659 (unsigned long)params_len[i]);
1660 total_len += (png_size_t)params_len[i];
1663 png_debug1(3, "pCAL total length = %d", (int)total_len);
1664 png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
1665 png_write_chunk_data(png_ptr, (png_const_bytep)new_purpose,
1666 (png_size_t)purpose_len);
1667 png_save_int_32(buf, X0);
1668 png_save_int_32(buf + 4, X1);
1669 buf[8] = (png_byte)type;
1670 buf[9] = (png_byte)nparams;
1671 png_write_chunk_data(png_ptr, buf, (png_size_t)10);
1672 png_write_chunk_data(png_ptr, (png_const_bytep)units, (png_size_t)units_len);
1674 png_free(png_ptr, new_purpose);
1676 for (i = 0; i < nparams; i++)
1678 png_write_chunk_data(png_ptr, (png_const_bytep)params[i],
1679 (png_size_t)params_len[i]);
1682 png_free(png_ptr, params_len);
1683 png_write_chunk_end(png_ptr);
1687 #ifdef PNG_WRITE_sCAL_SUPPORTED
1688 /* Write the sCAL chunk */
1690 png_write_sCAL_s(png_structp png_ptr, int unit, png_const_charp width,
1691 png_const_charp height)
1695 png_size_t wlen, hlen, total_len;
1697 png_debug(1, "in png_write_sCAL_s");
1699 wlen = png_strlen(width);
1700 hlen = png_strlen(height);
1701 total_len = wlen + hlen + 2;
1705 png_warning(png_ptr, "Can't write sCAL (buffer too small)");
1709 buf[0] = (png_byte)unit;
1710 png_memcpy(buf + 1, width, wlen + 1); /* Append the '\0' here */
1711 png_memcpy(buf + wlen + 2, height, hlen); /* Do NOT append the '\0' here */
1713 png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);
1714 png_write_chunk(png_ptr, png_sCAL, buf, total_len);
1718 #ifdef PNG_WRITE_pHYs_SUPPORTED
1719 /* Write the pHYs chunk */
1721 png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
1722 png_uint_32 y_pixels_per_unit,
1728 png_debug(1, "in png_write_pHYs");
1730 if (unit_type >= PNG_RESOLUTION_LAST)
1731 png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
1733 png_save_uint_32(buf, x_pixels_per_unit);
1734 png_save_uint_32(buf + 4, y_pixels_per_unit);
1735 buf[8] = (png_byte)unit_type;
1737 png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
1741 #ifdef PNG_WRITE_tIME_SUPPORTED
1742 /* Write the tIME chunk. Use either png_convert_from_struct_tm()
1743 * or png_convert_from_time_t(), or fill in the structure yourself.
1746 png_write_tIME(png_structp png_ptr, png_const_timep mod_time)
1751 png_debug(1, "in png_write_tIME");
1753 if (mod_time->month > 12 || mod_time->month < 1 ||
1754 mod_time->day > 31 || mod_time->day < 1 ||
1755 mod_time->hour > 23 || mod_time->second > 60)
1757 png_warning(png_ptr, "Invalid time specified for tIME chunk");
1761 png_save_uint_16(buf, mod_time->year);
1762 buf[2] = mod_time->month;
1763 buf[3] = mod_time->day;
1764 buf[4] = mod_time->hour;
1765 buf[5] = mod_time->minute;
1766 buf[6] = mod_time->second;
1768 png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
1772 /* Initializes the row writing capability of libpng */
1774 png_write_start_row(png_structp png_ptr)
1776 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
1777 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1779 /* Start of interlace block */
1780 int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1782 /* Offset to next interlace block */
1783 int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1785 /* Start of interlace block in the y direction */
1786 int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
1788 /* Offset to next interlace block in the y direction */
1789 int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
1792 png_size_t buf_size;
1794 png_debug(1, "in png_write_start_row");
1796 buf_size = (png_size_t)(PNG_ROWBYTES(
1797 png_ptr->usr_channels*png_ptr->usr_bit_depth, png_ptr->width) + 1);
1799 /* Set up row buffer */
1800 png_ptr->row_buf = (png_bytep)png_malloc(png_ptr,
1801 (png_alloc_size_t)buf_size);
1803 png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
1805 #ifdef PNG_WRITE_FILTER_SUPPORTED
1806 /* Set up filtering buffer, if using this filter */
1807 if (png_ptr->do_filter & PNG_FILTER_SUB)
1809 png_ptr->sub_row = (png_bytep)png_malloc(png_ptr, png_ptr->rowbytes + 1);
1811 png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
1814 /* We only need to keep the previous row if we are using one of these. */
1815 if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
1817 /* Set up previous row buffer */
1818 png_ptr->prev_row = (png_bytep)png_calloc(png_ptr,
1819 (png_alloc_size_t)buf_size);
1821 if (png_ptr->do_filter & PNG_FILTER_UP)
1823 png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
1824 png_ptr->rowbytes + 1);
1826 png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
1829 if (png_ptr->do_filter & PNG_FILTER_AVG)
1831 png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
1832 png_ptr->rowbytes + 1);
1834 png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
1837 if (png_ptr->do_filter & PNG_FILTER_PAETH)
1839 png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
1840 png_ptr->rowbytes + 1);
1842 png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
1845 #endif /* PNG_WRITE_FILTER_SUPPORTED */
1847 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
1848 /* If interlaced, we need to set up width and height of pass */
1849 if (png_ptr->interlaced)
1851 if (!(png_ptr->transformations & PNG_INTERLACE))
1853 png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
1854 png_pass_ystart[0]) / png_pass_yinc[0];
1856 png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
1857 png_pass_start[0]) / png_pass_inc[0];
1862 png_ptr->num_rows = png_ptr->height;
1863 png_ptr->usr_width = png_ptr->width;
1870 png_ptr->num_rows = png_ptr->height;
1871 png_ptr->usr_width = png_ptr->width;
1874 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
1875 png_ptr->zstream.next_out = png_ptr->zbuf;
1878 /* Internal use only. Called when finished processing a row of data. */
1880 png_write_finish_row(png_structp png_ptr)
1882 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
1883 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1885 /* Start of interlace block */
1886 int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1888 /* Offset to next interlace block */
1889 int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1891 /* Start of interlace block in the y direction */
1892 int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
1894 /* Offset to next interlace block in the y direction */
1895 int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
1900 png_debug(1, "in png_write_finish_row");
1903 png_ptr->row_number++;
1905 /* See if we are done */
1906 if (png_ptr->row_number < png_ptr->num_rows)
1909 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
1910 /* If interlaced, go to next pass */
1911 if (png_ptr->interlaced)
1913 png_ptr->row_number = 0;
1914 if (png_ptr->transformations & PNG_INTERLACE)
1921 /* Loop until we find a non-zero width or height pass */
1926 if (png_ptr->pass >= 7)
1929 png_ptr->usr_width = (png_ptr->width +
1930 png_pass_inc[png_ptr->pass] - 1 -
1931 png_pass_start[png_ptr->pass]) /
1932 png_pass_inc[png_ptr->pass];
1934 png_ptr->num_rows = (png_ptr->height +
1935 png_pass_yinc[png_ptr->pass] - 1 -
1936 png_pass_ystart[png_ptr->pass]) /
1937 png_pass_yinc[png_ptr->pass];
1939 if (png_ptr->transformations & PNG_INTERLACE)
1942 } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
1946 /* Reset the row above the image for the next pass */
1947 if (png_ptr->pass < 7)
1949 if (png_ptr->prev_row != NULL)
1950 png_memset(png_ptr->prev_row, 0,
1951 (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
1952 png_ptr->usr_bit_depth, png_ptr->width)) + 1);
1959 /* If we get here, we've just written the last row, so we need
1960 to flush the compressor */
1963 /* Tell the compressor we are done */
1964 ret = deflate(&png_ptr->zstream, Z_FINISH);
1966 /* Check for an error */
1969 /* Check to see if we need more room */
1970 if (!(png_ptr->zstream.avail_out))
1972 png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
1973 png_ptr->zstream.next_out = png_ptr->zbuf;
1974 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
1978 else if (ret != Z_STREAM_END)
1980 if (png_ptr->zstream.msg != NULL)
1981 png_error(png_ptr, png_ptr->zstream.msg);
1984 png_error(png_ptr, "zlib error");
1986 } while (ret != Z_STREAM_END);
1988 /* Write any extra space */
1989 if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
1991 png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
1992 png_ptr->zstream.avail_out);
1995 deflateReset(&png_ptr->zstream);
1996 png_ptr->zstream.data_type = Z_BINARY;
1999 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
2000 /* Pick out the correct pixels for the interlace pass.
2001 * The basic idea here is to go through the row with a source
2002 * pointer and a destination pointer (sp and dp), and copy the
2003 * correct pixels for the pass. As the row gets compacted,
2004 * sp will always be >= dp, so we should never overwrite anything.
2005 * See the default: case for the easiest code to understand.
2008 png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
2010 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
2012 /* Start of interlace block */
2013 int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
2015 /* Offset to next interlace block */
2016 int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
2018 png_debug(1, "in png_do_write_interlace");
2020 /* We don't have to do anything on the last pass (6) */
2023 /* Each pixel depth is handled separately */
2024 switch (row_info->pixel_depth)
2034 png_uint_32 row_width = row_info->width;
2040 for (i = png_pass_start[pass]; i < row_width;
2041 i += png_pass_inc[pass])
2043 sp = row + (png_size_t)(i >> 3);
2044 value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
2045 d |= (value << shift);
2050 *dp++ = (png_byte)d;
2072 png_uint_32 row_width = row_info->width;
2078 for (i = png_pass_start[pass]; i < row_width;
2079 i += png_pass_inc[pass])
2081 sp = row + (png_size_t)(i >> 2);
2082 value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
2083 d |= (value << shift);
2088 *dp++ = (png_byte)d;
2109 png_uint_32 row_width = row_info->width;
2114 for (i = png_pass_start[pass]; i < row_width;
2115 i += png_pass_inc[pass])
2117 sp = row + (png_size_t)(i >> 1);
2118 value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
2119 d |= (value << shift);
2124 *dp++ = (png_byte)d;
2142 png_uint_32 row_width = row_info->width;
2143 png_size_t pixel_bytes;
2145 /* Start at the beginning */
2148 /* Find out how many bytes each pixel takes up */
2149 pixel_bytes = (row_info->pixel_depth >> 3);
2151 /* Loop through the row, only looking at the pixels that matter */
2152 for (i = png_pass_start[pass]; i < row_width;
2153 i += png_pass_inc[pass])
2155 /* Find out where the original pixel is */
2156 sp = row + (png_size_t)i * pixel_bytes;
2158 /* Move the pixel */
2160 png_memcpy(dp, sp, pixel_bytes);
2168 /* Set new row width */
2169 row_info->width = (row_info->width +
2170 png_pass_inc[pass] - 1 -
2171 png_pass_start[pass]) /
2174 row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
2180 /* This filters the row, chooses which filter to use, if it has not already
2181 * been specified by the application, and then writes the row out with the
2184 #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
2185 #define PNG_HISHIFT 10
2186 #define PNG_LOMASK ((png_uint_32)0xffffL)
2187 #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
2189 png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
2192 #ifdef PNG_WRITE_FILTER_SUPPORTED
2193 png_bytep prev_row, row_buf;
2194 png_uint_32 mins, bpp;
2195 png_byte filter_to_do = png_ptr->do_filter;
2196 png_size_t row_bytes = row_info->rowbytes;
2197 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2198 int num_p_filters = (int)png_ptr->num_prev_filters;
2201 png_debug(1, "in png_write_find_filter");
2203 #ifndef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2204 if (png_ptr->row_number == 0 && filter_to_do == PNG_ALL_FILTERS)
2206 /* These will never be selected so we need not test them. */
2207 filter_to_do &= ~(PNG_FILTER_UP | PNG_FILTER_PAETH);
2211 /* Find out how many bytes offset each pixel is */
2212 bpp = (row_info->pixel_depth + 7) >> 3;
2214 prev_row = png_ptr->prev_row;
2216 best_row = png_ptr->row_buf;
2217 #ifdef PNG_WRITE_FILTER_SUPPORTED
2221 /* The prediction method we use is to find which method provides the
2222 * smallest value when summing the absolute values of the distances
2223 * from zero, using anything >= 128 as negative numbers. This is known
2224 * as the "minimum sum of absolute differences" heuristic. Other
2225 * heuristics are the "weighted minimum sum of absolute differences"
2226 * (experimental and can in theory improve compression), and the "zlib
2227 * predictive" method (not implemented yet), which does test compressions
2228 * of lines using different filter methods, and then chooses the
2229 * (series of) filter(s) that give minimum compressed data size (VERY
2230 * computationally expensive).
2232 * GRR 980525: consider also
2234 * (1) minimum sum of absolute differences from running average (i.e.,
2235 * keep running sum of non-absolute differences & count of bytes)
2236 * [track dispersion, too? restart average if dispersion too large?]
2238 * (1b) minimum sum of absolute differences from sliding average, probably
2239 * with window size <= deflate window (usually 32K)
2241 * (2) minimum sum of squared differences from zero or running average
2242 * (i.e., ~ root-mean-square approach)
2246 /* We don't need to test the 'no filter' case if this is the only filter
2247 * that has been chosen, as it doesn't actually do anything to the data.
2249 if ((filter_to_do & PNG_FILTER_NONE) && filter_to_do != PNG_FILTER_NONE)
2252 png_uint_32 sum = 0;
2256 for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
2259 sum += (v < 128) ? v : 256 - v;
2262 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2263 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2265 png_uint_32 sumhi, sumlo;
2267 sumlo = sum & PNG_LOMASK;
2268 sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
2270 /* Reduce the sum if we match any of the previous rows */
2271 for (j = 0; j < num_p_filters; j++)
2273 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
2275 sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2278 sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2283 /* Factor in the cost of this filter (this is here for completeness,
2284 * but it makes no sense to have a "cost" for the NONE filter, as
2285 * it has the minimum possible computational cost - none).
2287 sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
2290 sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
2293 if (sumhi > PNG_HIMASK)
2297 sum = (sumhi << PNG_HISHIFT) + sumlo;
2304 if (filter_to_do == PNG_FILTER_SUB)
2305 /* It's the only filter so no testing is needed */
2307 png_bytep rp, lp, dp;
2310 for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
2316 for (lp = row_buf + 1; i < row_bytes;
2317 i++, rp++, lp++, dp++)
2319 *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
2322 best_row = png_ptr->sub_row;
2325 else if (filter_to_do & PNG_FILTER_SUB)
2327 png_bytep rp, dp, lp;
2328 png_uint_32 sum = 0, lmins = mins;
2332 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2333 /* We temporarily increase the "minimum sum" by the factor we
2334 * would reduce the sum of this filter, so that we can do the
2335 * early exit comparison without scaling the sum each time.
2337 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2340 png_uint_32 lmhi, lmlo;
2341 lmlo = lmins & PNG_LOMASK;
2342 lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
2344 for (j = 0; j < num_p_filters; j++)
2346 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
2348 lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2351 lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2356 lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2359 lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2362 if (lmhi > PNG_HIMASK)
2366 lmins = (lmhi << PNG_HISHIFT) + lmlo;
2370 for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
2375 sum += (v < 128) ? v : 256 - v;
2378 for (lp = row_buf + 1; i < row_bytes;
2379 i++, rp++, lp++, dp++)
2381 v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
2383 sum += (v < 128) ? v : 256 - v;
2385 if (sum > lmins) /* We are already worse, don't continue. */
2389 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2390 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2393 png_uint_32 sumhi, sumlo;
2394 sumlo = sum & PNG_LOMASK;
2395 sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
2397 for (j = 0; j < num_p_filters; j++)
2399 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
2401 sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
2404 sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
2409 sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2412 sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2415 if (sumhi > PNG_HIMASK)
2419 sum = (sumhi << PNG_HISHIFT) + sumlo;
2426 best_row = png_ptr->sub_row;
2431 if (filter_to_do == PNG_FILTER_UP)
2433 png_bytep rp, dp, pp;
2436 for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
2437 pp = prev_row + 1; i < row_bytes;
2438 i++, rp++, pp++, dp++)
2440 *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
2443 best_row = png_ptr->up_row;
2446 else if (filter_to_do & PNG_FILTER_UP)
2448 png_bytep rp, dp, pp;
2449 png_uint_32 sum = 0, lmins = mins;
2454 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2455 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2458 png_uint_32 lmhi, lmlo;
2459 lmlo = lmins & PNG_LOMASK;
2460 lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
2462 for (j = 0; j < num_p_filters; j++)
2464 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
2466 lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2469 lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2474 lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
2477 lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
2480 if (lmhi > PNG_HIMASK)
2484 lmins = (lmhi << PNG_HISHIFT) + lmlo;
2488 for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
2489 pp = prev_row + 1; i < row_bytes; i++)
2491 v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 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_UP)
2511 sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2514 sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2519 sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
2522 sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
2525 if (sumhi > PNG_HIMASK)
2529 sum = (sumhi << PNG_HISHIFT) + sumlo;
2536 best_row = png_ptr->up_row;
2541 if (filter_to_do == PNG_FILTER_AVG)
2543 png_bytep rp, dp, pp, lp;
2546 for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
2547 pp = prev_row + 1; i < bpp; i++)
2549 *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
2552 for (lp = row_buf + 1; i < row_bytes; i++)
2554 *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
2557 best_row = png_ptr->avg_row;
2560 else if (filter_to_do & PNG_FILTER_AVG)
2562 png_bytep rp, dp, pp, lp;
2563 png_uint_32 sum = 0, lmins = mins;
2567 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2568 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2571 png_uint_32 lmhi, lmlo;
2572 lmlo = lmins & PNG_LOMASK;
2573 lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
2575 for (j = 0; j < num_p_filters; j++)
2577 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
2579 lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2582 lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2587 lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
2590 lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
2593 if (lmhi > PNG_HIMASK)
2597 lmins = (lmhi << PNG_HISHIFT) + lmlo;
2601 for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
2602 pp = prev_row + 1; i < bpp; i++)
2604 v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
2606 sum += (v < 128) ? v : 256 - v;
2609 for (lp = row_buf + 1; i < row_bytes; i++)
2612 (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
2614 sum += (v < 128) ? v : 256 - v;
2616 if (sum > lmins) /* We are already worse, don't continue. */
2620 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2621 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2624 png_uint_32 sumhi, sumlo;
2625 sumlo = sum & PNG_LOMASK;
2626 sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
2628 for (j = 0; j < num_p_filters; j++)
2630 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
2632 sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2635 sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2640 sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
2643 sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
2646 if (sumhi > PNG_HIMASK)
2650 sum = (sumhi << PNG_HISHIFT) + sumlo;
2657 best_row = png_ptr->avg_row;
2662 if (filter_to_do == PNG_FILTER_PAETH)
2664 png_bytep rp, dp, pp, cp, lp;
2667 for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
2668 pp = prev_row + 1; i < bpp; i++)
2670 *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
2673 for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
2675 int a, b, c, pa, pb, pc, p;
2689 pa = p < 0 ? -p : p;
2690 pb = pc < 0 ? -pc : pc;
2691 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
2694 p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
2696 *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
2698 best_row = png_ptr->paeth_row;
2701 else if (filter_to_do & PNG_FILTER_PAETH)
2703 png_bytep rp, dp, pp, cp, lp;
2704 png_uint_32 sum = 0, lmins = mins;
2708 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2709 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2712 png_uint_32 lmhi, lmlo;
2713 lmlo = lmins & PNG_LOMASK;
2714 lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
2716 for (j = 0; j < num_p_filters; j++)
2718 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
2720 lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2723 lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2728 lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2731 lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2734 if (lmhi > PNG_HIMASK)
2738 lmins = (lmhi << PNG_HISHIFT) + lmlo;
2742 for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
2743 pp = prev_row + 1; i < bpp; i++)
2745 v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
2747 sum += (v < 128) ? v : 256 - v;
2750 for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
2752 int a, b, c, pa, pb, pc, p;
2758 #ifndef PNG_SLOW_PAETH
2766 pa = p < 0 ? -p : p;
2767 pb = pc < 0 ? -pc : pc;
2768 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
2770 p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
2771 #else /* PNG_SLOW_PAETH */
2777 if (pa <= pb && pa <= pc)
2785 #endif /* PNG_SLOW_PAETH */
2787 v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
2789 sum += (v < 128) ? v : 256 - v;
2791 if (sum > lmins) /* We are already worse, don't continue. */
2795 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2796 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2799 png_uint_32 sumhi, sumlo;
2800 sumlo = sum & PNG_LOMASK;
2801 sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
2803 for (j = 0; j < num_p_filters; j++)
2805 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
2807 sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2810 sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2815 sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2818 sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2821 if (sumhi > PNG_HIMASK)
2825 sum = (sumhi << PNG_HISHIFT) + sumlo;
2831 best_row = png_ptr->paeth_row;
2834 #endif /* PNG_WRITE_FILTER_SUPPORTED */
2835 /* Do the actual writing of the filtered row data from the chosen filter. */
2837 png_write_filtered_row(png_ptr, best_row);
2839 #ifdef PNG_WRITE_FILTER_SUPPORTED
2840 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2841 /* Save the type of filter we picked this time for future calculations */
2842 if (png_ptr->num_prev_filters > 0)
2846 for (j = 1; j < num_p_filters; j++)
2848 png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
2851 png_ptr->prev_filters[j] = best_row[0];
2854 #endif /* PNG_WRITE_FILTER_SUPPORTED */
2858 /* Do the actual writing of a previously filtered row. */
2860 png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
2864 png_debug(1, "in png_write_filtered_row");
2866 png_debug1(2, "filter = %d", filtered_row[0]);
2867 /* Set up the zlib input buffer */
2869 png_ptr->zstream.next_in = filtered_row;
2870 png_ptr->zstream.avail_in = 0;
2871 avail = png_ptr->row_info.rowbytes + 1;
2872 /* Repeat until we have compressed all the data */
2875 int ret; /* Return of zlib */
2877 /* Record the number of bytes available - zlib supports at least 65535
2878 * bytes at one step, depending on the size of the zlib type 'uInt', the
2879 * maximum size zlib can write at once is ZLIB_IO_MAX (from pngpriv.h).
2880 * Use this because on 16 bit systems 'rowbytes' can be up to 65536 (i.e.
2881 * one more than 16 bits) and, in this case 'rowbytes+1' can overflow a
2882 * uInt. ZLIB_IO_MAX can be safely reduced to cause zlib to be called
2883 * with smaller chunks of data.
2885 if (png_ptr->zstream.avail_in == 0)
2887 if (avail > ZLIB_IO_MAX)
2889 png_ptr->zstream.avail_in = ZLIB_IO_MAX;
2890 avail -= ZLIB_IO_MAX;
2895 /* So this will fit in the available uInt space: */
2896 png_ptr->zstream.avail_in = (uInt)avail;
2901 /* Compress the data */
2902 ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
2904 /* Check for compression errors */
2907 if (png_ptr->zstream.msg != NULL)
2908 png_error(png_ptr, png_ptr->zstream.msg);
2911 png_error(png_ptr, "zlib error");
2914 /* See if it is time to write another IDAT */
2915 if (!(png_ptr->zstream.avail_out))
2917 /* Write the IDAT and reset the zlib output buffer */
2918 png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
2919 png_ptr->zstream.next_out = png_ptr->zbuf;
2920 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
2922 /* Repeat until all data has been compressed */
2923 } while (avail > 0 || png_ptr->zstream.avail_in > 0);
2925 /* Swap the current and previous rows */
2926 if (png_ptr->prev_row != NULL)
2930 tptr = png_ptr->prev_row;
2931 png_ptr->prev_row = png_ptr->row_buf;
2932 png_ptr->row_buf = tptr;
2935 /* Finish row - updates counters and flushes zlib if last row */
2936 png_write_finish_row(png_ptr);
2938 #ifdef PNG_WRITE_FLUSH_SUPPORTED
2939 png_ptr->flush_rows++;
2941 if (png_ptr->flush_dist > 0 &&
2942 png_ptr->flush_rows >= png_ptr->flush_dist)
2944 png_write_flush(png_ptr);
2948 #endif /* PNG_WRITE_SUPPORTED */