Support unrar64.dll
[xy_vsfilter.git] / src / libpng / pngwutil.c
blob91d761b62a722f8f63dddfd21c3a7a71cada75ed
2 /* pngwutil.c - utilities to write a PNG file
4 * Last changed in libpng 1.2.36 [June 4, 2009]
5 * For conditions of distribution and use, see copyright notice in png.h
6 * Copyright (c) 1998-2009 Glenn Randers-Pehrson
7 * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
8 * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
9 */
11 #define PNG_INTERNAL
12 #include "png.h"
13 #ifdef PNG_WRITE_SUPPORTED
15 /* Place a 32-bit number into a buffer in PNG byte order. We work
16 * with unsigned numbers for convenience, although one supported
17 * ancillary chunk uses signed (two's complement) numbers.
19 void PNGAPI
20 png_save_uint_32(png_bytep buf, png_uint_32 i)
22 buf[0] = (png_byte)((i >> 24) & 0xff);
23 buf[1] = (png_byte)((i >> 16) & 0xff);
24 buf[2] = (png_byte)((i >> 8) & 0xff);
25 buf[3] = (png_byte)(i & 0xff);
28 /* The png_save_int_32 function assumes integers are stored in two's
29 * complement format. If this isn't the case, then this routine needs to
30 * be modified to write data in two's complement format.
32 void PNGAPI
33 png_save_int_32(png_bytep buf, png_int_32 i)
35 buf[0] = (png_byte)((i >> 24) & 0xff);
36 buf[1] = (png_byte)((i >> 16) & 0xff);
37 buf[2] = (png_byte)((i >> 8) & 0xff);
38 buf[3] = (png_byte)(i & 0xff);
41 /* Place a 16-bit number into a buffer in PNG byte order.
42 * The parameter is declared unsigned int, not png_uint_16,
43 * just to avoid potential problems on pre-ANSI C compilers.
45 void PNGAPI
46 png_save_uint_16(png_bytep buf, unsigned int i)
48 buf[0] = (png_byte)((i >> 8) & 0xff);
49 buf[1] = (png_byte)(i & 0xff);
52 /* Simple function to write the signature. If we have already written
53 * the magic bytes of the signature, or more likely, the PNG stream is
54 * being embedded into another stream and doesn't need its own signature,
55 * we should call png_set_sig_bytes() to tell libpng how many of the
56 * bytes have already been written.
58 void /* PRIVATE */
59 png_write_sig(png_structp png_ptr)
61 png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
63 /* Write the rest of the 8 byte signature */
64 png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
65 (png_size_t)(8 - png_ptr->sig_bytes));
66 if (png_ptr->sig_bytes < 3)
67 png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
70 /* Write a PNG chunk all at once. The type is an array of ASCII characters
71 * representing the chunk name. The array must be at least 4 bytes in
72 * length, and does not need to be null terminated. To be safe, pass the
73 * pre-defined chunk names here, and if you need a new one, define it
74 * where the others are defined. The length is the length of the data.
75 * All the data must be present. If that is not possible, use the
76 * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
77 * functions instead.
79 void PNGAPI
80 png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
81 png_bytep data, png_size_t length)
83 if (png_ptr == NULL)
84 return;
85 png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
86 png_write_chunk_data(png_ptr, data, (png_size_t)length);
87 png_write_chunk_end(png_ptr);
90 /* Write the start of a PNG chunk. The type is the chunk type.
91 * The total_length is the sum of the lengths of all the data you will be
92 * passing in png_write_chunk_data().
94 void PNGAPI
95 png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
96 png_uint_32 length)
98 png_byte buf[8];
100 png_debug2(0, "Writing %s chunk, length = %lu", chunk_name,
101 (unsigned long)length);
102 if (png_ptr == NULL)
103 return;
105 /* Write the length and the chunk name */
106 png_save_uint_32(buf, length);
107 png_memcpy(buf + 4, chunk_name, 4);
108 png_write_data(png_ptr, buf, (png_size_t)8);
109 /* Put the chunk name into png_ptr->chunk_name */
110 png_memcpy(png_ptr->chunk_name, chunk_name, 4);
111 /* Reset the crc and run it over the chunk name */
112 png_reset_crc(png_ptr);
113 png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
116 /* Write the data of a PNG chunk started with png_write_chunk_start().
117 * Note that multiple calls to this function are allowed, and that the
118 * sum of the lengths from these calls *must* add up to the total_length
119 * given to png_write_chunk_start().
121 void PNGAPI
122 png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
124 /* Write the data, and run the CRC over it */
125 if (png_ptr == NULL)
126 return;
127 if (data != NULL && length > 0)
129 png_write_data(png_ptr, data, length);
130 /* Update the CRC after writing the data,
131 * in case that the user I/O routine alters it.
133 png_calculate_crc(png_ptr, data, length);
137 /* Finish a chunk started with png_write_chunk_start(). */
138 void PNGAPI
139 png_write_chunk_end(png_structp png_ptr)
141 png_byte buf[4];
143 if (png_ptr == NULL) return;
145 /* Write the crc in a single operation */
146 png_save_uint_32(buf, png_ptr->crc);
148 png_write_data(png_ptr, buf, (png_size_t)4);
151 #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
152 /* This pair of functions encapsulates the operation of (a) compressing a
153 * text string, and (b) issuing it later as a series of chunk data writes.
154 * The compression_state structure is shared context for these functions
155 * set up by the caller in order to make the whole mess thread-safe.
158 typedef struct
160 char *input; /* The uncompressed input data */
161 int input_len; /* Its length */
162 int num_output_ptr; /* Number of output pointers used */
163 int max_output_ptr; /* Size of output_ptr */
164 png_charpp output_ptr; /* Array of pointers to output */
165 } compression_state;
167 /* Compress given text into storage in the png_ptr structure */
168 static int /* PRIVATE */
169 png_text_compress(png_structp png_ptr,
170 png_charp text, png_size_t text_len, int compression,
171 compression_state *comp)
173 int ret;
175 comp->num_output_ptr = 0;
176 comp->max_output_ptr = 0;
177 comp->output_ptr = NULL;
178 comp->input = NULL;
179 comp->input_len = 0;
181 /* We may just want to pass the text right through */
182 if (compression == PNG_TEXT_COMPRESSION_NONE)
184 comp->input = text;
185 comp->input_len = text_len;
186 return((int)text_len);
189 if (compression >= PNG_TEXT_COMPRESSION_LAST)
191 #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
192 char msg[50];
193 png_snprintf(msg, 50, "Unknown compression type %d", compression);
194 png_warning(png_ptr, msg);
195 #else
196 png_warning(png_ptr, "Unknown compression type");
197 #endif
200 /* We can't write the chunk until we find out how much data we have,
201 * which means we need to run the compressor first and save the
202 * output. This shouldn't be a problem, as the vast majority of
203 * comments should be reasonable, but we will set up an array of
204 * malloc'd pointers to be sure.
206 * If we knew the application was well behaved, we could simplify this
207 * greatly by assuming we can always malloc an output buffer large
208 * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
209 * and malloc this directly. The only time this would be a bad idea is
210 * if we can't malloc more than 64K and we have 64K of random input
211 * data, or if the input string is incredibly large (although this
212 * wouldn't cause a failure, just a slowdown due to swapping).
215 /* Set up the compression buffers */
216 png_ptr->zstream.avail_in = (uInt)text_len;
217 png_ptr->zstream.next_in = (Bytef *)text;
218 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
219 png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
221 /* This is the same compression loop as in png_write_row() */
224 /* Compress the data */
225 ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
226 if (ret != Z_OK)
228 /* Error */
229 if (png_ptr->zstream.msg != NULL)
230 png_error(png_ptr, png_ptr->zstream.msg);
231 else
232 png_error(png_ptr, "zlib error");
234 /* Check to see if we need more room */
235 if (!(png_ptr->zstream.avail_out))
237 /* Make sure the output array has room */
238 if (comp->num_output_ptr >= comp->max_output_ptr)
240 int old_max;
242 old_max = comp->max_output_ptr;
243 comp->max_output_ptr = comp->num_output_ptr + 4;
244 if (comp->output_ptr != NULL)
246 png_charpp old_ptr;
248 old_ptr = comp->output_ptr;
249 comp->output_ptr = (png_charpp)png_malloc(png_ptr,
250 (png_uint_32)
251 (comp->max_output_ptr * png_sizeof(png_charpp)));
252 png_memcpy(comp->output_ptr, old_ptr, old_max
253 * png_sizeof(png_charp));
254 png_free(png_ptr, old_ptr);
256 else
257 comp->output_ptr = (png_charpp)png_malloc(png_ptr,
258 (png_uint_32)
259 (comp->max_output_ptr * png_sizeof(png_charp)));
262 /* Save the data */
263 comp->output_ptr[comp->num_output_ptr] =
264 (png_charp)png_malloc(png_ptr,
265 (png_uint_32)png_ptr->zbuf_size);
266 png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
267 png_ptr->zbuf_size);
268 comp->num_output_ptr++;
270 /* and reset the buffer */
271 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
272 png_ptr->zstream.next_out = png_ptr->zbuf;
274 /* Continue until we don't have any more to compress */
275 } while (png_ptr->zstream.avail_in);
277 /* Finish the compression */
280 /* Tell zlib we are finished */
281 ret = deflate(&png_ptr->zstream, Z_FINISH);
283 if (ret == Z_OK)
285 /* Check to see if we need more room */
286 if (!(png_ptr->zstream.avail_out))
288 /* Check to make sure our output array has room */
289 if (comp->num_output_ptr >= comp->max_output_ptr)
291 int old_max;
293 old_max = comp->max_output_ptr;
294 comp->max_output_ptr = comp->num_output_ptr + 4;
295 if (comp->output_ptr != NULL)
297 png_charpp old_ptr;
299 old_ptr = comp->output_ptr;
300 /* This could be optimized to realloc() */
301 comp->output_ptr = (png_charpp)png_malloc(png_ptr,
302 (png_uint_32)(comp->max_output_ptr *
303 png_sizeof(png_charp)));
304 png_memcpy(comp->output_ptr, old_ptr,
305 old_max * png_sizeof(png_charp));
306 png_free(png_ptr, old_ptr);
308 else
309 comp->output_ptr = (png_charpp)png_malloc(png_ptr,
310 (png_uint_32)(comp->max_output_ptr *
311 png_sizeof(png_charp)));
314 /* Save the data */
315 comp->output_ptr[comp->num_output_ptr] =
316 (png_charp)png_malloc(png_ptr,
317 (png_uint_32)png_ptr->zbuf_size);
318 png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
319 png_ptr->zbuf_size);
320 comp->num_output_ptr++;
322 /* and reset the buffer pointers */
323 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
324 png_ptr->zstream.next_out = png_ptr->zbuf;
327 else if (ret != Z_STREAM_END)
329 /* We got an error */
330 if (png_ptr->zstream.msg != NULL)
331 png_error(png_ptr, png_ptr->zstream.msg);
332 else
333 png_error(png_ptr, "zlib error");
335 } while (ret != Z_STREAM_END);
337 /* Text length is number of buffers plus last buffer */
338 text_len = png_ptr->zbuf_size * comp->num_output_ptr;
339 if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
340 text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
342 return((int)text_len);
345 /* Ship the compressed text out via chunk writes */
346 static void /* PRIVATE */
347 png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
349 int i;
351 /* Handle the no-compression case */
352 if (comp->input)
354 png_write_chunk_data(png_ptr, (png_bytep)comp->input,
355 (png_size_t)comp->input_len);
356 return;
359 /* Write saved output buffers, if any */
360 for (i = 0; i < comp->num_output_ptr; i++)
362 png_write_chunk_data(png_ptr, (png_bytep)comp->output_ptr[i],
363 (png_size_t)png_ptr->zbuf_size);
364 png_free(png_ptr, comp->output_ptr[i]);
365 comp->output_ptr[i]=NULL;
367 if (comp->max_output_ptr != 0)
368 png_free(png_ptr, comp->output_ptr);
369 comp->output_ptr=NULL;
370 /* Write anything left in zbuf */
371 if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
372 png_write_chunk_data(png_ptr, png_ptr->zbuf,
373 (png_size_t)(png_ptr->zbuf_size - png_ptr->zstream.avail_out));
375 /* Reset zlib for another zTXt/iTXt or image data */
376 deflateReset(&png_ptr->zstream);
377 png_ptr->zstream.data_type = Z_BINARY;
379 #endif
381 /* Write the IHDR chunk, and update the png_struct with the necessary
382 * information. Note that the rest of this code depends upon this
383 * information being correct.
385 void /* PRIVATE */
386 png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
387 int bit_depth, int color_type, int compression_type, int filter_type,
388 int interlace_type)
390 #ifdef PNG_USE_LOCAL_ARRAYS
391 PNG_IHDR;
392 #endif
393 int ret;
395 png_byte buf[13]; /* Buffer to store the IHDR info */
397 png_debug(1, "in png_write_IHDR");
398 /* Check that we have valid input data from the application info */
399 switch (color_type)
401 case PNG_COLOR_TYPE_GRAY:
402 switch (bit_depth)
404 case 1:
405 case 2:
406 case 4:
407 case 8:
408 case 16: png_ptr->channels = 1; break;
409 default: png_error(png_ptr, "Invalid bit depth for grayscale image");
411 break;
412 case PNG_COLOR_TYPE_RGB:
413 if (bit_depth != 8 && bit_depth != 16)
414 png_error(png_ptr, "Invalid bit depth for RGB image");
415 png_ptr->channels = 3;
416 break;
417 case PNG_COLOR_TYPE_PALETTE:
418 switch (bit_depth)
420 case 1:
421 case 2:
422 case 4:
423 case 8: png_ptr->channels = 1; break;
424 default: png_error(png_ptr, "Invalid bit depth for paletted image");
426 break;
427 case PNG_COLOR_TYPE_GRAY_ALPHA:
428 if (bit_depth != 8 && bit_depth != 16)
429 png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
430 png_ptr->channels = 2;
431 break;
432 case PNG_COLOR_TYPE_RGB_ALPHA:
433 if (bit_depth != 8 && bit_depth != 16)
434 png_error(png_ptr, "Invalid bit depth for RGBA image");
435 png_ptr->channels = 4;
436 break;
437 default:
438 png_error(png_ptr, "Invalid image color type specified");
441 if (compression_type != PNG_COMPRESSION_TYPE_BASE)
443 png_warning(png_ptr, "Invalid compression type specified");
444 compression_type = PNG_COMPRESSION_TYPE_BASE;
447 /* Write filter_method 64 (intrapixel differencing) only if
448 * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
449 * 2. Libpng did not write a PNG signature (this filter_method is only
450 * used in PNG datastreams that are embedded in MNG datastreams) and
451 * 3. The application called png_permit_mng_features with a mask that
452 * included PNG_FLAG_MNG_FILTER_64 and
453 * 4. The filter_method is 64 and
454 * 5. The color_type is RGB or RGBA
456 if (
457 #if defined(PNG_MNG_FEATURES_SUPPORTED)
458 !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
459 ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
460 (color_type == PNG_COLOR_TYPE_RGB ||
461 color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
462 (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
463 #endif
464 filter_type != PNG_FILTER_TYPE_BASE)
466 png_warning(png_ptr, "Invalid filter type specified");
467 filter_type = PNG_FILTER_TYPE_BASE;
470 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
471 if (interlace_type != PNG_INTERLACE_NONE &&
472 interlace_type != PNG_INTERLACE_ADAM7)
474 png_warning(png_ptr, "Invalid interlace type specified");
475 interlace_type = PNG_INTERLACE_ADAM7;
477 #else
478 interlace_type=PNG_INTERLACE_NONE;
479 #endif
481 /* Save the relevent information */
482 png_ptr->bit_depth = (png_byte)bit_depth;
483 png_ptr->color_type = (png_byte)color_type;
484 png_ptr->interlaced = (png_byte)interlace_type;
485 #if defined(PNG_MNG_FEATURES_SUPPORTED)
486 png_ptr->filter_type = (png_byte)filter_type;
487 #endif
488 png_ptr->compression_type = (png_byte)compression_type;
489 png_ptr->width = width;
490 png_ptr->height = height;
492 png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
493 png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
494 /* Set the usr info, so any transformations can modify it */
495 png_ptr->usr_width = png_ptr->width;
496 png_ptr->usr_bit_depth = png_ptr->bit_depth;
497 png_ptr->usr_channels = png_ptr->channels;
499 /* Pack the header information into the buffer */
500 png_save_uint_32(buf, width);
501 png_save_uint_32(buf + 4, height);
502 buf[8] = (png_byte)bit_depth;
503 buf[9] = (png_byte)color_type;
504 buf[10] = (png_byte)compression_type;
505 buf[11] = (png_byte)filter_type;
506 buf[12] = (png_byte)interlace_type;
508 /* Write the chunk */
509 png_write_chunk(png_ptr, (png_bytep)png_IHDR, buf, (png_size_t)13);
511 /* Initialize zlib with PNG info */
512 png_ptr->zstream.zalloc = png_zalloc;
513 png_ptr->zstream.zfree = png_zfree;
514 png_ptr->zstream.opaque = (voidpf)png_ptr;
515 if (!(png_ptr->do_filter))
517 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
518 png_ptr->bit_depth < 8)
519 png_ptr->do_filter = PNG_FILTER_NONE;
520 else
521 png_ptr->do_filter = PNG_ALL_FILTERS;
523 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
525 if (png_ptr->do_filter != PNG_FILTER_NONE)
526 png_ptr->zlib_strategy = Z_FILTERED;
527 else
528 png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
530 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
531 png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
532 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
533 png_ptr->zlib_mem_level = 8;
534 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
535 png_ptr->zlib_window_bits = 15;
536 if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
537 png_ptr->zlib_method = 8;
538 ret = deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
539 png_ptr->zlib_method, png_ptr->zlib_window_bits,
540 png_ptr->zlib_mem_level, png_ptr->zlib_strategy);
541 if (ret != Z_OK)
543 if (ret == Z_VERSION_ERROR) png_error(png_ptr,
544 "zlib failed to initialize compressor -- version error");
545 if (ret == Z_STREAM_ERROR) png_error(png_ptr,
546 "zlib failed to initialize compressor -- stream error");
547 if (ret == Z_MEM_ERROR) png_error(png_ptr,
548 "zlib failed to initialize compressor -- mem error");
549 png_error(png_ptr, "zlib failed to initialize compressor");
551 png_ptr->zstream.next_out = png_ptr->zbuf;
552 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
553 /* libpng is not interested in zstream.data_type */
554 /* Set it to a predefined value, to avoid its evaluation inside zlib */
555 png_ptr->zstream.data_type = Z_BINARY;
557 png_ptr->mode = PNG_HAVE_IHDR;
560 /* Write the palette. We are careful not to trust png_color to be in the
561 * correct order for PNG, so people can redefine it to any convenient
562 * structure.
564 void /* PRIVATE */
565 png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
567 #ifdef PNG_USE_LOCAL_ARRAYS
568 PNG_PLTE;
569 #endif
570 png_uint_32 i;
571 png_colorp pal_ptr;
572 png_byte buf[3];
574 png_debug(1, "in png_write_PLTE");
575 if ((
576 #if defined(PNG_MNG_FEATURES_SUPPORTED)
577 !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
578 #endif
579 num_pal == 0) || num_pal > 256)
581 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
583 png_error(png_ptr, "Invalid number of colors in palette");
585 else
587 png_warning(png_ptr, "Invalid number of colors in palette");
588 return;
592 if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
594 png_warning(png_ptr,
595 "Ignoring request to write a PLTE chunk in grayscale PNG");
596 return;
599 png_ptr->num_palette = (png_uint_16)num_pal;
600 png_debug1(3, "num_palette = %d", png_ptr->num_palette);
602 png_write_chunk_start(png_ptr, (png_bytep)png_PLTE,
603 (png_uint_32)(num_pal * 3));
604 #ifndef PNG_NO_POINTER_INDEXING
605 for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
607 buf[0] = pal_ptr->red;
608 buf[1] = pal_ptr->green;
609 buf[2] = pal_ptr->blue;
610 png_write_chunk_data(png_ptr, buf, (png_size_t)3);
612 #else
613 /* This is a little slower but some buggy compilers need to do this instead */
614 pal_ptr=palette;
615 for (i = 0; i < num_pal; i++)
617 buf[0] = pal_ptr[i].red;
618 buf[1] = pal_ptr[i].green;
619 buf[2] = pal_ptr[i].blue;
620 png_write_chunk_data(png_ptr, buf, (png_size_t)3);
622 #endif
623 png_write_chunk_end(png_ptr);
624 png_ptr->mode |= PNG_HAVE_PLTE;
627 /* Write an IDAT chunk */
628 void /* PRIVATE */
629 png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
631 #ifdef PNG_USE_LOCAL_ARRAYS
632 PNG_IDAT;
633 #endif
634 png_debug(1, "in png_write_IDAT");
636 /* Optimize the CMF field in the zlib stream. */
637 /* This hack of the zlib stream is compliant to the stream specification. */
638 if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
639 png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
641 unsigned int z_cmf = data[0]; /* zlib compression method and flags */
642 if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
644 /* Avoid memory underflows and multiplication overflows.
646 * The conditions below are practically always satisfied;
647 * however, they still must be checked.
649 if (length >= 2 &&
650 png_ptr->height < 16384 && png_ptr->width < 16384)
652 png_uint_32 uncompressed_idat_size = png_ptr->height *
653 ((png_ptr->width *
654 png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
655 unsigned int z_cinfo = z_cmf >> 4;
656 unsigned int half_z_window_size = 1 << (z_cinfo + 7);
657 while (uncompressed_idat_size <= half_z_window_size &&
658 half_z_window_size >= 256)
660 z_cinfo--;
661 half_z_window_size >>= 1;
663 z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
664 if (data[0] != (png_byte)z_cmf)
666 data[0] = (png_byte)z_cmf;
667 data[1] &= 0xe0;
668 data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
672 else
673 png_error(png_ptr,
674 "Invalid zlib compression method or flags in IDAT");
677 png_write_chunk(png_ptr, (png_bytep)png_IDAT, data, length);
678 png_ptr->mode |= PNG_HAVE_IDAT;
681 /* Write an IEND chunk */
682 void /* PRIVATE */
683 png_write_IEND(png_structp png_ptr)
685 #ifdef PNG_USE_LOCAL_ARRAYS
686 PNG_IEND;
687 #endif
688 png_debug(1, "in png_write_IEND");
689 png_write_chunk(png_ptr, (png_bytep)png_IEND, png_bytep_NULL,
690 (png_size_t)0);
691 png_ptr->mode |= PNG_HAVE_IEND;
694 #if defined(PNG_WRITE_gAMA_SUPPORTED)
695 /* Write a gAMA chunk */
696 #ifdef PNG_FLOATING_POINT_SUPPORTED
697 void /* PRIVATE */
698 png_write_gAMA(png_structp png_ptr, double file_gamma)
700 #ifdef PNG_USE_LOCAL_ARRAYS
701 PNG_gAMA;
702 #endif
703 png_uint_32 igamma;
704 png_byte buf[4];
706 png_debug(1, "in png_write_gAMA");
707 /* file_gamma is saved in 1/100,000ths */
708 igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
709 png_save_uint_32(buf, igamma);
710 png_write_chunk(png_ptr, (png_bytep)png_gAMA, buf, (png_size_t)4);
712 #endif
713 #ifdef PNG_FIXED_POINT_SUPPORTED
714 void /* PRIVATE */
715 png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
717 #ifdef PNG_USE_LOCAL_ARRAYS
718 PNG_gAMA;
719 #endif
720 png_byte buf[4];
722 png_debug(1, "in png_write_gAMA");
723 /* file_gamma is saved in 1/100,000ths */
724 png_save_uint_32(buf, (png_uint_32)file_gamma);
725 png_write_chunk(png_ptr, (png_bytep)png_gAMA, buf, (png_size_t)4);
727 #endif
728 #endif
730 #if defined(PNG_WRITE_sRGB_SUPPORTED)
731 /* Write a sRGB chunk */
732 void /* PRIVATE */
733 png_write_sRGB(png_structp png_ptr, int srgb_intent)
735 #ifdef PNG_USE_LOCAL_ARRAYS
736 PNG_sRGB;
737 #endif
738 png_byte buf[1];
740 png_debug(1, "in png_write_sRGB");
741 if (srgb_intent >= PNG_sRGB_INTENT_LAST)
742 png_warning(png_ptr,
743 "Invalid sRGB rendering intent specified");
744 buf[0]=(png_byte)srgb_intent;
745 png_write_chunk(png_ptr, (png_bytep)png_sRGB, buf, (png_size_t)1);
747 #endif
749 #if defined(PNG_WRITE_iCCP_SUPPORTED)
750 /* Write an iCCP chunk */
751 void /* PRIVATE */
752 png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
753 png_charp profile, int profile_len)
755 #ifdef PNG_USE_LOCAL_ARRAYS
756 PNG_iCCP;
757 #endif
758 png_size_t name_len;
759 png_charp new_name;
760 compression_state comp;
761 int embedded_profile_len = 0;
763 png_debug(1, "in png_write_iCCP");
765 comp.num_output_ptr = 0;
766 comp.max_output_ptr = 0;
767 comp.output_ptr = NULL;
768 comp.input = NULL;
769 comp.input_len = 0;
771 if ((name_len = png_check_keyword(png_ptr, name,
772 &new_name)) == 0)
773 return;
775 if (compression_type != PNG_COMPRESSION_TYPE_BASE)
776 png_warning(png_ptr, "Unknown compression type in iCCP chunk");
778 if (profile == NULL)
779 profile_len = 0;
781 if (profile_len > 3)
782 embedded_profile_len =
783 ((*( (png_bytep)profile ))<<24) |
784 ((*( (png_bytep)profile + 1))<<16) |
785 ((*( (png_bytep)profile + 2))<< 8) |
786 ((*( (png_bytep)profile + 3)) );
788 if (profile_len < embedded_profile_len)
790 png_warning(png_ptr,
791 "Embedded profile length too large in iCCP chunk");
792 png_free(png_ptr, new_name);
793 return;
796 if (profile_len > embedded_profile_len)
798 png_warning(png_ptr,
799 "Truncating profile to actual length in iCCP chunk");
800 profile_len = embedded_profile_len;
803 if (profile_len)
804 profile_len = png_text_compress(png_ptr, profile,
805 (png_size_t)profile_len, PNG_COMPRESSION_TYPE_BASE, &comp);
807 /* Make sure we include the NULL after the name and the compression type */
808 png_write_chunk_start(png_ptr, (png_bytep)png_iCCP,
809 (png_uint_32)(name_len + profile_len + 2));
810 new_name[name_len + 1] = 0x00;
811 png_write_chunk_data(png_ptr, (png_bytep)new_name,
812 (png_size_t)(name_len + 2));
814 if (profile_len)
815 png_write_compressed_data_out(png_ptr, &comp);
817 png_write_chunk_end(png_ptr);
818 png_free(png_ptr, new_name);
820 #endif
822 #if defined(PNG_WRITE_sPLT_SUPPORTED)
823 /* Write a sPLT chunk */
824 void /* PRIVATE */
825 png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
827 #ifdef PNG_USE_LOCAL_ARRAYS
828 PNG_sPLT;
829 #endif
830 png_size_t name_len;
831 png_charp new_name;
832 png_byte entrybuf[10];
833 int entry_size = (spalette->depth == 8 ? 6 : 10);
834 int palette_size = entry_size * spalette->nentries;
835 png_sPLT_entryp ep;
836 #ifdef PNG_NO_POINTER_INDEXING
837 int i;
838 #endif
840 png_debug(1, "in png_write_sPLT");
841 if ((name_len = png_check_keyword(png_ptr,spalette->name, &new_name))==0)
842 return;
844 /* Make sure we include the NULL after the name */
845 png_write_chunk_start(png_ptr, (png_bytep)png_sPLT,
846 (png_uint_32)(name_len + 2 + palette_size));
847 png_write_chunk_data(png_ptr, (png_bytep)new_name,
848 (png_size_t)(name_len + 1));
849 png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, (png_size_t)1);
851 /* Loop through each palette entry, writing appropriately */
852 #ifndef PNG_NO_POINTER_INDEXING
853 for (ep = spalette->entries; ep<spalette->entries + spalette->nentries; ep++)
855 if (spalette->depth == 8)
857 entrybuf[0] = (png_byte)ep->red;
858 entrybuf[1] = (png_byte)ep->green;
859 entrybuf[2] = (png_byte)ep->blue;
860 entrybuf[3] = (png_byte)ep->alpha;
861 png_save_uint_16(entrybuf + 4, ep->frequency);
863 else
865 png_save_uint_16(entrybuf + 0, ep->red);
866 png_save_uint_16(entrybuf + 2, ep->green);
867 png_save_uint_16(entrybuf + 4, ep->blue);
868 png_save_uint_16(entrybuf + 6, ep->alpha);
869 png_save_uint_16(entrybuf + 8, ep->frequency);
871 png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
873 #else
874 ep=spalette->entries;
875 for (i=0; i>spalette->nentries; i++)
877 if (spalette->depth == 8)
879 entrybuf[0] = (png_byte)ep[i].red;
880 entrybuf[1] = (png_byte)ep[i].green;
881 entrybuf[2] = (png_byte)ep[i].blue;
882 entrybuf[3] = (png_byte)ep[i].alpha;
883 png_save_uint_16(entrybuf + 4, ep[i].frequency);
885 else
887 png_save_uint_16(entrybuf + 0, ep[i].red);
888 png_save_uint_16(entrybuf + 2, ep[i].green);
889 png_save_uint_16(entrybuf + 4, ep[i].blue);
890 png_save_uint_16(entrybuf + 6, ep[i].alpha);
891 png_save_uint_16(entrybuf + 8, ep[i].frequency);
893 png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
895 #endif
897 png_write_chunk_end(png_ptr);
898 png_free(png_ptr, new_name);
900 #endif
902 #if defined(PNG_WRITE_sBIT_SUPPORTED)
903 /* Write the sBIT chunk */
904 void /* PRIVATE */
905 png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
907 #ifdef PNG_USE_LOCAL_ARRAYS
908 PNG_sBIT;
909 #endif
910 png_byte buf[4];
911 png_size_t size;
913 png_debug(1, "in png_write_sBIT");
914 /* Make sure we don't depend upon the order of PNG_COLOR_8 */
915 if (color_type & PNG_COLOR_MASK_COLOR)
917 png_byte maxbits;
919 maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
920 png_ptr->usr_bit_depth);
921 if (sbit->red == 0 || sbit->red > maxbits ||
922 sbit->green == 0 || sbit->green > maxbits ||
923 sbit->blue == 0 || sbit->blue > maxbits)
925 png_warning(png_ptr, "Invalid sBIT depth specified");
926 return;
928 buf[0] = sbit->red;
929 buf[1] = sbit->green;
930 buf[2] = sbit->blue;
931 size = 3;
933 else
935 if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
937 png_warning(png_ptr, "Invalid sBIT depth specified");
938 return;
940 buf[0] = sbit->gray;
941 size = 1;
944 if (color_type & PNG_COLOR_MASK_ALPHA)
946 if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
948 png_warning(png_ptr, "Invalid sBIT depth specified");
949 return;
951 buf[size++] = sbit->alpha;
954 png_write_chunk(png_ptr, (png_bytep)png_sBIT, buf, size);
956 #endif
958 #if defined(PNG_WRITE_cHRM_SUPPORTED)
959 /* Write the cHRM chunk */
960 #ifdef PNG_FLOATING_POINT_SUPPORTED
961 void /* PRIVATE */
962 png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
963 double red_x, double red_y, double green_x, double green_y,
964 double blue_x, double blue_y)
966 #ifdef PNG_USE_LOCAL_ARRAYS
967 PNG_cHRM;
968 #endif
969 png_byte buf[32];
971 png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y,
972 int_green_x, int_green_y, int_blue_x, int_blue_y;
974 png_debug(1, "in png_write_cHRM");
976 int_white_x = (png_uint_32)(white_x * 100000.0 + 0.5);
977 int_white_y = (png_uint_32)(white_y * 100000.0 + 0.5);
978 int_red_x = (png_uint_32)(red_x * 100000.0 + 0.5);
979 int_red_y = (png_uint_32)(red_y * 100000.0 + 0.5);
980 int_green_x = (png_uint_32)(green_x * 100000.0 + 0.5);
981 int_green_y = (png_uint_32)(green_y * 100000.0 + 0.5);
982 int_blue_x = (png_uint_32)(blue_x * 100000.0 + 0.5);
983 int_blue_y = (png_uint_32)(blue_y * 100000.0 + 0.5);
985 #if !defined(PNG_NO_CHECK_cHRM)
986 if (png_check_cHRM_fixed(png_ptr, int_white_x, int_white_y,
987 int_red_x, int_red_y, int_green_x, int_green_y, int_blue_x, int_blue_y))
988 #endif
990 /* Each value is saved in 1/100,000ths */
992 png_save_uint_32(buf, int_white_x);
993 png_save_uint_32(buf + 4, int_white_y);
995 png_save_uint_32(buf + 8, int_red_x);
996 png_save_uint_32(buf + 12, int_red_y);
998 png_save_uint_32(buf + 16, int_green_x);
999 png_save_uint_32(buf + 20, int_green_y);
1001 png_save_uint_32(buf + 24, int_blue_x);
1002 png_save_uint_32(buf + 28, int_blue_y);
1004 png_write_chunk(png_ptr, (png_bytep)png_cHRM, buf, (png_size_t)32);
1007 #endif
1008 #ifdef PNG_FIXED_POINT_SUPPORTED
1009 void /* PRIVATE */
1010 png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
1011 png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
1012 png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
1013 png_fixed_point blue_y)
1015 #ifdef PNG_USE_LOCAL_ARRAYS
1016 PNG_cHRM;
1017 #endif
1018 png_byte buf[32];
1020 png_debug(1, "in png_write_cHRM");
1021 /* Each value is saved in 1/100,000ths */
1022 #if !defined(PNG_NO_CHECK_cHRM)
1023 if (png_check_cHRM_fixed(png_ptr, white_x, white_y, red_x, red_y,
1024 green_x, green_y, blue_x, blue_y))
1025 #endif
1027 png_save_uint_32(buf, (png_uint_32)white_x);
1028 png_save_uint_32(buf + 4, (png_uint_32)white_y);
1030 png_save_uint_32(buf + 8, (png_uint_32)red_x);
1031 png_save_uint_32(buf + 12, (png_uint_32)red_y);
1033 png_save_uint_32(buf + 16, (png_uint_32)green_x);
1034 png_save_uint_32(buf + 20, (png_uint_32)green_y);
1036 png_save_uint_32(buf + 24, (png_uint_32)blue_x);
1037 png_save_uint_32(buf + 28, (png_uint_32)blue_y);
1039 png_write_chunk(png_ptr, (png_bytep)png_cHRM, buf, (png_size_t)32);
1042 #endif
1043 #endif
1045 #if defined(PNG_WRITE_tRNS_SUPPORTED)
1046 /* Write the tRNS chunk */
1047 void /* PRIVATE */
1048 png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
1049 int num_trans, int color_type)
1051 #ifdef PNG_USE_LOCAL_ARRAYS
1052 PNG_tRNS;
1053 #endif
1054 png_byte buf[6];
1056 png_debug(1, "in png_write_tRNS");
1057 if (color_type == PNG_COLOR_TYPE_PALETTE)
1059 if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
1061 png_warning(png_ptr, "Invalid number of transparent colors specified");
1062 return;
1064 /* Write the chunk out as it is */
1065 png_write_chunk(png_ptr, (png_bytep)png_tRNS, trans,
1066 (png_size_t)num_trans);
1068 else if (color_type == PNG_COLOR_TYPE_GRAY)
1070 /* One 16 bit value */
1071 if (tran->gray >= (1 << png_ptr->bit_depth))
1073 png_warning(png_ptr,
1074 "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
1075 return;
1077 png_save_uint_16(buf, tran->gray);
1078 png_write_chunk(png_ptr, (png_bytep)png_tRNS, buf, (png_size_t)2);
1080 else if (color_type == PNG_COLOR_TYPE_RGB)
1082 /* Three 16 bit values */
1083 png_save_uint_16(buf, tran->red);
1084 png_save_uint_16(buf + 2, tran->green);
1085 png_save_uint_16(buf + 4, tran->blue);
1086 if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
1088 png_warning(png_ptr,
1089 "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
1090 return;
1092 png_write_chunk(png_ptr, (png_bytep)png_tRNS, buf, (png_size_t)6);
1094 else
1096 png_warning(png_ptr, "Can't write tRNS with an alpha channel");
1099 #endif
1101 #if defined(PNG_WRITE_bKGD_SUPPORTED)
1102 /* Write the background chunk */
1103 void /* PRIVATE */
1104 png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
1106 #ifdef PNG_USE_LOCAL_ARRAYS
1107 PNG_bKGD;
1108 #endif
1109 png_byte buf[6];
1111 png_debug(1, "in png_write_bKGD");
1112 if (color_type == PNG_COLOR_TYPE_PALETTE)
1114 if (
1115 #if defined(PNG_MNG_FEATURES_SUPPORTED)
1116 (png_ptr->num_palette ||
1117 (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
1118 #endif
1119 back->index >= png_ptr->num_palette)
1121 png_warning(png_ptr, "Invalid background palette index");
1122 return;
1124 buf[0] = back->index;
1125 png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)1);
1127 else if (color_type & PNG_COLOR_MASK_COLOR)
1129 png_save_uint_16(buf, back->red);
1130 png_save_uint_16(buf + 2, back->green);
1131 png_save_uint_16(buf + 4, back->blue);
1132 if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
1134 png_warning(png_ptr,
1135 "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
1136 return;
1138 png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)6);
1140 else
1142 if (back->gray >= (1 << png_ptr->bit_depth))
1144 png_warning(png_ptr,
1145 "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
1146 return;
1148 png_save_uint_16(buf, back->gray);
1149 png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)2);
1152 #endif
1154 #if defined(PNG_WRITE_hIST_SUPPORTED)
1155 /* Write the histogram */
1156 void /* PRIVATE */
1157 png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
1159 #ifdef PNG_USE_LOCAL_ARRAYS
1160 PNG_hIST;
1161 #endif
1162 int i;
1163 png_byte buf[3];
1165 png_debug(1, "in png_write_hIST");
1166 if (num_hist > (int)png_ptr->num_palette)
1168 png_debug2(3, "num_hist = %d, num_palette = %d", num_hist,
1169 png_ptr->num_palette);
1170 png_warning(png_ptr, "Invalid number of histogram entries specified");
1171 return;
1174 png_write_chunk_start(png_ptr, (png_bytep)png_hIST,
1175 (png_uint_32)(num_hist * 2));
1176 for (i = 0; i < num_hist; i++)
1178 png_save_uint_16(buf, hist[i]);
1179 png_write_chunk_data(png_ptr, buf, (png_size_t)2);
1181 png_write_chunk_end(png_ptr);
1183 #endif
1185 #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
1186 defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
1187 /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
1188 * and if invalid, correct the keyword rather than discarding the entire
1189 * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
1190 * length, forbids leading or trailing whitespace, multiple internal spaces,
1191 * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
1193 * The new_key is allocated to hold the corrected keyword and must be freed
1194 * by the calling routine. This avoids problems with trying to write to
1195 * static keywords without having to have duplicate copies of the strings.
1197 png_size_t /* PRIVATE */
1198 png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
1200 png_size_t key_len;
1201 png_charp kp, dp;
1202 int kflag;
1203 int kwarn=0;
1205 png_debug(1, "in png_check_keyword");
1206 *new_key = NULL;
1208 if (key == NULL || (key_len = png_strlen(key)) == 0)
1210 png_warning(png_ptr, "zero length keyword");
1211 return ((png_size_t)0);
1214 png_debug1(2, "Keyword to be checked is '%s'", key);
1216 *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
1217 if (*new_key == NULL)
1219 png_warning(png_ptr, "Out of memory while procesing keyword");
1220 return ((png_size_t)0);
1223 /* Replace non-printing characters with a blank and print a warning */
1224 for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
1226 if ((png_byte)*kp < 0x20 ||
1227 ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
1229 #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
1230 char msg[40];
1232 png_snprintf(msg, 40,
1233 "invalid keyword character 0x%02X", (png_byte)*kp);
1234 png_warning(png_ptr, msg);
1235 #else
1236 png_warning(png_ptr, "invalid character in keyword");
1237 #endif
1238 *dp = ' ';
1240 else
1242 *dp = *kp;
1245 *dp = '\0';
1247 /* Remove any trailing white space. */
1248 kp = *new_key + key_len - 1;
1249 if (*kp == ' ')
1251 png_warning(png_ptr, "trailing spaces removed from keyword");
1253 while (*kp == ' ')
1255 *(kp--) = '\0';
1256 key_len--;
1260 /* Remove any leading white space. */
1261 kp = *new_key;
1262 if (*kp == ' ')
1264 png_warning(png_ptr, "leading spaces removed from keyword");
1266 while (*kp == ' ')
1268 kp++;
1269 key_len--;
1273 png_debug1(2, "Checking for multiple internal spaces in '%s'", kp);
1275 /* Remove multiple internal spaces. */
1276 for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
1278 if (*kp == ' ' && kflag == 0)
1280 *(dp++) = *kp;
1281 kflag = 1;
1283 else if (*kp == ' ')
1285 key_len--;
1286 kwarn=1;
1288 else
1290 *(dp++) = *kp;
1291 kflag = 0;
1294 *dp = '\0';
1295 if (kwarn)
1296 png_warning(png_ptr, "extra interior spaces removed from keyword");
1298 if (key_len == 0)
1300 png_free(png_ptr, *new_key);
1301 *new_key=NULL;
1302 png_warning(png_ptr, "Zero length keyword");
1305 if (key_len > 79)
1307 png_warning(png_ptr, "keyword length must be 1 - 79 characters");
1308 (*new_key)[79] = '\0';
1309 key_len = 79;
1312 return (key_len);
1314 #endif
1316 #if defined(PNG_WRITE_tEXt_SUPPORTED)
1317 /* Write a tEXt chunk */
1318 void /* PRIVATE */
1319 png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
1320 png_size_t text_len)
1322 #ifdef PNG_USE_LOCAL_ARRAYS
1323 PNG_tEXt;
1324 #endif
1325 png_size_t key_len;
1326 png_charp new_key;
1328 png_debug(1, "in png_write_tEXt");
1329 if ((key_len = png_check_keyword(png_ptr, key, &new_key))==0)
1330 return;
1332 if (text == NULL || *text == '\0')
1333 text_len = 0;
1334 else
1335 text_len = png_strlen(text);
1337 /* Make sure we include the 0 after the key */
1338 png_write_chunk_start(png_ptr, (png_bytep)png_tEXt,
1339 (png_uint_32)(key_len + text_len + 1));
1341 * We leave it to the application to meet PNG-1.0 requirements on the
1342 * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
1343 * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
1344 * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
1346 png_write_chunk_data(png_ptr, (png_bytep)new_key,
1347 (png_size_t)(key_len + 1));
1348 if (text_len)
1349 png_write_chunk_data(png_ptr, (png_bytep)text, (png_size_t)text_len);
1351 png_write_chunk_end(png_ptr);
1352 png_free(png_ptr, new_key);
1354 #endif
1356 #if defined(PNG_WRITE_zTXt_SUPPORTED)
1357 /* Write a compressed text chunk */
1358 void /* PRIVATE */
1359 png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
1360 png_size_t text_len, int compression)
1362 #ifdef PNG_USE_LOCAL_ARRAYS
1363 PNG_zTXt;
1364 #endif
1365 png_size_t key_len;
1366 char buf[1];
1367 png_charp new_key;
1368 compression_state comp;
1370 png_debug(1, "in png_write_zTXt");
1372 comp.num_output_ptr = 0;
1373 comp.max_output_ptr = 0;
1374 comp.output_ptr = NULL;
1375 comp.input = NULL;
1376 comp.input_len = 0;
1378 if ((key_len = png_check_keyword(png_ptr, key, &new_key))==0)
1380 png_free(png_ptr, new_key);
1381 return;
1384 if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
1386 png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
1387 png_free(png_ptr, new_key);
1388 return;
1391 text_len = png_strlen(text);
1393 /* Compute the compressed data; do it now for the length */
1394 text_len = png_text_compress(png_ptr, text, text_len, compression,
1395 &comp);
1397 /* Write start of chunk */
1398 png_write_chunk_start(png_ptr, (png_bytep)png_zTXt,
1399 (png_uint_32)(key_len+text_len + 2));
1400 /* Write key */
1401 png_write_chunk_data(png_ptr, (png_bytep)new_key,
1402 (png_size_t)(key_len + 1));
1403 png_free(png_ptr, new_key);
1405 buf[0] = (png_byte)compression;
1406 /* Write compression */
1407 png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
1408 /* Write the compressed data */
1409 png_write_compressed_data_out(png_ptr, &comp);
1411 /* Close the chunk */
1412 png_write_chunk_end(png_ptr);
1414 #endif
1416 #if defined(PNG_WRITE_iTXt_SUPPORTED)
1417 /* Write an iTXt chunk */
1418 void /* PRIVATE */
1419 png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
1420 png_charp lang, png_charp lang_key, png_charp text)
1422 #ifdef PNG_USE_LOCAL_ARRAYS
1423 PNG_iTXt;
1424 #endif
1425 png_size_t lang_len, key_len, lang_key_len, text_len;
1426 png_charp new_lang;
1427 png_charp new_key = NULL;
1428 png_byte cbuf[2];
1429 compression_state comp;
1431 png_debug(1, "in png_write_iTXt");
1433 comp.num_output_ptr = 0;
1434 comp.max_output_ptr = 0;
1435 comp.output_ptr = NULL;
1436 comp.input = NULL;
1438 if ((key_len = png_check_keyword(png_ptr, key, &new_key))==0)
1439 return;
1441 if ((lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
1443 png_warning(png_ptr, "Empty language field in iTXt chunk");
1444 new_lang = NULL;
1445 lang_len = 0;
1448 if (lang_key == NULL)
1449 lang_key_len = 0;
1450 else
1451 lang_key_len = png_strlen(lang_key);
1453 if (text == NULL)
1454 text_len = 0;
1455 else
1456 text_len = png_strlen(text);
1458 /* Compute the compressed data; do it now for the length */
1459 text_len = png_text_compress(png_ptr, text, text_len, compression-2,
1460 &comp);
1463 /* Make sure we include the compression flag, the compression byte,
1464 * and the NULs after the key, lang, and lang_key parts */
1466 png_write_chunk_start(png_ptr, (png_bytep)png_iTXt,
1467 (png_uint_32)(
1468 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
1469 + key_len
1470 + lang_len
1471 + lang_key_len
1472 + text_len));
1474 /* We leave it to the application to meet PNG-1.0 requirements on the
1475 * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
1476 * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
1477 * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
1479 png_write_chunk_data(png_ptr, (png_bytep)new_key,
1480 (png_size_t)(key_len + 1));
1482 /* Set the compression flag */
1483 if (compression == PNG_ITXT_COMPRESSION_NONE || \
1484 compression == PNG_TEXT_COMPRESSION_NONE)
1485 cbuf[0] = 0;
1486 else /* compression == PNG_ITXT_COMPRESSION_zTXt */
1487 cbuf[0] = 1;
1488 /* Set the compression method */
1489 cbuf[1] = 0;
1490 png_write_chunk_data(png_ptr, cbuf, (png_size_t)2);
1492 cbuf[0] = 0;
1493 png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf),
1494 (png_size_t)(lang_len + 1));
1495 png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf),
1496 (png_size_t)(lang_key_len + 1));
1497 png_write_compressed_data_out(png_ptr, &comp);
1499 png_write_chunk_end(png_ptr);
1500 png_free(png_ptr, new_key);
1501 png_free(png_ptr, new_lang);
1503 #endif
1505 #if defined(PNG_WRITE_oFFs_SUPPORTED)
1506 /* Write the oFFs chunk */
1507 void /* PRIVATE */
1508 png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
1509 int unit_type)
1511 #ifdef PNG_USE_LOCAL_ARRAYS
1512 PNG_oFFs;
1513 #endif
1514 png_byte buf[9];
1516 png_debug(1, "in png_write_oFFs");
1517 if (unit_type >= PNG_OFFSET_LAST)
1518 png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
1520 png_save_int_32(buf, x_offset);
1521 png_save_int_32(buf + 4, y_offset);
1522 buf[8] = (png_byte)unit_type;
1524 png_write_chunk(png_ptr, (png_bytep)png_oFFs, buf, (png_size_t)9);
1526 #endif
1527 #if defined(PNG_WRITE_pCAL_SUPPORTED)
1528 /* Write the pCAL chunk (described in the PNG extensions document) */
1529 void /* PRIVATE */
1530 png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
1531 png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
1533 #ifdef PNG_USE_LOCAL_ARRAYS
1534 PNG_pCAL;
1535 #endif
1536 png_size_t purpose_len, units_len, total_len;
1537 png_uint_32p params_len;
1538 png_byte buf[10];
1539 png_charp new_purpose;
1540 int i;
1542 png_debug1(1, "in png_write_pCAL (%d parameters)", nparams);
1543 if (type >= PNG_EQUATION_LAST)
1544 png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
1546 purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
1547 png_debug1(3, "pCAL purpose length = %d", (int)purpose_len);
1548 units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
1549 png_debug1(3, "pCAL units length = %d", (int)units_len);
1550 total_len = purpose_len + units_len + 10;
1552 params_len = (png_uint_32p)png_malloc(png_ptr,
1553 (png_uint_32)(nparams * png_sizeof(png_uint_32)));
1555 /* Find the length of each parameter, making sure we don't count the
1556 null terminator for the last parameter. */
1557 for (i = 0; i < nparams; i++)
1559 params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
1560 png_debug2(3, "pCAL parameter %d length = %lu", i,
1561 (unsigned long) params_len[i]);
1562 total_len += (png_size_t)params_len[i];
1565 png_debug1(3, "pCAL total length = %d", (int)total_len);
1566 png_write_chunk_start(png_ptr, (png_bytep)png_pCAL, (png_uint_32)total_len);
1567 png_write_chunk_data(png_ptr, (png_bytep)new_purpose,
1568 (png_size_t)purpose_len);
1569 png_save_int_32(buf, X0);
1570 png_save_int_32(buf + 4, X1);
1571 buf[8] = (png_byte)type;
1572 buf[9] = (png_byte)nparams;
1573 png_write_chunk_data(png_ptr, buf, (png_size_t)10);
1574 png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
1576 png_free(png_ptr, new_purpose);
1578 for (i = 0; i < nparams; i++)
1580 png_write_chunk_data(png_ptr, (png_bytep)params[i],
1581 (png_size_t)params_len[i]);
1584 png_free(png_ptr, params_len);
1585 png_write_chunk_end(png_ptr);
1587 #endif
1589 #if defined(PNG_WRITE_sCAL_SUPPORTED)
1590 /* Write the sCAL chunk */
1591 #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
1592 void /* PRIVATE */
1593 png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
1595 #ifdef PNG_USE_LOCAL_ARRAYS
1596 PNG_sCAL;
1597 #endif
1598 char buf[64];
1599 png_size_t total_len;
1601 png_debug(1, "in png_write_sCAL");
1603 buf[0] = (char)unit;
1604 #if defined(_WIN32_WCE)
1605 /* sprintf() function is not supported on WindowsCE */
1607 wchar_t wc_buf[32];
1608 size_t wc_len;
1609 swprintf(wc_buf, TEXT("%12.12e"), width);
1610 wc_len = wcslen(wc_buf);
1611 WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
1612 total_len = wc_len + 2;
1613 swprintf(wc_buf, TEXT("%12.12e"), height);
1614 wc_len = wcslen(wc_buf);
1615 WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
1616 NULL, NULL);
1617 total_len += wc_len;
1619 #else
1620 png_snprintf(buf + 1, 63, "%12.12e", width);
1621 total_len = 1 + png_strlen(buf + 1) + 1;
1622 png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
1623 total_len += png_strlen(buf + total_len);
1624 #endif
1626 png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);
1627 png_write_chunk(png_ptr, (png_bytep)png_sCAL, (png_bytep)buf, total_len);
1629 #else
1630 #ifdef PNG_FIXED_POINT_SUPPORTED
1631 void /* PRIVATE */
1632 png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
1633 png_charp height)
1635 #ifdef PNG_USE_LOCAL_ARRAYS
1636 PNG_sCAL;
1637 #endif
1638 png_byte buf[64];
1639 png_size_t wlen, hlen, total_len;
1641 png_debug(1, "in png_write_sCAL_s");
1643 wlen = png_strlen(width);
1644 hlen = png_strlen(height);
1645 total_len = wlen + hlen + 2;
1646 if (total_len > 64)
1648 png_warning(png_ptr, "Can't write sCAL (buffer too small)");
1649 return;
1652 buf[0] = (png_byte)unit;
1653 png_memcpy(buf + 1, width, wlen + 1); /* Append the '\0' here */
1654 png_memcpy(buf + wlen + 2, height, hlen); /* Do NOT append the '\0' here */
1656 png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);
1657 png_write_chunk(png_ptr, (png_bytep)png_sCAL, buf, total_len);
1659 #endif
1660 #endif
1661 #endif
1663 #if defined(PNG_WRITE_pHYs_SUPPORTED)
1664 /* Write the pHYs chunk */
1665 void /* PRIVATE */
1666 png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
1667 png_uint_32 y_pixels_per_unit,
1668 int unit_type)
1670 #ifdef PNG_USE_LOCAL_ARRAYS
1671 PNG_pHYs;
1672 #endif
1673 png_byte buf[9];
1675 png_debug(1, "in png_write_pHYs");
1676 if (unit_type >= PNG_RESOLUTION_LAST)
1677 png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
1679 png_save_uint_32(buf, x_pixels_per_unit);
1680 png_save_uint_32(buf + 4, y_pixels_per_unit);
1681 buf[8] = (png_byte)unit_type;
1683 png_write_chunk(png_ptr, (png_bytep)png_pHYs, buf, (png_size_t)9);
1685 #endif
1687 #if defined(PNG_WRITE_tIME_SUPPORTED)
1688 /* Write the tIME chunk. Use either png_convert_from_struct_tm()
1689 * or png_convert_from_time_t(), or fill in the structure yourself.
1691 void /* PRIVATE */
1692 png_write_tIME(png_structp png_ptr, png_timep mod_time)
1694 #ifdef PNG_USE_LOCAL_ARRAYS
1695 PNG_tIME;
1696 #endif
1697 png_byte buf[7];
1699 png_debug(1, "in png_write_tIME");
1700 if (mod_time->month > 12 || mod_time->month < 1 ||
1701 mod_time->day > 31 || mod_time->day < 1 ||
1702 mod_time->hour > 23 || mod_time->second > 60)
1704 png_warning(png_ptr, "Invalid time specified for tIME chunk");
1705 return;
1708 png_save_uint_16(buf, mod_time->year);
1709 buf[2] = mod_time->month;
1710 buf[3] = mod_time->day;
1711 buf[4] = mod_time->hour;
1712 buf[5] = mod_time->minute;
1713 buf[6] = mod_time->second;
1715 png_write_chunk(png_ptr, (png_bytep)png_tIME, buf, (png_size_t)7);
1717 #endif
1719 /* Initializes the row writing capability of libpng */
1720 void /* PRIVATE */
1721 png_write_start_row(png_structp png_ptr)
1723 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
1724 #ifdef PNG_USE_LOCAL_ARRAYS
1725 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1727 /* Start of interlace block */
1728 int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1730 /* Offset to next interlace block */
1731 int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1733 /* Start of interlace block in the y direction */
1734 int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
1736 /* Offset to next interlace block in the y direction */
1737 int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
1738 #endif
1739 #endif
1741 png_size_t buf_size;
1743 png_debug(1, "in png_write_start_row");
1744 buf_size = (png_size_t)(PNG_ROWBYTES(
1745 png_ptr->usr_channels*png_ptr->usr_bit_depth, png_ptr->width) + 1);
1747 /* Set up row buffer */
1748 png_ptr->row_buf = (png_bytep)png_malloc(png_ptr,
1749 (png_uint_32)buf_size);
1750 png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
1752 #ifndef PNG_NO_WRITE_FILTER
1753 /* Set up filtering buffer, if using this filter */
1754 if (png_ptr->do_filter & PNG_FILTER_SUB)
1756 png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
1757 (png_uint_32)(png_ptr->rowbytes + 1));
1758 png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
1761 /* We only need to keep the previous row if we are using one of these. */
1762 if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
1764 /* Set up previous row buffer */
1765 png_ptr->prev_row = (png_bytep)png_malloc(png_ptr,
1766 (png_uint_32)buf_size);
1767 png_memset(png_ptr->prev_row, 0, buf_size);
1769 if (png_ptr->do_filter & PNG_FILTER_UP)
1771 png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
1772 (png_uint_32)(png_ptr->rowbytes + 1));
1773 png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
1776 if (png_ptr->do_filter & PNG_FILTER_AVG)
1778 png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
1779 (png_uint_32)(png_ptr->rowbytes + 1));
1780 png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
1783 if (png_ptr->do_filter & PNG_FILTER_PAETH)
1785 png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
1786 (png_uint_32)(png_ptr->rowbytes + 1));
1787 png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
1790 #endif /* PNG_NO_WRITE_FILTER */
1792 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
1793 /* If interlaced, we need to set up width and height of pass */
1794 if (png_ptr->interlaced)
1796 if (!(png_ptr->transformations & PNG_INTERLACE))
1798 png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
1799 png_pass_ystart[0]) / png_pass_yinc[0];
1800 png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
1801 png_pass_start[0]) / png_pass_inc[0];
1803 else
1805 png_ptr->num_rows = png_ptr->height;
1806 png_ptr->usr_width = png_ptr->width;
1809 else
1810 #endif
1812 png_ptr->num_rows = png_ptr->height;
1813 png_ptr->usr_width = png_ptr->width;
1815 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
1816 png_ptr->zstream.next_out = png_ptr->zbuf;
1819 /* Internal use only. Called when finished processing a row of data. */
1820 void /* PRIVATE */
1821 png_write_finish_row(png_structp png_ptr)
1823 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
1824 #ifdef PNG_USE_LOCAL_ARRAYS
1825 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1827 /* Start of interlace block */
1828 int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1830 /* Offset to next interlace block */
1831 int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1833 /* Start of interlace block in the y direction */
1834 int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
1836 /* Offset to next interlace block in the y direction */
1837 int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
1838 #endif
1839 #endif
1841 int ret;
1843 png_debug(1, "in png_write_finish_row");
1844 /* Next row */
1845 png_ptr->row_number++;
1847 /* See if we are done */
1848 if (png_ptr->row_number < png_ptr->num_rows)
1849 return;
1851 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
1852 /* If interlaced, go to next pass */
1853 if (png_ptr->interlaced)
1855 png_ptr->row_number = 0;
1856 if (png_ptr->transformations & PNG_INTERLACE)
1858 png_ptr->pass++;
1860 else
1862 /* Loop until we find a non-zero width or height pass */
1865 png_ptr->pass++;
1866 if (png_ptr->pass >= 7)
1867 break;
1868 png_ptr->usr_width = (png_ptr->width +
1869 png_pass_inc[png_ptr->pass] - 1 -
1870 png_pass_start[png_ptr->pass]) /
1871 png_pass_inc[png_ptr->pass];
1872 png_ptr->num_rows = (png_ptr->height +
1873 png_pass_yinc[png_ptr->pass] - 1 -
1874 png_pass_ystart[png_ptr->pass]) /
1875 png_pass_yinc[png_ptr->pass];
1876 if (png_ptr->transformations & PNG_INTERLACE)
1877 break;
1878 } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
1882 /* Reset the row above the image for the next pass */
1883 if (png_ptr->pass < 7)
1885 if (png_ptr->prev_row != NULL)
1886 png_memset(png_ptr->prev_row, 0,
1887 (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
1888 png_ptr->usr_bit_depth, png_ptr->width)) + 1);
1889 return;
1892 #endif
1894 /* If we get here, we've just written the last row, so we need
1895 to flush the compressor */
1898 /* Tell the compressor we are done */
1899 ret = deflate(&png_ptr->zstream, Z_FINISH);
1900 /* Check for an error */
1901 if (ret == Z_OK)
1903 /* Check to see if we need more room */
1904 if (!(png_ptr->zstream.avail_out))
1906 png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
1907 png_ptr->zstream.next_out = png_ptr->zbuf;
1908 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
1911 else if (ret != Z_STREAM_END)
1913 if (png_ptr->zstream.msg != NULL)
1914 png_error(png_ptr, png_ptr->zstream.msg);
1915 else
1916 png_error(png_ptr, "zlib error");
1918 } while (ret != Z_STREAM_END);
1920 /* Write any extra space */
1921 if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
1923 png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
1924 png_ptr->zstream.avail_out);
1927 deflateReset(&png_ptr->zstream);
1928 png_ptr->zstream.data_type = Z_BINARY;
1931 #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
1932 /* Pick out the correct pixels for the interlace pass.
1933 * The basic idea here is to go through the row with a source
1934 * pointer and a destination pointer (sp and dp), and copy the
1935 * correct pixels for the pass. As the row gets compacted,
1936 * sp will always be >= dp, so we should never overwrite anything.
1937 * See the default: case for the easiest code to understand.
1939 void /* PRIVATE */
1940 png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
1942 #ifdef PNG_USE_LOCAL_ARRAYS
1943 /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1945 /* Start of interlace block */
1946 int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1948 /* Offset to next interlace block */
1949 int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1950 #endif
1952 png_debug(1, "in png_do_write_interlace");
1953 /* We don't have to do anything on the last pass (6) */
1954 #if defined(PNG_USELESS_TESTS_SUPPORTED)
1955 if (row != NULL && row_info != NULL && pass < 6)
1956 #else
1957 if (pass < 6)
1958 #endif
1960 /* Each pixel depth is handled separately */
1961 switch (row_info->pixel_depth)
1963 case 1:
1965 png_bytep sp;
1966 png_bytep dp;
1967 int shift;
1968 int d;
1969 int value;
1970 png_uint_32 i;
1971 png_uint_32 row_width = row_info->width;
1973 dp = row;
1974 d = 0;
1975 shift = 7;
1976 for (i = png_pass_start[pass]; i < row_width;
1977 i += png_pass_inc[pass])
1979 sp = row + (png_size_t)(i >> 3);
1980 value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
1981 d |= (value << shift);
1983 if (shift == 0)
1985 shift = 7;
1986 *dp++ = (png_byte)d;
1987 d = 0;
1989 else
1990 shift--;
1993 if (shift != 7)
1994 *dp = (png_byte)d;
1995 break;
1997 case 2:
1999 png_bytep sp;
2000 png_bytep dp;
2001 int shift;
2002 int d;
2003 int value;
2004 png_uint_32 i;
2005 png_uint_32 row_width = row_info->width;
2007 dp = row;
2008 shift = 6;
2009 d = 0;
2010 for (i = png_pass_start[pass]; i < row_width;
2011 i += png_pass_inc[pass])
2013 sp = row + (png_size_t)(i >> 2);
2014 value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
2015 d |= (value << shift);
2017 if (shift == 0)
2019 shift = 6;
2020 *dp++ = (png_byte)d;
2021 d = 0;
2023 else
2024 shift -= 2;
2026 if (shift != 6)
2027 *dp = (png_byte)d;
2028 break;
2030 case 4:
2032 png_bytep sp;
2033 png_bytep dp;
2034 int shift;
2035 int d;
2036 int value;
2037 png_uint_32 i;
2038 png_uint_32 row_width = row_info->width;
2040 dp = row;
2041 shift = 4;
2042 d = 0;
2043 for (i = png_pass_start[pass]; i < row_width;
2044 i += png_pass_inc[pass])
2046 sp = row + (png_size_t)(i >> 1);
2047 value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
2048 d |= (value << shift);
2050 if (shift == 0)
2052 shift = 4;
2053 *dp++ = (png_byte)d;
2054 d = 0;
2056 else
2057 shift -= 4;
2059 if (shift != 4)
2060 *dp = (png_byte)d;
2061 break;
2063 default:
2065 png_bytep sp;
2066 png_bytep dp;
2067 png_uint_32 i;
2068 png_uint_32 row_width = row_info->width;
2069 png_size_t pixel_bytes;
2071 /* Start at the beginning */
2072 dp = row;
2073 /* Find out how many bytes each pixel takes up */
2074 pixel_bytes = (row_info->pixel_depth >> 3);
2075 /* Loop through the row, only looking at the pixels that
2076 matter */
2077 for (i = png_pass_start[pass]; i < row_width;
2078 i += png_pass_inc[pass])
2080 /* Find out where the original pixel is */
2081 sp = row + (png_size_t)i * pixel_bytes;
2082 /* Move the pixel */
2083 if (dp != sp)
2084 png_memcpy(dp, sp, pixel_bytes);
2085 /* Next pixel */
2086 dp += pixel_bytes;
2088 break;
2091 /* Set new row width */
2092 row_info->width = (row_info->width +
2093 png_pass_inc[pass] - 1 -
2094 png_pass_start[pass]) /
2095 png_pass_inc[pass];
2096 row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
2097 row_info->width);
2100 #endif
2102 /* This filters the row, chooses which filter to use, if it has not already
2103 * been specified by the application, and then writes the row out with the
2104 * chosen filter.
2106 #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
2107 #define PNG_HISHIFT 10
2108 #define PNG_LOMASK ((png_uint_32)0xffffL)
2109 #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
2110 void /* PRIVATE */
2111 png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
2113 png_bytep best_row;
2114 #ifndef PNG_NO_WRITE_FILTER
2115 png_bytep prev_row, row_buf;
2116 png_uint_32 mins, bpp;
2117 png_byte filter_to_do = png_ptr->do_filter;
2118 png_uint_32 row_bytes = row_info->rowbytes;
2119 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
2120 int num_p_filters = (int)png_ptr->num_prev_filters;
2121 #endif
2123 png_debug(1, "in png_write_find_filter");
2124 /* Find out how many bytes offset each pixel is */
2125 bpp = (row_info->pixel_depth + 7) >> 3;
2127 prev_row = png_ptr->prev_row;
2128 #endif
2129 best_row = png_ptr->row_buf;
2130 #ifndef PNG_NO_WRITE_FILTER
2131 row_buf = best_row;
2132 mins = PNG_MAXSUM;
2134 /* The prediction method we use is to find which method provides the
2135 * smallest value when summing the absolute values of the distances
2136 * from zero, using anything >= 128 as negative numbers. This is known
2137 * as the "minimum sum of absolute differences" heuristic. Other
2138 * heuristics are the "weighted minimum sum of absolute differences"
2139 * (experimental and can in theory improve compression), and the "zlib
2140 * predictive" method (not implemented yet), which does test compressions
2141 * of lines using different filter methods, and then chooses the
2142 * (series of) filter(s) that give minimum compressed data size (VERY
2143 * computationally expensive).
2145 * GRR 980525: consider also
2146 * (1) minimum sum of absolute differences from running average (i.e.,
2147 * keep running sum of non-absolute differences & count of bytes)
2148 * [track dispersion, too? restart average if dispersion too large?]
2149 * (1b) minimum sum of absolute differences from sliding average, probably
2150 * with window size <= deflate window (usually 32K)
2151 * (2) minimum sum of squared differences from zero or running average
2152 * (i.e., ~ root-mean-square approach)
2156 /* We don't need to test the 'no filter' case if this is the only filter
2157 * that has been chosen, as it doesn't actually do anything to the data.
2159 if ((filter_to_do & PNG_FILTER_NONE) &&
2160 filter_to_do != PNG_FILTER_NONE)
2162 png_bytep rp;
2163 png_uint_32 sum = 0;
2164 png_uint_32 i;
2165 int v;
2167 for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
2169 v = *rp;
2170 sum += (v < 128) ? v : 256 - v;
2173 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
2174 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2176 png_uint_32 sumhi, sumlo;
2177 int j;
2178 sumlo = sum & PNG_LOMASK;
2179 sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
2181 /* Reduce the sum if we match any of the previous rows */
2182 for (j = 0; j < num_p_filters; j++)
2184 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
2186 sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2187 PNG_WEIGHT_SHIFT;
2188 sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2189 PNG_WEIGHT_SHIFT;
2193 /* Factor in the cost of this filter (this is here for completeness,
2194 * but it makes no sense to have a "cost" for the NONE filter, as
2195 * it has the minimum possible computational cost - none).
2197 sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
2198 PNG_COST_SHIFT;
2199 sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
2200 PNG_COST_SHIFT;
2202 if (sumhi > PNG_HIMASK)
2203 sum = PNG_MAXSUM;
2204 else
2205 sum = (sumhi << PNG_HISHIFT) + sumlo;
2207 #endif
2208 mins = sum;
2211 /* Sub filter */
2212 if (filter_to_do == PNG_FILTER_SUB)
2213 /* It's the only filter so no testing is needed */
2215 png_bytep rp, lp, dp;
2216 png_uint_32 i;
2217 for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
2218 i++, rp++, dp++)
2220 *dp = *rp;
2222 for (lp = row_buf + 1; i < row_bytes;
2223 i++, rp++, lp++, dp++)
2225 *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
2227 best_row = png_ptr->sub_row;
2230 else if (filter_to_do & PNG_FILTER_SUB)
2232 png_bytep rp, dp, lp;
2233 png_uint_32 sum = 0, lmins = mins;
2234 png_uint_32 i;
2235 int v;
2237 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
2238 /* We temporarily increase the "minimum sum" by the factor we
2239 * would reduce the sum of this filter, so that we can do the
2240 * early exit comparison without scaling the sum each time.
2242 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2244 int j;
2245 png_uint_32 lmhi, lmlo;
2246 lmlo = lmins & PNG_LOMASK;
2247 lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
2249 for (j = 0; j < num_p_filters; j++)
2251 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
2253 lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2254 PNG_WEIGHT_SHIFT;
2255 lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2256 PNG_WEIGHT_SHIFT;
2260 lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2261 PNG_COST_SHIFT;
2262 lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2263 PNG_COST_SHIFT;
2265 if (lmhi > PNG_HIMASK)
2266 lmins = PNG_MAXSUM;
2267 else
2268 lmins = (lmhi << PNG_HISHIFT) + lmlo;
2270 #endif
2272 for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
2273 i++, rp++, dp++)
2275 v = *dp = *rp;
2277 sum += (v < 128) ? v : 256 - v;
2279 for (lp = row_buf + 1; i < row_bytes;
2280 i++, rp++, lp++, dp++)
2282 v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
2284 sum += (v < 128) ? v : 256 - v;
2286 if (sum > lmins) /* We are already worse, don't continue. */
2287 break;
2290 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
2291 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2293 int j;
2294 png_uint_32 sumhi, sumlo;
2295 sumlo = sum & PNG_LOMASK;
2296 sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
2298 for (j = 0; j < num_p_filters; j++)
2300 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
2302 sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
2303 PNG_WEIGHT_SHIFT;
2304 sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
2305 PNG_WEIGHT_SHIFT;
2309 sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2310 PNG_COST_SHIFT;
2311 sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2312 PNG_COST_SHIFT;
2314 if (sumhi > PNG_HIMASK)
2315 sum = PNG_MAXSUM;
2316 else
2317 sum = (sumhi << PNG_HISHIFT) + sumlo;
2319 #endif
2321 if (sum < mins)
2323 mins = sum;
2324 best_row = png_ptr->sub_row;
2328 /* Up filter */
2329 if (filter_to_do == PNG_FILTER_UP)
2331 png_bytep rp, dp, pp;
2332 png_uint_32 i;
2334 for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
2335 pp = prev_row + 1; i < row_bytes;
2336 i++, rp++, pp++, dp++)
2338 *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
2340 best_row = png_ptr->up_row;
2343 else if (filter_to_do & PNG_FILTER_UP)
2345 png_bytep rp, dp, pp;
2346 png_uint_32 sum = 0, lmins = mins;
2347 png_uint_32 i;
2348 int v;
2351 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
2352 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2354 int j;
2355 png_uint_32 lmhi, lmlo;
2356 lmlo = lmins & PNG_LOMASK;
2357 lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
2359 for (j = 0; j < num_p_filters; j++)
2361 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
2363 lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2364 PNG_WEIGHT_SHIFT;
2365 lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2366 PNG_WEIGHT_SHIFT;
2370 lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
2371 PNG_COST_SHIFT;
2372 lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
2373 PNG_COST_SHIFT;
2375 if (lmhi > PNG_HIMASK)
2376 lmins = PNG_MAXSUM;
2377 else
2378 lmins = (lmhi << PNG_HISHIFT) + lmlo;
2380 #endif
2382 for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
2383 pp = prev_row + 1; i < row_bytes; i++)
2385 v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
2387 sum += (v < 128) ? v : 256 - v;
2389 if (sum > lmins) /* We are already worse, don't continue. */
2390 break;
2393 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
2394 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2396 int j;
2397 png_uint_32 sumhi, sumlo;
2398 sumlo = sum & PNG_LOMASK;
2399 sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
2401 for (j = 0; j < num_p_filters; j++)
2403 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
2405 sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2406 PNG_WEIGHT_SHIFT;
2407 sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2408 PNG_WEIGHT_SHIFT;
2412 sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
2413 PNG_COST_SHIFT;
2414 sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
2415 PNG_COST_SHIFT;
2417 if (sumhi > PNG_HIMASK)
2418 sum = PNG_MAXSUM;
2419 else
2420 sum = (sumhi << PNG_HISHIFT) + sumlo;
2422 #endif
2424 if (sum < mins)
2426 mins = sum;
2427 best_row = png_ptr->up_row;
2431 /* Avg filter */
2432 if (filter_to_do == PNG_FILTER_AVG)
2434 png_bytep rp, dp, pp, lp;
2435 png_uint_32 i;
2436 for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
2437 pp = prev_row + 1; i < bpp; i++)
2439 *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
2441 for (lp = row_buf + 1; i < row_bytes; i++)
2443 *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
2444 & 0xff);
2446 best_row = png_ptr->avg_row;
2449 else if (filter_to_do & PNG_FILTER_AVG)
2451 png_bytep rp, dp, pp, lp;
2452 png_uint_32 sum = 0, lmins = mins;
2453 png_uint_32 i;
2454 int v;
2456 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
2457 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2459 int j;
2460 png_uint_32 lmhi, lmlo;
2461 lmlo = lmins & PNG_LOMASK;
2462 lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
2464 for (j = 0; j < num_p_filters; j++)
2466 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
2468 lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2469 PNG_WEIGHT_SHIFT;
2470 lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2471 PNG_WEIGHT_SHIFT;
2475 lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
2476 PNG_COST_SHIFT;
2477 lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
2478 PNG_COST_SHIFT;
2480 if (lmhi > PNG_HIMASK)
2481 lmins = PNG_MAXSUM;
2482 else
2483 lmins = (lmhi << PNG_HISHIFT) + lmlo;
2485 #endif
2487 for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
2488 pp = prev_row + 1; i < bpp; i++)
2490 v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
2492 sum += (v < 128) ? v : 256 - v;
2494 for (lp = row_buf + 1; i < row_bytes; i++)
2496 v = *dp++ =
2497 (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
2499 sum += (v < 128) ? v : 256 - v;
2501 if (sum > lmins) /* We are already worse, don't continue. */
2502 break;
2505 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
2506 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2508 int j;
2509 png_uint_32 sumhi, sumlo;
2510 sumlo = sum & PNG_LOMASK;
2511 sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
2513 for (j = 0; j < num_p_filters; j++)
2515 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
2517 sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2518 PNG_WEIGHT_SHIFT;
2519 sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2520 PNG_WEIGHT_SHIFT;
2524 sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
2525 PNG_COST_SHIFT;
2526 sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
2527 PNG_COST_SHIFT;
2529 if (sumhi > PNG_HIMASK)
2530 sum = PNG_MAXSUM;
2531 else
2532 sum = (sumhi << PNG_HISHIFT) + sumlo;
2534 #endif
2536 if (sum < mins)
2538 mins = sum;
2539 best_row = png_ptr->avg_row;
2543 /* Paeth filter */
2544 if (filter_to_do == PNG_FILTER_PAETH)
2546 png_bytep rp, dp, pp, cp, lp;
2547 png_uint_32 i;
2548 for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
2549 pp = prev_row + 1; i < bpp; i++)
2551 *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
2554 for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
2556 int a, b, c, pa, pb, pc, p;
2558 b = *pp++;
2559 c = *cp++;
2560 a = *lp++;
2562 p = b - c;
2563 pc = a - c;
2565 #ifdef PNG_USE_ABS
2566 pa = abs(p);
2567 pb = abs(pc);
2568 pc = abs(p + pc);
2569 #else
2570 pa = p < 0 ? -p : p;
2571 pb = pc < 0 ? -pc : pc;
2572 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
2573 #endif
2575 p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
2577 *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
2579 best_row = png_ptr->paeth_row;
2582 else if (filter_to_do & PNG_FILTER_PAETH)
2584 png_bytep rp, dp, pp, cp, lp;
2585 png_uint_32 sum = 0, lmins = mins;
2586 png_uint_32 i;
2587 int v;
2589 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
2590 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2592 int j;
2593 png_uint_32 lmhi, lmlo;
2594 lmlo = lmins & PNG_LOMASK;
2595 lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
2597 for (j = 0; j < num_p_filters; j++)
2599 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
2601 lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2602 PNG_WEIGHT_SHIFT;
2603 lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2604 PNG_WEIGHT_SHIFT;
2608 lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2609 PNG_COST_SHIFT;
2610 lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2611 PNG_COST_SHIFT;
2613 if (lmhi > PNG_HIMASK)
2614 lmins = PNG_MAXSUM;
2615 else
2616 lmins = (lmhi << PNG_HISHIFT) + lmlo;
2618 #endif
2620 for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
2621 pp = prev_row + 1; i < bpp; i++)
2623 v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
2625 sum += (v < 128) ? v : 256 - v;
2628 for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
2630 int a, b, c, pa, pb, pc, p;
2632 b = *pp++;
2633 c = *cp++;
2634 a = *lp++;
2636 #ifndef PNG_SLOW_PAETH
2637 p = b - c;
2638 pc = a - c;
2639 #ifdef PNG_USE_ABS
2640 pa = abs(p);
2641 pb = abs(pc);
2642 pc = abs(p + pc);
2643 #else
2644 pa = p < 0 ? -p : p;
2645 pb = pc < 0 ? -pc : pc;
2646 pc = (p + pc) < 0 ? -(p + pc) : p + pc;
2647 #endif
2648 p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
2649 #else /* PNG_SLOW_PAETH */
2650 p = a + b - c;
2651 pa = abs(p - a);
2652 pb = abs(p - b);
2653 pc = abs(p - c);
2654 if (pa <= pb && pa <= pc)
2655 p = a;
2656 else if (pb <= pc)
2657 p = b;
2658 else
2659 p = c;
2660 #endif /* PNG_SLOW_PAETH */
2662 v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
2664 sum += (v < 128) ? v : 256 - v;
2666 if (sum > lmins) /* We are already worse, don't continue. */
2667 break;
2670 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
2671 if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
2673 int j;
2674 png_uint_32 sumhi, sumlo;
2675 sumlo = sum & PNG_LOMASK;
2676 sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
2678 for (j = 0; j < num_p_filters; j++)
2680 if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
2682 sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2683 PNG_WEIGHT_SHIFT;
2684 sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2685 PNG_WEIGHT_SHIFT;
2689 sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2690 PNG_COST_SHIFT;
2691 sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2692 PNG_COST_SHIFT;
2694 if (sumhi > PNG_HIMASK)
2695 sum = PNG_MAXSUM;
2696 else
2697 sum = (sumhi << PNG_HISHIFT) + sumlo;
2699 #endif
2701 if (sum < mins)
2703 best_row = png_ptr->paeth_row;
2706 #endif /* PNG_NO_WRITE_FILTER */
2707 /* Do the actual writing of the filtered row data from the chosen filter. */
2709 png_write_filtered_row(png_ptr, best_row);
2711 #ifndef PNG_NO_WRITE_FILTER
2712 #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
2713 /* Save the type of filter we picked this time for future calculations */
2714 if (png_ptr->num_prev_filters > 0)
2716 int j;
2717 for (j = 1; j < num_p_filters; j++)
2719 png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
2721 png_ptr->prev_filters[j] = best_row[0];
2723 #endif
2724 #endif /* PNG_NO_WRITE_FILTER */
2728 /* Do the actual writing of a previously filtered row. */
2729 void /* PRIVATE */
2730 png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
2732 png_debug(1, "in png_write_filtered_row");
2733 png_debug1(2, "filter = %d", filtered_row[0]);
2734 /* Set up the zlib input buffer */
2736 png_ptr->zstream.next_in = filtered_row;
2737 png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
2738 /* Repeat until we have compressed all the data */
2741 int ret; /* Return of zlib */
2743 /* Compress the data */
2744 ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
2745 /* Check for compression errors */
2746 if (ret != Z_OK)
2748 if (png_ptr->zstream.msg != NULL)
2749 png_error(png_ptr, png_ptr->zstream.msg);
2750 else
2751 png_error(png_ptr, "zlib error");
2754 /* See if it is time to write another IDAT */
2755 if (!(png_ptr->zstream.avail_out))
2757 /* Write the IDAT and reset the zlib output buffer */
2758 png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
2759 png_ptr->zstream.next_out = png_ptr->zbuf;
2760 png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
2762 /* Repeat until all data has been compressed */
2763 } while (png_ptr->zstream.avail_in);
2765 /* Swap the current and previous rows */
2766 if (png_ptr->prev_row != NULL)
2768 png_bytep tptr;
2770 tptr = png_ptr->prev_row;
2771 png_ptr->prev_row = png_ptr->row_buf;
2772 png_ptr->row_buf = tptr;
2775 /* Finish row - updates counters and flushes zlib if last row */
2776 png_write_finish_row(png_ptr);
2778 #if defined(PNG_WRITE_FLUSH_SUPPORTED)
2779 png_ptr->flush_rows++;
2781 if (png_ptr->flush_dist > 0 &&
2782 png_ptr->flush_rows >= png_ptr->flush_dist)
2784 png_write_flush(png_ptr);
2786 #endif
2788 #endif /* PNG_WRITE_SUPPORTED */