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