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