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