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