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