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