pngwutil.c 83.1 KB
Newer Older
G
Guy Schalnat 已提交
1

A
Andreas Dilger 已提交
2
/* pngwutil.c - utilities to write a PNG file
3
 *
4
 * Last changed in libpng 1.4.0 [June 5, 2009]
5
 * For conditions of distribution and use, see copyright notice in png.h
6
 * Copyright (c) 1998-2009 Glenn Randers-Pehrson
7 8
 * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
 * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
9
 */
A
Andreas Dilger 已提交
10

G
Guy Schalnat 已提交
11
#include "png.h"
12
#ifdef PNG_WRITE_SUPPORTED
13
#include "pngpriv.h"
G
Guy Schalnat 已提交
14

A
Andreas Dilger 已提交
15 16 17 18
/* Place a 32-bit number into a buffer in PNG byte order.  We work
 * with unsigned numbers for convenience, although one supported
 * ancillary chunk uses signed (two's complement) numbers.
 */
19
void PNGAPI
G
Guy Schalnat 已提交
20
png_save_uint_32(png_bytep buf, png_uint_32 i)
G
Guy Schalnat 已提交
21 22 23 24 25 26 27
{
   buf[0] = (png_byte)((i >> 24) & 0xff);
   buf[1] = (png_byte)((i >> 16) & 0xff);
   buf[2] = (png_byte)((i >> 8) & 0xff);
   buf[3] = (png_byte)(i & 0xff);
}

28
#if defined(PNG_SAVE_INT_32_SUPPORTED)
A
Andreas Dilger 已提交
29
/* The png_save_int_32 function assumes integers are stored in two's
30 31 32
 * complement format.  If this isn't the case, then this routine needs to
 * be modified to write data in two's complement format.
 */
33
void PNGAPI
A
Andreas Dilger 已提交
34
png_save_int_32(png_bytep buf, png_int_32 i)
G
Guy Schalnat 已提交
35 36 37 38 39 40
{
   buf[0] = (png_byte)((i >> 24) & 0xff);
   buf[1] = (png_byte)((i >> 16) & 0xff);
   buf[2] = (png_byte)((i >> 8) & 0xff);
   buf[3] = (png_byte)(i & 0xff);
}
41
#endif
G
Guy Schalnat 已提交
42

43 44 45 46
/* Place a 16-bit number into a buffer in PNG byte order.
 * The parameter is declared unsigned int, not png_uint_16,
 * just to avoid potential problems on pre-ANSI C compilers.
 */
47
void PNGAPI
48
png_save_uint_16(png_bytep buf, unsigned int i)
G
Guy Schalnat 已提交
49 50 51 52 53
{
   buf[0] = (png_byte)((i >> 8) & 0xff);
   buf[1] = (png_byte)(i & 0xff);
}

54 55 56 57 58 59 60 61 62 63
/* Simple function to write the signature.  If we have already written
 * the magic bytes of the signature, or more likely, the PNG stream is
 * being embedded into another stream and doesn't need its own signature,
 * we should call png_set_sig_bytes() to tell libpng how many of the
 * bytes have already been written.
 */
void PNGAPI
png_write_sig(png_structp png_ptr)
{
   png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
64 65

#ifdef PNG_IO_STATE_SUPPORTED
66
   /* Inform the I/O callback that the signature is being written */
67 68 69
   png_ptr->io_state = PNG_IO_WRITING | PNG_IO_SIGNATURE;
#endif

70
   /* Write the rest of the 8 byte signature */
71
   png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
72
      (png_size_t)(8 - png_ptr->sig_bytes));
73
   if (png_ptr->sig_bytes < 3)
74 75 76
      png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
}

A
Andreas Dilger 已提交
77
/* Write a PNG chunk all at once.  The type is an array of ASCII characters
78 79 80 81 82 83 84 85
 * representing the chunk name.  The array must be at least 4 bytes in
 * length, and does not need to be null terminated.  To be safe, pass the
 * pre-defined chunk names here, and if you need a new one, define it
 * where the others are defined.  The length is the length of the data.
 * All the data must be present.  If that is not possible, use the
 * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
 * functions instead.
 */
86
void PNGAPI
A
Andreas Dilger 已提交
87
png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
A
Andreas Dilger 已提交
88
   png_bytep data, png_size_t length)
G
Guy Schalnat 已提交
89
{
90 91
   if (png_ptr == NULL)
      return;
A
Andreas Dilger 已提交
92
   png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
93
   png_write_chunk_data(png_ptr, data, (png_size_t)length);
A
Andreas Dilger 已提交
94
   png_write_chunk_end(png_ptr);
G
Guy Schalnat 已提交
95 96
}

A
Andreas Dilger 已提交
97
/* Write the start of a PNG chunk.  The type is the chunk type.
98 99 100
 * The total_length is the sum of the lengths of all the data you will be
 * passing in png_write_chunk_data().
 */
101
void PNGAPI
A
Andreas Dilger 已提交
102 103
png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
   png_uint_32 length)
G
Guy Schalnat 已提交
104
{
105 106 107 108 109 110 111 112
   png_byte buf[8];

#ifdef PNG_IO_STATE_SUPPORTED
   /* Inform the I/O callback that the chunk header is being written.
    * PNG_IO_CHUNK_HDR requires a single I/O call.
    */
   png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_HDR;
#endif
A
Andreas Dilger 已提交
113

114
   png_debug2(0, "Writing %s chunk, length = %lu", chunk_name,
115
      (unsigned long)length);
116 117
   if (png_ptr == NULL)
      return;
118

119
   /* Write the length and the chunk name */
A
Andreas Dilger 已提交
120
   png_save_uint_32(buf, length);
121
   png_memcpy(buf + 4, chunk_name, 4);
122
   png_write_data(png_ptr, buf, (png_size_t)8);
123
   /* Put the chunk name into png_ptr->chunk_name */
124
   png_memcpy(png_ptr->chunk_name, chunk_name, 4);
125
   /* Reset the crc and run it over the chunk name */
G
Guy Schalnat 已提交
126
   png_reset_crc(png_ptr);
127 128 129 130 131 132 133 134
   png_calculate_crc(png_ptr, chunk_name, 4);

#ifdef PNG_IO_STATE_SUPPORTED
   /* Inform the I/O callback that chunk data will (possibly) be written.
    * PNG_IO_CHUNK_DATA does NOT require a specific number of I/O calls.
    */
   png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_DATA;
#endif
G
Guy Schalnat 已提交
135 136
}

A
Andreas Dilger 已提交
137
/* Write the data of a PNG chunk started with png_write_chunk_start().
138 139 140 141
 * Note that multiple calls to this function are allowed, and that the
 * sum of the lengths from these calls *must* add up to the total_length
 * given to png_write_chunk_start().
 */
142
void PNGAPI
A
Andreas Dilger 已提交
143
png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
G
Guy Schalnat 已提交
144
{
145 146 147
   /* Write the data, and run the CRC over it */
   if (png_ptr == NULL)
      return;
A
Andreas Dilger 已提交
148
   if (data != NULL && length > 0)
G
Guy Schalnat 已提交
149
   {
G
Guy Schalnat 已提交
150
      png_write_data(png_ptr, data, length);
151
      /* Update the CRC after writing the data,
152 153 154
       * in case that the user I/O routine alters it.
       */
      png_calculate_crc(png_ptr, data, length);
G
Guy Schalnat 已提交
155 156 157
   }
}

A
Andreas Dilger 已提交
158
/* Finish a chunk started with png_write_chunk_start(). */
159
void PNGAPI
G
Guy Schalnat 已提交
160
png_write_chunk_end(png_structp png_ptr)
G
Guy Schalnat 已提交
161
{
A
Andreas Dilger 已提交
162 163
   png_byte buf[4];

164 165
   if (png_ptr == NULL) return;

166 167 168 169 170 171 172
#ifdef PNG_IO_STATE_SUPPORTED
   /* Inform the I/O callback that the chunk CRC is being written.
    * PNG_IO_CHUNK_CRC requires a single I/O function call.
    */
   png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_CRC;
#endif

173
   /* Write the crc in a single operation */
A
Andreas Dilger 已提交
174 175
   png_save_uint_32(buf, png_ptr->crc);

176
   png_write_data(png_ptr, buf, (png_size_t)4);
G
Guy Schalnat 已提交
177 178
}

179
#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
180
/* This pair of functions encapsulates the operation of (a) compressing a
181 182 183 184 185 186 187
 * text string, and (b) issuing it later as a series of chunk data writes.
 * The compression_state structure is shared context for these functions
 * set up by the caller in order to make the whole mess thread-safe.
 */

typedef struct
{
188 189 190 191 192
   char *input;   /* The uncompressed input data */
   int input_len;   /* Its length */
   int num_output_ptr; /* Number of output pointers used */
   int max_output_ptr; /* Size of output_ptr */
   png_charpp output_ptr; /* Array of pointers to output */
193 194
} compression_state;

195
/* Compress given text into storage in the png_ptr structure */
196
static int /* PRIVATE */
197 198 199 200 201 202
png_text_compress(png_structp png_ptr,
        png_charp text, png_size_t text_len, int compression,
        compression_state *comp)
{
   int ret;

203 204
   comp->num_output_ptr = 0;
   comp->max_output_ptr = 0;
205 206
   comp->output_ptr = NULL;
   comp->input = NULL;
207
   comp->input_len = 0;
208

209
   /* We may just want to pass the text right through */
210 211 212 213
   if (compression == PNG_TEXT_COMPRESSION_NONE)
   {
       comp->input = text;
       comp->input_len = text_len;
214
       return((int)text_len);
215 216 217 218
   }

   if (compression >= PNG_TEXT_COMPRESSION_LAST)
   {
219
#if !defined(PNG_NO_STDIO)
220
      char msg[50];
221
      png_snprintf(msg, 50, "Unknown compression type %d", compression);
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
      png_warning(png_ptr, msg);
#else
      png_warning(png_ptr, "Unknown compression type");
#endif
   }

   /* We can't write the chunk until we find out how much data we have,
    * which means we need to run the compressor first and save the
    * output.  This shouldn't be a problem, as the vast majority of
    * comments should be reasonable, but we will set up an array of
    * malloc'd pointers to be sure.
    *
    * If we knew the application was well behaved, we could simplify this
    * greatly by assuming we can always malloc an output buffer large
    * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
    * and malloc this directly.  The only time this would be a bad idea is
    * if we can't malloc more than 64K and we have 64K of random input
    * data, or if the input string is incredibly large (although this
    * wouldn't cause a failure, just a slowdown due to swapping).
    */

243
   /* Set up the compression buffers */
244 245 246 247 248
   png_ptr->zstream.avail_in = (uInt)text_len;
   png_ptr->zstream.next_in = (Bytef *)text;
   png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
   png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;

249
   /* This is the same compression loop as in png_write_row() */
250 251
   do
   {
252
      /* Compress the data */
253 254 255
      ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
      if (ret != Z_OK)
      {
256
         /* Error */
257 258 259 260 261
         if (png_ptr->zstream.msg != NULL)
            png_error(png_ptr, png_ptr->zstream.msg);
         else
            png_error(png_ptr, "zlib error");
      }
262
      /* Check to see if we need more room */
263
      if (!(png_ptr->zstream.avail_out))
264
      {
265
         /* Make sure the output array has room */
266 267 268 269 270 271 272 273 274 275 276 277
         if (comp->num_output_ptr >= comp->max_output_ptr)
         {
            int old_max;

            old_max = comp->max_output_ptr;
            comp->max_output_ptr = comp->num_output_ptr + 4;
            if (comp->output_ptr != NULL)
            {
               png_charpp old_ptr;

               old_ptr = comp->output_ptr;
               comp->output_ptr = (png_charpp)png_malloc(png_ptr,
278
                  (png_alloc_size_t)
279
                  (comp->max_output_ptr * png_sizeof(png_charpp)));
280
               png_memcpy(comp->output_ptr, old_ptr, old_max
281
                  * png_sizeof(png_charp));
282 283 284 285
               png_free(png_ptr, old_ptr);
            }
            else
               comp->output_ptr = (png_charpp)png_malloc(png_ptr,
286
                  (png_alloc_size_t)
287
                  (comp->max_output_ptr * png_sizeof(png_charp)));
288 289
         }

290
         /* Save the data */
291
         comp->output_ptr[comp->num_output_ptr] =
292
            (png_charp)png_malloc(png_ptr,
293
            (png_alloc_size_t)png_ptr->zbuf_size);
294 295 296
         png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
            png_ptr->zbuf_size);
         comp->num_output_ptr++;
297 298 299 300 301

         /* and reset the buffer */
         png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
         png_ptr->zstream.next_out = png_ptr->zbuf;
      }
302
   /* Continue until we don't have any more to compress */
303 304
   } while (png_ptr->zstream.avail_in);

305
   /* Finish the compression */
306 307
   do
   {
308
      /* Tell zlib we are finished */
309 310
      ret = deflate(&png_ptr->zstream, Z_FINISH);

311
      if (ret == Z_OK)
312
      {
313
         /* Check to see if we need more room */
314
         if (!(png_ptr->zstream.avail_out))
315
         {
316
            /* Check to make sure our output array has room */
317
            if (comp->num_output_ptr >= comp->max_output_ptr)
318
            {
319 320 321 322 323 324 325 326 327 328 329
               int old_max;

               old_max = comp->max_output_ptr;
               comp->max_output_ptr = comp->num_output_ptr + 4;
               if (comp->output_ptr != NULL)
               {
                  png_charpp old_ptr;

                  old_ptr = comp->output_ptr;
                  /* This could be optimized to realloc() */
                  comp->output_ptr = (png_charpp)png_malloc(png_ptr,
330
                     (png_alloc_size_t)(comp->max_output_ptr *
331
                     png_sizeof(png_charp)));
332
                  png_memcpy(comp->output_ptr, old_ptr,
333
                     old_max * png_sizeof(png_charp));
334 335 336 337
                  png_free(png_ptr, old_ptr);
               }
               else
                  comp->output_ptr = (png_charpp)png_malloc(png_ptr,
338
                     (png_alloc_size_t)(comp->max_output_ptr *
339
                     png_sizeof(png_charp)));
340 341
            }

342
            /* Save the data */
343
            comp->output_ptr[comp->num_output_ptr] =
344
               (png_charp)png_malloc(png_ptr,
345
               (png_alloc_size_t)png_ptr->zbuf_size);
346 347 348
            png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
               png_ptr->zbuf_size);
            comp->num_output_ptr++;
349

350 351 352 353 354 355 356
            /* and reset the buffer pointers */
            png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
            png_ptr->zstream.next_out = png_ptr->zbuf;
         }
      }
      else if (ret != Z_STREAM_END)
      {
357
         /* We got an error */
358 359 360 361
         if (png_ptr->zstream.msg != NULL)
            png_error(png_ptr, png_ptr->zstream.msg);
         else
            png_error(png_ptr, "zlib error");
362 363 364
      }
   } while (ret != Z_STREAM_END);

365
   /* Text length is number of buffers plus last buffer */
366 367 368 369
   text_len = png_ptr->zbuf_size * comp->num_output_ptr;
   if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
      text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;

370
   return((int)text_len);
371 372
}

373
/* Ship the compressed text out via chunk writes */
374
static void /* PRIVATE */
375 376 377 378
png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
{
   int i;

379
   /* Handle the no-compression case */
380 381
   if (comp->input)
   {
382
      png_write_chunk_data(png_ptr, (png_bytep)comp->input,
383
                            (png_size_t)comp->input_len);
384
      return;
385 386
   }

387
   /* Write saved output buffers, if any */
388 389
   for (i = 0; i < comp->num_output_ptr; i++)
   {
390 391
      png_write_chunk_data(png_ptr, (png_bytep)comp->output_ptr[i],
         (png_size_t)png_ptr->zbuf_size);
392 393 394 395
      png_free(png_ptr, comp->output_ptr[i]);
   }
   if (comp->max_output_ptr != 0)
      png_free(png_ptr, comp->output_ptr);
396
   /* Write anything left in zbuf */
397 398
   if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
      png_write_chunk_data(png_ptr, png_ptr->zbuf,
399
         (png_size_t)(png_ptr->zbuf_size - png_ptr->zstream.avail_out));
400

401
   /* Reset zlib for another zTXt/iTXt or image data */
402
   deflateReset(&png_ptr->zstream);
403
   png_ptr->zstream.data_type = Z_BINARY;
404 405 406
}
#endif

G
Guy Schalnat 已提交
407
/* Write the IHDR chunk, and update the png_struct with the necessary
408 409 410
 * information.  Note that the rest of this code depends upon this
 * information being correct.
 */
411
void /* PRIVATE */
G
Guy Schalnat 已提交
412
png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
G
Guy Schalnat 已提交
413 414 415
   int bit_depth, int color_type, int compression_type, int filter_type,
   int interlace_type)
{
416 417 418
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_IHDR;
#endif
419 420
   int ret;

421
   png_byte buf[13]; /* Buffer to store the IHDR info */
G
Guy Schalnat 已提交
422

423
   png_debug(1, "in png_write_IHDR");
G
Guy Schalnat 已提交
424
   /* Check that we have valid input data from the application info */
G
Guy Schalnat 已提交
425 426
   switch (color_type)
   {
A
Andreas Dilger 已提交
427
      case PNG_COLOR_TYPE_GRAY:
G
Guy Schalnat 已提交
428 429 430 431 432 433 434
         switch (bit_depth)
         {
            case 1:
            case 2:
            case 4:
            case 8:
            case 16: png_ptr->channels = 1; break;
435
            default: png_error(png_ptr, "Invalid bit depth for grayscale image");
G
Guy Schalnat 已提交
436
         }
G
Guy Schalnat 已提交
437
         break;
A
Andreas Dilger 已提交
438
      case PNG_COLOR_TYPE_RGB:
G
Guy Schalnat 已提交
439 440
         if (bit_depth != 8 && bit_depth != 16)
            png_error(png_ptr, "Invalid bit depth for RGB image");
G
Guy Schalnat 已提交
441 442
         png_ptr->channels = 3;
         break;
A
Andreas Dilger 已提交
443
      case PNG_COLOR_TYPE_PALETTE:
G
Guy Schalnat 已提交
444 445 446 447 448 449 450 451 452
         switch (bit_depth)
         {
            case 1:
            case 2:
            case 4:
            case 8: png_ptr->channels = 1; break;
            default: png_error(png_ptr, "Invalid bit depth for paletted image");
         }
         break;
A
Andreas Dilger 已提交
453
      case PNG_COLOR_TYPE_GRAY_ALPHA:
G
Guy Schalnat 已提交
454 455
         if (bit_depth != 8 && bit_depth != 16)
            png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
G
Guy Schalnat 已提交
456 457
         png_ptr->channels = 2;
         break;
A
Andreas Dilger 已提交
458
      case PNG_COLOR_TYPE_RGB_ALPHA:
G
Guy Schalnat 已提交
459 460
         if (bit_depth != 8 && bit_depth != 16)
            png_error(png_ptr, "Invalid bit depth for RGBA image");
G
Guy Schalnat 已提交
461 462
         png_ptr->channels = 4;
         break;
G
Guy Schalnat 已提交
463 464 465 466
      default:
         png_error(png_ptr, "Invalid image color type specified");
   }

A
Andreas Dilger 已提交
467
   if (compression_type != PNG_COMPRESSION_TYPE_BASE)
G
Guy Schalnat 已提交
468 469
   {
      png_warning(png_ptr, "Invalid compression type specified");
A
Andreas Dilger 已提交
470
      compression_type = PNG_COMPRESSION_TYPE_BASE;
G
Guy Schalnat 已提交
471 472
   }

473 474 475 476 477 478 479 480 481
   /* Write filter_method 64 (intrapixel differencing) only if
    * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
    * 2. Libpng did not write a PNG signature (this filter_method is only
    *    used in PNG datastreams that are embedded in MNG datastreams) and
    * 3. The application called png_permit_mng_features with a mask that
    *    included PNG_FLAG_MNG_FILTER_64 and
    * 4. The filter_method is 64 and
    * 5. The color_type is RGB or RGBA
    */
482 483 484
   if (
#if defined(PNG_MNG_FEATURES_SUPPORTED)
      !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
485
      ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
486
      (color_type == PNG_COLOR_TYPE_RGB ||
487
       color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
488 489 490
      (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
#endif
      filter_type != PNG_FILTER_TYPE_BASE)
G
Guy Schalnat 已提交
491 492
   {
      png_warning(png_ptr, "Invalid filter type specified");
A
Andreas Dilger 已提交
493
      filter_type = PNG_FILTER_TYPE_BASE;
G
Guy Schalnat 已提交
494 495
   }

496
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
A
Andreas Dilger 已提交
497 498
   if (interlace_type != PNG_INTERLACE_NONE &&
      interlace_type != PNG_INTERLACE_ADAM7)
G
Guy Schalnat 已提交
499 500
   {
      png_warning(png_ptr, "Invalid interlace type specified");
A
Andreas Dilger 已提交
501
      interlace_type = PNG_INTERLACE_ADAM7;
G
Guy Schalnat 已提交
502
   }
503 504 505
#else
   interlace_type=PNG_INTERLACE_NONE;
#endif
G
Guy Schalnat 已提交
506

507
   /* Save the relevent information */
G
Guy Schalnat 已提交
508 509 510
   png_ptr->bit_depth = (png_byte)bit_depth;
   png_ptr->color_type = (png_byte)color_type;
   png_ptr->interlaced = (png_byte)interlace_type;
511
#if defined(PNG_MNG_FEATURES_SUPPORTED)
512
   png_ptr->filter_type = (png_byte)filter_type;
513
#endif
514
   png_ptr->compression_type = (png_byte)compression_type;
G
Guy Schalnat 已提交
515 516 517
   png_ptr->width = width;
   png_ptr->height = height;

G
Guy Schalnat 已提交
518
   png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
519
   png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
520
   /* Set the usr info, so any transformations can modify it */
G
Guy Schalnat 已提交
521 522
   png_ptr->usr_width = png_ptr->width;
   png_ptr->usr_bit_depth = png_ptr->bit_depth;
G
Guy Schalnat 已提交
523 524
   png_ptr->usr_channels = png_ptr->channels;

525
   /* Pack the header information into the buffer */
G
Guy Schalnat 已提交
526 527 528 529 530 531 532
   png_save_uint_32(buf, width);
   png_save_uint_32(buf + 4, height);
   buf[8] = (png_byte)bit_depth;
   buf[9] = (png_byte)color_type;
   buf[10] = (png_byte)compression_type;
   buf[11] = (png_byte)filter_type;
   buf[12] = (png_byte)interlace_type;
G
Guy Schalnat 已提交
533

534
   /* Write the chunk */
535
   png_write_chunk(png_ptr, (png_bytep)png_IHDR, buf, (png_size_t)13);
G
Guy Schalnat 已提交
536

537
   /* Initialize zlib with PNG info */
A
Andreas Dilger 已提交
538 539 540
   png_ptr->zstream.zalloc = png_zalloc;
   png_ptr->zstream.zfree = png_zfree;
   png_ptr->zstream.opaque = (voidpf)png_ptr;
G
Guy Schalnat 已提交
541
   if (!(png_ptr->do_filter))
G
Guy Schalnat 已提交
542
   {
A
Andreas Dilger 已提交
543 544
      if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
         png_ptr->bit_depth < 8)
G
Guy Schalnat 已提交
545
         png_ptr->do_filter = PNG_FILTER_NONE;
G
Guy Schalnat 已提交
546
      else
G
Guy Schalnat 已提交
547
         png_ptr->do_filter = PNG_ALL_FILTERS;
G
Guy Schalnat 已提交
548
   }
G
Guy Schalnat 已提交
549
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
G
Guy Schalnat 已提交
550
   {
G
Guy Schalnat 已提交
551
      if (png_ptr->do_filter != PNG_FILTER_NONE)
G
Guy Schalnat 已提交
552 553 554 555
         png_ptr->zlib_strategy = Z_FILTERED;
      else
         png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
   }
G
Guy Schalnat 已提交
556
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
G
Guy Schalnat 已提交
557
      png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
G
Guy Schalnat 已提交
558
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
G
Guy Schalnat 已提交
559
      png_ptr->zlib_mem_level = 8;
G
Guy Schalnat 已提交
560
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
561
      png_ptr->zlib_window_bits = 15;
G
Guy Schalnat 已提交
562
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
G
Guy Schalnat 已提交
563
      png_ptr->zlib_method = 8;
564 565 566 567 568 569 570 571 572 573 574 575 576
   ret = deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
         png_ptr->zlib_method, png_ptr->zlib_window_bits,
         png_ptr->zlib_mem_level, png_ptr->zlib_strategy);
   if (ret != Z_OK)
   {
      if (ret == Z_VERSION_ERROR) png_error(png_ptr,
          "zlib failed to initialize compressor -- version error");
      if (ret == Z_STREAM_ERROR) png_error(png_ptr,
           "zlib failed to initialize compressor -- stream error");
      if (ret == Z_MEM_ERROR) png_error(png_ptr,
           "zlib failed to initialize compressor -- mem error");
      png_error(png_ptr, "zlib failed to initialize compressor");
   }
A
Andreas Dilger 已提交
577 578
   png_ptr->zstream.next_out = png_ptr->zbuf;
   png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
579
   /* libpng is not interested in zstream.data_type */
580
   /* Set it to a predefined value, to avoid its evaluation inside zlib */
581
   png_ptr->zstream.data_type = Z_BINARY;
G
Guy Schalnat 已提交
582

G
Guy Schalnat 已提交
583
   png_ptr->mode = PNG_HAVE_IHDR;
G
Guy Schalnat 已提交
584 585
}

586
/* Write the palette.  We are careful not to trust png_color to be in the
587
 * correct order for PNG, so people can redefine it to any convenient
588 589
 * structure.
 */
590
void /* PRIVATE */
A
Andreas Dilger 已提交
591
png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
G
Guy Schalnat 已提交
592
{
593 594 595
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_PLTE;
#endif
A
Andreas Dilger 已提交
596
   png_uint_32 i;
G
Guy Schalnat 已提交
597
   png_colorp pal_ptr;
G
Guy Schalnat 已提交
598 599
   png_byte buf[3];

600
   png_debug(1, "in png_write_PLTE");
601
   if ((
602
#if defined(PNG_MNG_FEATURES_SUPPORTED)
603
        !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
604 605
#endif
        num_pal == 0) || num_pal > 256)
606 607
   {
     if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
608
     {
609 610 611 612 613 614 615 616 617 618 619 620 621 622
        png_error(png_ptr, "Invalid number of colors in palette");
     }
     else
     {
        png_warning(png_ptr, "Invalid number of colors in palette");
        return;
     }
   }

   if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
   {
      png_warning(png_ptr,
        "Ignoring request to write a PLTE chunk in grayscale PNG");
      return;
G
Guy Schalnat 已提交
623 624
   }

A
Andreas Dilger 已提交
625
   png_ptr->num_palette = (png_uint_16)num_pal;
626
   png_debug1(3, "num_palette = %d", png_ptr->num_palette);
G
Guy Schalnat 已提交
627

628 629
   png_write_chunk_start(png_ptr, (png_bytep)png_PLTE,
     (png_uint_32)(num_pal * 3));
630
#ifndef PNG_NO_POINTER_INDEXING
A
Andreas Dilger 已提交
631
   for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
G
Guy Schalnat 已提交
632 633 634 635
   {
      buf[0] = pal_ptr->red;
      buf[1] = pal_ptr->green;
      buf[2] = pal_ptr->blue;
636
      png_write_chunk_data(png_ptr, buf, (png_size_t)3);
G
Guy Schalnat 已提交
637
   }
638 639 640 641 642 643 644 645
#else
   /* This is a little slower but some buggy compilers need to do this instead */
   pal_ptr=palette;
   for (i = 0; i < num_pal; i++)
   {
      buf[0] = pal_ptr[i].red;
      buf[1] = pal_ptr[i].green;
      buf[2] = pal_ptr[i].blue;
646
      png_write_chunk_data(png_ptr, buf, (png_size_t)3);
647 648
   }
#endif
G
Guy Schalnat 已提交
649
   png_write_chunk_end(png_ptr);
G
Guy Schalnat 已提交
650
   png_ptr->mode |= PNG_HAVE_PLTE;
G
Guy Schalnat 已提交
651 652
}

653
/* Write an IDAT chunk */
654
void /* PRIVATE */
A
Andreas Dilger 已提交
655
png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
G
Guy Schalnat 已提交
656
{
657 658 659
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_IDAT;
#endif
660
   png_debug(1, "in png_write_IDAT");
661

662 663 664 665 666 667 668 669
   /* Optimize the CMF field in the zlib stream. */
   /* This hack of the zlib stream is compliant to the stream specification. */
   if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
       png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
   {
      unsigned int z_cmf = data[0];  /* zlib compression method and flags */
      if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
      {
670 671 672 673 674
         /* Avoid memory underflows and multiplication overflows.
          *
          * The conditions below are practically always satisfied;
          * however, they still must be checked.
          */
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
         if (length >= 2 &&
             png_ptr->height < 16384 && png_ptr->width < 16384)
         {
            png_uint_32 uncompressed_idat_size = png_ptr->height *
               ((png_ptr->width *
               png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
            unsigned int z_cinfo = z_cmf >> 4;
            unsigned int half_z_window_size = 1 << (z_cinfo + 7);
            while (uncompressed_idat_size <= half_z_window_size &&
                   half_z_window_size >= 256)
            {
               z_cinfo--;
               half_z_window_size >>= 1;
            }
            z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
            if (data[0] != (png_byte)z_cmf)
            {
               data[0] = (png_byte)z_cmf;
               data[1] &= 0xe0;
               data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
            }
         }
      }
      else
         png_error(png_ptr,
            "Invalid zlib compression method or flags in IDAT");
   }

703
   png_write_chunk(png_ptr, (png_bytep)png_IDAT, data, length);
G
Guy Schalnat 已提交
704
   png_ptr->mode |= PNG_HAVE_IDAT;
G
Guy Schalnat 已提交
705 706
}

707
/* Write an IEND chunk */
708
void /* PRIVATE */
G
Guy Schalnat 已提交
709
png_write_IEND(png_structp png_ptr)
G
Guy Schalnat 已提交
710
{
711 712 713
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_IEND;
#endif
714
   png_debug(1, "in png_write_IEND");
715 716
   png_write_chunk(png_ptr, (png_bytep)png_IEND, NULL,
     (png_size_t)0);
A
Andreas Dilger 已提交
717
   png_ptr->mode |= PNG_HAVE_IEND;
G
Guy Schalnat 已提交
718 719
}

G
Guy Schalnat 已提交
720
#if defined(PNG_WRITE_gAMA_SUPPORTED)
721
/* Write a gAMA chunk */
722
#ifdef PNG_FLOATING_POINT_SUPPORTED
723
void /* PRIVATE */
A
Andreas Dilger 已提交
724
png_write_gAMA(png_structp png_ptr, double file_gamma)
G
Guy Schalnat 已提交
725
{
726 727 728
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_gAMA;
#endif
G
Guy Schalnat 已提交
729 730 731
   png_uint_32 igamma;
   png_byte buf[4];

732
   png_debug(1, "in png_write_gAMA");
733
   /* file_gamma is saved in 1/100,000ths */
734
   igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
G
Guy Schalnat 已提交
735
   png_save_uint_32(buf, igamma);
736
   png_write_chunk(png_ptr, (png_bytep)png_gAMA, buf, (png_size_t)4);
G
Guy Schalnat 已提交
737
}
G
Guy Schalnat 已提交
738
#endif
739
#ifdef PNG_FIXED_POINT_SUPPORTED
740
void /* PRIVATE */
741
png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
742 743 744 745 746 747
{
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_gAMA;
#endif
   png_byte buf[4];

748
   png_debug(1, "in png_write_gAMA");
749
   /* file_gamma is saved in 1/100,000ths */
750
   png_save_uint_32(buf, (png_uint_32)file_gamma);
751
   png_write_chunk(png_ptr, (png_bytep)png_gAMA, buf, (png_size_t)4);
752 753 754
}
#endif
#endif
G
Guy Schalnat 已提交
755

756
#if defined(PNG_WRITE_sRGB_SUPPORTED)
757
/* Write a sRGB chunk */
758
void /* PRIVATE */
759
png_write_sRGB(png_structp png_ptr, int srgb_intent)
760
{
761 762 763
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_sRGB;
#endif
764 765
   png_byte buf[1];

766
   png_debug(1, "in png_write_sRGB");
767
   if (srgb_intent >= PNG_sRGB_INTENT_LAST)
768 769
         png_warning(png_ptr,
            "Invalid sRGB rendering intent specified");
770
   buf[0]=(png_byte)srgb_intent;
771
   png_write_chunk(png_ptr, (png_bytep)png_sRGB, buf, (png_size_t)1);
772 773 774
}
#endif

775
#if defined(PNG_WRITE_iCCP_SUPPORTED)
776
/* Write an iCCP chunk */
777
void /* PRIVATE */
778 779 780 781 782 783 784 785 786
png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
   png_charp profile, int profile_len)
{
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_iCCP;
#endif
   png_size_t name_len;
   png_charp new_name;
   compression_state comp;
787
   int embedded_profile_len = 0;
788

789
   png_debug(1, "in png_write_iCCP");
790 791 792 793 794 795 796

   comp.num_output_ptr = 0;
   comp.max_output_ptr = 0;
   comp.output_ptr = NULL;
   comp.input = NULL;
   comp.input_len = 0;

797
   if ((name_len = png_check_keyword(png_ptr, name,
798 799 800
      &new_name)) == 0)
      return;

801
   if (compression_type != PNG_COMPRESSION_TYPE_BASE)
802
      png_warning(png_ptr, "Unknown compression type in iCCP chunk");
803

804
   if (profile == NULL)
805 806
      profile_len = 0;

807
   if (profile_len > 3)
808
      embedded_profile_len =
809 810 811 812
          ((*( (png_bytep)profile    ))<<24) |
          ((*( (png_bytep)profile + 1))<<16) |
          ((*( (png_bytep)profile + 2))<< 8) |
          ((*( (png_bytep)profile + 3))    );
813 814

   if (profile_len < embedded_profile_len)
815 816 817
   {
      png_warning(png_ptr,
        "Embedded profile length too large in iCCP chunk");
818
      png_free(png_ptr, new_name);
819 820
      return;
   }
821 822

   if (profile_len > embedded_profile_len)
823 824 825 826 827
   {
      png_warning(png_ptr,
        "Truncating profile to actual length in iCCP chunk");
      profile_len = embedded_profile_len;
   }
828

829
   if (profile_len)
830 831
      profile_len = png_text_compress(png_ptr, profile,
        (png_size_t)profile_len, PNG_COMPRESSION_TYPE_BASE, &comp);
832

833
   /* Make sure we include the NULL after the name and the compression type */
834
   png_write_chunk_start(png_ptr, (png_bytep)png_iCCP,
835 836 837 838
          (png_uint_32)(name_len + profile_len + 2));
   new_name[name_len + 1] = 0x00;
   png_write_chunk_data(png_ptr, (png_bytep)new_name,
     (png_size_t)(name_len + 2));
839 840 841 842 843 844 845 846 847 848

   if (profile_len)
      png_write_compressed_data_out(png_ptr, &comp);

   png_write_chunk_end(png_ptr);
   png_free(png_ptr, new_name);
}
#endif

#if defined(PNG_WRITE_sPLT_SUPPORTED)
849
/* Write a sPLT chunk */
850
void /* PRIVATE */
851
png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
852 853 854 855 856 857 858
{
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_sPLT;
#endif
   png_size_t name_len;
   png_charp new_name;
   png_byte entrybuf[10];
859 860
   png_size_t entry_size = (spalette->depth == 8 ? 6 : 10);
   png_size_t palette_size = entry_size * spalette->nentries;
861
   png_sPLT_entryp ep;
862 863 864
#ifdef PNG_NO_POINTER_INDEXING
   int i;
#endif
865

866
   png_debug(1, "in png_write_sPLT");
867 868
   if ((name_len = png_check_keyword(png_ptr,spalette->name, &new_name))==0)
      return;
869

870
   /* Make sure we include the NULL after the name */
871
   png_write_chunk_start(png_ptr, (png_bytep)png_sPLT,
872 873 874 875
     (png_uint_32)(name_len + 2 + palette_size));
   png_write_chunk_data(png_ptr, (png_bytep)new_name,
     (png_size_t)(name_len + 1));
   png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, (png_size_t)1);
876

877
   /* Loop through each palette entry, writing appropriately */
878
#ifndef PNG_NO_POINTER_INDEXING
879
   for (ep = spalette->entries; ep<spalette->entries + spalette->nentries; ep++)
880
   {
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
      if (spalette->depth == 8)
      {
          entrybuf[0] = (png_byte)ep->red;
          entrybuf[1] = (png_byte)ep->green;
          entrybuf[2] = (png_byte)ep->blue;
          entrybuf[3] = (png_byte)ep->alpha;
          png_save_uint_16(entrybuf + 4, ep->frequency);
      }
      else
      {
          png_save_uint_16(entrybuf + 0, ep->red);
          png_save_uint_16(entrybuf + 2, ep->green);
          png_save_uint_16(entrybuf + 4, ep->blue);
          png_save_uint_16(entrybuf + 6, ep->alpha);
          png_save_uint_16(entrybuf + 8, ep->frequency);
      }
897
      png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
898
   }
899 900 901 902
#else
   ep=spalette->entries;
   for (i=0; i>spalette->nentries; i++)
   {
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
      if (spalette->depth == 8)
      {
          entrybuf[0] = (png_byte)ep[i].red;
          entrybuf[1] = (png_byte)ep[i].green;
          entrybuf[2] = (png_byte)ep[i].blue;
          entrybuf[3] = (png_byte)ep[i].alpha;
          png_save_uint_16(entrybuf + 4, ep[i].frequency);
      }
      else
      {
          png_save_uint_16(entrybuf + 0, ep[i].red);
          png_save_uint_16(entrybuf + 2, ep[i].green);
          png_save_uint_16(entrybuf + 4, ep[i].blue);
          png_save_uint_16(entrybuf + 6, ep[i].alpha);
          png_save_uint_16(entrybuf + 8, ep[i].frequency);
      }
919
      png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
920 921
   }
#endif
922 923 924 925 926 927

   png_write_chunk_end(png_ptr);
   png_free(png_ptr, new_name);
}
#endif

G
Guy Schalnat 已提交
928
#if defined(PNG_WRITE_sBIT_SUPPORTED)
929
/* Write the sBIT chunk */
930
void /* PRIVATE */
G
Guy Schalnat 已提交
931
png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
G
Guy Schalnat 已提交
932
{
933 934 935
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_sBIT;
#endif
G
Guy Schalnat 已提交
936
   png_byte buf[4];
A
Andreas Dilger 已提交
937
   png_size_t size;
G
Guy Schalnat 已提交
938

939
   png_debug(1, "in png_write_sBIT");
940
   /* Make sure we don't depend upon the order of PNG_COLOR_8 */
G
Guy Schalnat 已提交
941 942
   if (color_type & PNG_COLOR_MASK_COLOR)
   {
943
      png_byte maxbits;
G
Guy Schalnat 已提交
944

945 946
      maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
                png_ptr->usr_bit_depth);
947 948
      if (sbit->red == 0 || sbit->red > maxbits ||
          sbit->green == 0 || sbit->green > maxbits ||
G
Guy Schalnat 已提交
949 950 951 952 953
          sbit->blue == 0 || sbit->blue > maxbits)
      {
         png_warning(png_ptr, "Invalid sBIT depth specified");
         return;
      }
G
Guy Schalnat 已提交
954 955 956 957 958 959 960
      buf[0] = sbit->red;
      buf[1] = sbit->green;
      buf[2] = sbit->blue;
      size = 3;
   }
   else
   {
G
Guy Schalnat 已提交
961 962 963 964 965
      if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
      {
         png_warning(png_ptr, "Invalid sBIT depth specified");
         return;
      }
G
Guy Schalnat 已提交
966 967 968 969 970 971
      buf[0] = sbit->gray;
      size = 1;
   }

   if (color_type & PNG_COLOR_MASK_ALPHA)
   {
G
Guy Schalnat 已提交
972 973 974 975 976
      if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
      {
         png_warning(png_ptr, "Invalid sBIT depth specified");
         return;
      }
G
Guy Schalnat 已提交
977 978 979
      buf[size++] = sbit->alpha;
   }

980
   png_write_chunk(png_ptr, (png_bytep)png_sBIT, buf, size);
G
Guy Schalnat 已提交
981
}
G
Guy Schalnat 已提交
982
#endif
G
Guy Schalnat 已提交
983

G
Guy Schalnat 已提交
984
#if defined(PNG_WRITE_cHRM_SUPPORTED)
985
/* Write the cHRM chunk */
986
#ifdef PNG_FLOATING_POINT_SUPPORTED
987
void /* PRIVATE */
A
Andreas Dilger 已提交
988
png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
G
Guy Schalnat 已提交
989 990
   double red_x, double red_y, double green_x, double green_y,
   double blue_x, double blue_y)
G
Guy Schalnat 已提交
991
{
992 993 994
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_cHRM;
#endif
G
Guy Schalnat 已提交
995
   png_byte buf[32];
996 997 998

   png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y,
      int_green_x, int_green_y, int_blue_x, int_blue_y;
G
Guy Schalnat 已提交
999

1000
   png_debug(1, "in png_write_cHRM");
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010

   int_white_x = (png_uint_32)(white_x * 100000.0 + 0.5);
   int_white_y = (png_uint_32)(white_y * 100000.0 + 0.5);
   int_red_x   = (png_uint_32)(red_x   * 100000.0 + 0.5);
   int_red_y   = (png_uint_32)(red_y   * 100000.0 + 0.5);
   int_green_x = (png_uint_32)(green_x * 100000.0 + 0.5);
   int_green_y = (png_uint_32)(green_y * 100000.0 + 0.5);
   int_blue_x  = (png_uint_32)(blue_x  * 100000.0 + 0.5);
   int_blue_y  = (png_uint_32)(blue_y  * 100000.0 + 0.5);

1011
#if !defined(PNG_NO_CHECK_cHRM)
1012 1013
   if (png_check_cHRM_fixed(png_ptr, int_white_x, int_white_y,
      int_red_x, int_red_y, int_green_x, int_green_y, int_blue_x, int_blue_y))
1014
#endif
G
Guy Schalnat 已提交
1015
   {
1016
      /* Each value is saved in 1/100,000ths */
1017 1018 1019
    
      png_save_uint_32(buf, int_white_x);
      png_save_uint_32(buf + 4, int_white_y);
1020

1021 1022
      png_save_uint_32(buf + 8, int_red_x);
      png_save_uint_32(buf + 12, int_red_y);
1023

1024 1025
      png_save_uint_32(buf + 16, int_green_x);
      png_save_uint_32(buf + 20, int_green_y);
1026

1027 1028
      png_save_uint_32(buf + 24, int_blue_x);
      png_save_uint_32(buf + 28, int_blue_y);
1029

1030
      png_write_chunk(png_ptr, (png_bytep)png_cHRM, buf, (png_size_t)32);
1031
   }
G
Guy Schalnat 已提交
1032
}
G
Guy Schalnat 已提交
1033
#endif
1034
#ifdef PNG_FIXED_POINT_SUPPORTED
1035
void /* PRIVATE */
1036 1037 1038 1039
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)
1040 1041 1042 1043 1044 1045
{
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_cHRM;
#endif
   png_byte buf[32];

1046
   png_debug(1, "in png_write_cHRM");
1047
   /* Each value is saved in 1/100,000ths */
1048
#if !defined(PNG_NO_CHECK_cHRM)
1049 1050
   if (png_check_cHRM_fixed(png_ptr, white_x, white_y, red_x, red_y,
      green_x, green_y, blue_x, blue_y))
1051
#endif
1052
   {
1053 1054
      png_save_uint_32(buf, (png_uint_32)white_x);
      png_save_uint_32(buf + 4, (png_uint_32)white_y);
1055

1056 1057
      png_save_uint_32(buf + 8, (png_uint_32)red_x);
      png_save_uint_32(buf + 12, (png_uint_32)red_y);
1058

1059 1060
      png_save_uint_32(buf + 16, (png_uint_32)green_x);
      png_save_uint_32(buf + 20, (png_uint_32)green_y);
1061

1062 1063
      png_save_uint_32(buf + 24, (png_uint_32)blue_x);
      png_save_uint_32(buf + 28, (png_uint_32)blue_y);
1064

1065
      png_write_chunk(png_ptr, (png_bytep)png_cHRM, buf, (png_size_t)32);
1066
   }
1067 1068 1069
}
#endif
#endif
G
Guy Schalnat 已提交
1070

G
Guy Schalnat 已提交
1071
#if defined(PNG_WRITE_tRNS_SUPPORTED)
1072
/* Write the tRNS chunk */
1073
void /* PRIVATE */
G
Guy Schalnat 已提交
1074
png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
G
Guy Schalnat 已提交
1075 1076
   int num_trans, int color_type)
{
1077 1078 1079
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_tRNS;
#endif
G
Guy Schalnat 已提交
1080 1081
   png_byte buf[6];

1082
   png_debug(1, "in png_write_tRNS");
G
Guy Schalnat 已提交
1083 1084
   if (color_type == PNG_COLOR_TYPE_PALETTE)
   {
1085
      if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
G
Guy Schalnat 已提交
1086
      {
1087
         png_warning(png_ptr, "Invalid number of transparent colors specified");
G
Guy Schalnat 已提交
1088 1089
         return;
      }
1090
      /* Write the chunk out as it is */
1091 1092
      png_write_chunk(png_ptr, (png_bytep)png_tRNS, trans,
        (png_size_t)num_trans);
G
Guy Schalnat 已提交
1093 1094 1095
   }
   else if (color_type == PNG_COLOR_TYPE_GRAY)
   {
1096
      /* One 16 bit value */
1097
      if (tran->gray >= (1 << png_ptr->bit_depth))
1098 1099 1100 1101 1102
      {
         png_warning(png_ptr,
           "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
         return;
      }
G
Guy Schalnat 已提交
1103
      png_save_uint_16(buf, tran->gray);
1104
      png_write_chunk(png_ptr, (png_bytep)png_tRNS, buf, (png_size_t)2);
G
Guy Schalnat 已提交
1105 1106 1107
   }
   else if (color_type == PNG_COLOR_TYPE_RGB)
   {
1108
      /* Three 16 bit values */
G
Guy Schalnat 已提交
1109 1110 1111
      png_save_uint_16(buf, tran->red);
      png_save_uint_16(buf + 2, tran->green);
      png_save_uint_16(buf + 4, tran->blue);
1112
      if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
1113 1114
      {
         png_warning(png_ptr,
1115
           "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
1116 1117
         return;
      }
1118
      png_write_chunk(png_ptr, (png_bytep)png_tRNS, buf, (png_size_t)6);
G
Guy Schalnat 已提交
1119
   }
G
Guy Schalnat 已提交
1120 1121
   else
   {
1122
      png_warning(png_ptr, "Can't write tRNS with an alpha channel");
G
Guy Schalnat 已提交
1123
   }
G
Guy Schalnat 已提交
1124
}
G
Guy Schalnat 已提交
1125
#endif
G
Guy Schalnat 已提交
1126

G
Guy Schalnat 已提交
1127
#if defined(PNG_WRITE_bKGD_SUPPORTED)
1128
/* Write the background chunk */
1129
void /* PRIVATE */
G
Guy Schalnat 已提交
1130
png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
G
Guy Schalnat 已提交
1131
{
1132 1133 1134
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_bKGD;
#endif
G
Guy Schalnat 已提交
1135 1136
   png_byte buf[6];

1137
   png_debug(1, "in png_write_bKGD");
G
Guy Schalnat 已提交
1138 1139
   if (color_type == PNG_COLOR_TYPE_PALETTE)
   {
1140
      if (
1141
#if defined(PNG_MNG_FEATURES_SUPPORTED)
1142 1143
          (png_ptr->num_palette ||
          (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
1144
#endif
1145
         back->index >= png_ptr->num_palette)
G
Guy Schalnat 已提交
1146 1147 1148 1149
      {
         png_warning(png_ptr, "Invalid background palette index");
         return;
      }
G
Guy Schalnat 已提交
1150
      buf[0] = back->index;
1151
      png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)1);
G
Guy Schalnat 已提交
1152 1153 1154 1155 1156 1157
   }
   else if (color_type & PNG_COLOR_MASK_COLOR)
   {
      png_save_uint_16(buf, back->red);
      png_save_uint_16(buf + 2, back->green);
      png_save_uint_16(buf + 4, back->blue);
1158
      if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
1159 1160 1161 1162 1163
      {
         png_warning(png_ptr,
           "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
         return;
      }
1164
      png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)6);
G
Guy Schalnat 已提交
1165 1166
   }
   else
G
Guy Schalnat 已提交
1167
   {
1168
      if (back->gray >= (1 << png_ptr->bit_depth))
1169 1170 1171 1172 1173
      {
         png_warning(png_ptr,
           "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
         return;
      }
G
Guy Schalnat 已提交
1174
      png_save_uint_16(buf, back->gray);
1175
      png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)2);
G
Guy Schalnat 已提交
1176 1177
   }
}
G
Guy Schalnat 已提交
1178
#endif
G
Guy Schalnat 已提交
1179

G
Guy Schalnat 已提交
1180
#if defined(PNG_WRITE_hIST_SUPPORTED)
1181
/* Write the histogram */
1182
void /* PRIVATE */
1183
png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
G
Guy Schalnat 已提交
1184
{
1185 1186 1187
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_hIST;
#endif
1188
   int i;
G
Guy Schalnat 已提交
1189 1190
   png_byte buf[3];

1191
   png_debug(1, "in png_write_hIST");
1192
   if (num_hist > (int)png_ptr->num_palette)
G
Guy Schalnat 已提交
1193
   {
1194
      png_debug2(3, "num_hist = %d, num_palette = %d", num_hist,
A
Andreas Dilger 已提交
1195
         png_ptr->num_palette);
G
Guy Schalnat 已提交
1196 1197 1198 1199
      png_warning(png_ptr, "Invalid number of histogram entries specified");
      return;
   }

1200
   png_write_chunk_start(png_ptr, (png_bytep)png_hIST,
1201
     (png_uint_32)(num_hist * 2));
A
Andreas Dilger 已提交
1202
   for (i = 0; i < num_hist; i++)
G
Guy Schalnat 已提交
1203
   {
G
Guy Schalnat 已提交
1204
      png_save_uint_16(buf, hist[i]);
1205
      png_write_chunk_data(png_ptr, buf, (png_size_t)2);
G
Guy Schalnat 已提交
1206 1207 1208
   }
   png_write_chunk_end(png_ptr);
}
G
Guy Schalnat 已提交
1209
#endif
G
Guy Schalnat 已提交
1210

1211 1212
#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
    defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
A
Andreas Dilger 已提交
1213 1214 1215 1216 1217
/* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
 * and if invalid, correct the keyword rather than discarding the entire
 * chunk.  The PNG 1.0 specification requires keywords 1-79 characters in
 * length, forbids leading or trailing whitespace, multiple internal spaces,
 * and the non-break space (0x80) from ISO 8859-1.  Returns keyword length.
A
Andreas Dilger 已提交
1218 1219 1220 1221
 *
 * The new_key is allocated to hold the corrected keyword and must be freed
 * by the calling routine.  This avoids problems with trying to write to
 * static keywords without having to have duplicate copies of the strings.
A
Andreas Dilger 已提交
1222
 */
1223
png_size_t /* PRIVATE */
1224
png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
A
Andreas Dilger 已提交
1225
{
A
Andreas Dilger 已提交
1226
   png_size_t key_len;
1227
   png_charp kp, dp;
A
Andreas Dilger 已提交
1228
   int kflag;
1229
   int kwarn=0;
A
Andreas Dilger 已提交
1230

1231
   png_debug(1, "in png_check_keyword");
A
Andreas Dilger 已提交
1232 1233 1234
   *new_key = NULL;

   if (key == NULL || (key_len = png_strlen(key)) == 0)
A
Andreas Dilger 已提交
1235
   {
1236
      png_warning(png_ptr, "zero length keyword");
1237
      return ((png_size_t)0);
A
Andreas Dilger 已提交
1238
   }
A
Andreas Dilger 已提交
1239

1240
   png_debug1(2, "Keyword to be checked is '%s'", key);
A
Andreas Dilger 已提交
1241

1242
   *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
1243 1244 1245
   if (*new_key == NULL)
   {
      png_warning(png_ptr, "Out of memory while procesing keyword");
1246
      return ((png_size_t)0);
1247
   }
1248

A
Andreas Dilger 已提交
1249 1250
   /* Replace non-printing characters with a blank and print a warning */
   for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
A
Andreas Dilger 已提交
1251
   {
1252 1253
      if ((png_byte)*kp < 0x20 ||
         ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
A
Andreas Dilger 已提交
1254
      {
1255
#if !defined(PNG_NO_STDIO)
A
Andreas Dilger 已提交
1256
         char msg[40];
A
Andreas Dilger 已提交
1257

1258 1259
         png_snprintf(msg, 40,
           "invalid keyword character 0x%02X", (png_byte)*kp);
1260
         png_warning(png_ptr, msg);
1261
#else
1262
         png_warning(png_ptr, "invalid character in keyword");
1263
#endif
A
Andreas Dilger 已提交
1264 1265 1266 1267 1268 1269
         *dp = ' ';
      }
      else
      {
         *dp = *kp;
      }
A
Andreas Dilger 已提交
1270
   }
A
Andreas Dilger 已提交
1271
   *dp = '\0';
A
Andreas Dilger 已提交
1272

A
Andreas Dilger 已提交
1273 1274 1275
   /* Remove any trailing white space. */
   kp = *new_key + key_len - 1;
   if (*kp == ' ')
A
Andreas Dilger 已提交
1276
   {
1277
      png_warning(png_ptr, "trailing spaces removed from keyword");
A
Andreas Dilger 已提交
1278 1279 1280

      while (*kp == ' ')
      {
1281 1282
         *(kp--) = '\0';
         key_len--;
A
Andreas Dilger 已提交
1283
      }
A
Andreas Dilger 已提交
1284 1285 1286
   }

   /* Remove any leading white space. */
A
Andreas Dilger 已提交
1287 1288
   kp = *new_key;
   if (*kp == ' ')
A
Andreas Dilger 已提交
1289
   {
1290
      png_warning(png_ptr, "leading spaces removed from keyword");
A
Andreas Dilger 已提交
1291 1292 1293

      while (*kp == ' ')
      {
1294 1295
         kp++;
         key_len--;
A
Andreas Dilger 已提交
1296
      }
A
Andreas Dilger 已提交
1297 1298
   }

1299
   png_debug1(2, "Checking for multiple internal spaces in '%s'", kp);
A
Andreas Dilger 已提交
1300 1301 1302

   /* Remove multiple internal spaces. */
   for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
A
Andreas Dilger 已提交
1303
   {
A
Andreas Dilger 已提交
1304
      if (*kp == ' ' && kflag == 0)
A
Andreas Dilger 已提交
1305
      {
A
Andreas Dilger 已提交
1306 1307
         *(dp++) = *kp;
         kflag = 1;
A
Andreas Dilger 已提交
1308
      }
A
Andreas Dilger 已提交
1309
      else if (*kp == ' ')
A
Andreas Dilger 已提交
1310 1311
      {
         key_len--;
1312
         kwarn=1;
A
Andreas Dilger 已提交
1313 1314 1315
      }
      else
      {
A
Andreas Dilger 已提交
1316 1317
         *(dp++) = *kp;
         kflag = 0;
A
Andreas Dilger 已提交
1318 1319
      }
   }
A
Andreas Dilger 已提交
1320
   *dp = '\0';
1321
   if (kwarn)
1322
      png_warning(png_ptr, "extra interior spaces removed from keyword");
A
Andreas Dilger 已提交
1323 1324

   if (key_len == 0)
A
Andreas Dilger 已提交
1325
   {
1326
      png_free(png_ptr, *new_key);
1327
      png_warning(png_ptr, "Zero length keyword");
A
Andreas Dilger 已提交
1328 1329 1330 1331
   }

   if (key_len > 79)
   {
1332
      png_warning(png_ptr, "keyword length must be 1 - 79 characters");
1333
      (*new_key)[79] = '\0';
A
Andreas Dilger 已提交
1334 1335
      key_len = 79;
   }
A
Andreas Dilger 已提交
1336

1337
   return (key_len);
A
Andreas Dilger 已提交
1338 1339 1340
}
#endif

G
Guy Schalnat 已提交
1341
#if defined(PNG_WRITE_tEXt_SUPPORTED)
1342
/* Write a tEXt chunk */
1343
void /* PRIVATE */
G
Guy Schalnat 已提交
1344
png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
A
Andreas Dilger 已提交
1345
   png_size_t text_len)
G
Guy Schalnat 已提交
1346
{
1347 1348 1349
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_tEXt;
#endif
A
Andreas Dilger 已提交
1350
   png_size_t key_len;
1351
   png_charp new_key;
A
Andreas Dilger 已提交
1352

1353
   png_debug(1, "in png_write_tEXt");
1354
   if ((key_len = png_check_keyword(png_ptr, key, &new_key))==0)
G
Guy Schalnat 已提交
1355 1356
      return;

A
Andreas Dilger 已提交
1357
   if (text == NULL || *text == '\0')
A
Andreas Dilger 已提交
1358
      text_len = 0;
1359 1360
   else
      text_len = png_strlen(text);
A
Andreas Dilger 已提交
1361

1362
   /* Make sure we include the 0 after the key */
1363
   png_write_chunk_start(png_ptr, (png_bytep)png_tEXt,
1364
      (png_uint_32)(key_len + text_len + 1));
1365 1366 1367 1368
   /*
    * We leave it to the application to meet PNG-1.0 requirements on the
    * contents of the text.  PNG-1.0 through PNG-1.2 discourage the use of
    * any non-Latin-1 characters except for NEWLINE.  ISO PNG will forbid them.
1369
    * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
1370
    */
1371 1372
   png_write_chunk_data(png_ptr, (png_bytep)new_key,
     (png_size_t)(key_len + 1));
A
Andreas Dilger 已提交
1373
   if (text_len)
1374
      png_write_chunk_data(png_ptr, (png_bytep)text, (png_size_t)text_len);
A
Andreas Dilger 已提交
1375

G
Guy Schalnat 已提交
1376
   png_write_chunk_end(png_ptr);
A
Andreas Dilger 已提交
1377
   png_free(png_ptr, new_key);
G
Guy Schalnat 已提交
1378
}
G
Guy Schalnat 已提交
1379
#endif
G
Guy Schalnat 已提交
1380

G
Guy Schalnat 已提交
1381
#if defined(PNG_WRITE_zTXt_SUPPORTED)
1382
/* Write a compressed text chunk */
1383
void /* PRIVATE */
G
Guy Schalnat 已提交
1384
png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
A
Andreas Dilger 已提交
1385
   png_size_t text_len, int compression)
G
Guy Schalnat 已提交
1386
{
1387 1388 1389
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_zTXt;
#endif
A
Andreas Dilger 已提交
1390
   png_size_t key_len;
G
Guy Schalnat 已提交
1391
   char buf[1];
1392
   png_charp new_key;
1393
   compression_state comp;
G
Guy Schalnat 已提交
1394

1395
   png_debug(1, "in png_write_zTXt");
A
Andreas Dilger 已提交
1396

1397 1398 1399 1400 1401 1402
   comp.num_output_ptr = 0;
   comp.max_output_ptr = 0;
   comp.output_ptr = NULL;
   comp.input = NULL;
   comp.input_len = 0;

1403
   if ((key_len = png_check_keyword(png_ptr, key, &new_key))==0)
A
Andreas Dilger 已提交
1404
   {
1405
      png_free(png_ptr, new_key);
G
Guy Schalnat 已提交
1406
      return;
A
Andreas Dilger 已提交
1407
   }
A
Andreas Dilger 已提交
1408

A
Andreas Dilger 已提交
1409 1410
   if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
   {
1411
      png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
A
Andreas Dilger 已提交
1412 1413 1414 1415
      png_free(png_ptr, new_key);
      return;
   }

1416 1417
   text_len = png_strlen(text);

1418
   /* Compute the compressed data; do it now for the length */
1419 1420
   text_len = png_text_compress(png_ptr, text, text_len, compression,
       &comp);
G
Guy Schalnat 已提交
1421

1422
   /* Write start of chunk */
1423 1424
   png_write_chunk_start(png_ptr, (png_bytep)png_zTXt,
     (png_uint_32)(key_len+text_len + 2));
1425
   /* Write key */
1426 1427 1428 1429
   png_write_chunk_data(png_ptr, (png_bytep)new_key,
     (png_size_t)(key_len + 1));
   png_free(png_ptr, new_key);

1430
   buf[0] = (png_byte)compression;
1431
   /* Write compression */
1432
   png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
1433
   /* Write the compressed data */
1434
   png_write_compressed_data_out(png_ptr, &comp);
G
Guy Schalnat 已提交
1435

1436
   /* Close the chunk */
1437 1438 1439
   png_write_chunk_end(png_ptr);
}
#endif
G
Guy Schalnat 已提交
1440

1441
#if defined(PNG_WRITE_iTXt_SUPPORTED)
1442
/* Write an iTXt chunk */
1443
void /* PRIVATE */
1444
png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
1445
    png_charp lang, png_charp lang_key, png_charp text)
1446 1447 1448 1449
{
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_iTXt;
#endif
1450
   png_size_t lang_len, key_len, lang_key_len, text_len;
1451 1452
   png_charp new_lang;
   png_charp new_key = NULL;
1453 1454
   png_byte cbuf[2];
   compression_state comp;
G
Guy Schalnat 已提交
1455

1456
   png_debug(1, "in png_write_iTXt");
G
Guy Schalnat 已提交
1457

1458 1459 1460 1461 1462
   comp.num_output_ptr = 0;
   comp.max_output_ptr = 0;
   comp.output_ptr = NULL;
   comp.input = NULL;

1463
   if ((key_len = png_check_keyword(png_ptr, key, &new_key))==0)
1464
      return;
1465 1466

   if ((lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
1467
   {
1468
      png_warning(png_ptr, "Empty language field in iTXt chunk");
1469
      new_lang = NULL;
1470
      lang_len = 0;
1471
   }
G
Guy Schalnat 已提交
1472

1473
   if (lang_key == NULL)
1474
      lang_key_len = 0;
1475
   else
1476
      lang_key_len = png_strlen(lang_key);
1477 1478

   if (text == NULL)
1479
      text_len = 0;
1480
   else
1481
      text_len = png_strlen(text);
G
Guy Schalnat 已提交
1482

1483
   /* Compute the compressed data; do it now for the length */
1484 1485
   text_len = png_text_compress(png_ptr, text, text_len, compression-2,
      &comp);
G
Guy Schalnat 已提交
1486

1487

1488
   /* Make sure we include the compression flag, the compression byte,
1489
    * and the NULs after the key, lang, and lang_key parts */
G
Guy Schalnat 已提交
1490

1491 1492 1493 1494 1495 1496 1497
   png_write_chunk_start(png_ptr, (png_bytep)png_iTXt,
          (png_uint_32)(
        5 /* comp byte, comp flag, terminators for key, lang and lang_key */
        + key_len
        + lang_len
        + lang_key_len
        + text_len));
G
Guy Schalnat 已提交
1498

1499
   /* We leave it to the application to meet PNG-1.0 requirements on the
1500 1501 1502 1503
    * contents of the text.  PNG-1.0 through PNG-1.2 discourage the use of
    * any non-Latin-1 characters except for NEWLINE.  ISO PNG will forbid them.
    * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
    */
1504 1505
   png_write_chunk_data(png_ptr, (png_bytep)new_key,
     (png_size_t)(key_len + 1));
1506

1507
   /* Set the compression flag */
1508 1509 1510 1511 1512
   if (compression == PNG_ITXT_COMPRESSION_NONE || \
       compression == PNG_TEXT_COMPRESSION_NONE)
       cbuf[0] = 0;
   else /* compression == PNG_ITXT_COMPRESSION_zTXt */
       cbuf[0] = 1;
1513
   /* Set the compression method */
1514
   cbuf[1] = 0;
1515
   png_write_chunk_data(png_ptr, cbuf, (png_size_t)2);
1516

1517
   cbuf[0] = 0;
1518 1519 1520 1521
   png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf),
     (png_size_t)(lang_len + 1));
   png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf),
     (png_size_t)(lang_key_len + 1));
1522
   png_write_compressed_data_out(png_ptr, &comp);
G
Guy Schalnat 已提交
1523 1524

   png_write_chunk_end(png_ptr);
1525
   png_free(png_ptr, new_key);
1526
   png_free(png_ptr, new_lang);
G
Guy Schalnat 已提交
1527
}
G
Guy Schalnat 已提交
1528
#endif
G
Guy Schalnat 已提交
1529

A
Andreas Dilger 已提交
1530
#if defined(PNG_WRITE_oFFs_SUPPORTED)
1531
/* Write the oFFs chunk */
1532
void /* PRIVATE */
1533
png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
G
Guy Schalnat 已提交
1534 1535
   int unit_type)
{
1536 1537 1538
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_oFFs;
#endif
G
Guy Schalnat 已提交
1539 1540
   png_byte buf[9];

1541
   png_debug(1, "in png_write_oFFs");
A
Andreas Dilger 已提交
1542 1543
   if (unit_type >= PNG_OFFSET_LAST)
      png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
G
Guy Schalnat 已提交
1544

1545 1546
   png_save_int_32(buf, x_offset);
   png_save_int_32(buf + 4, y_offset);
G
Guy Schalnat 已提交
1547
   buf[8] = (png_byte)unit_type;
G
Guy Schalnat 已提交
1548

1549
   png_write_chunk(png_ptr, (png_bytep)png_oFFs, buf, (png_size_t)9);
G
Guy Schalnat 已提交
1550
}
G
Guy Schalnat 已提交
1551
#endif
A
Andreas Dilger 已提交
1552
#if defined(PNG_WRITE_pCAL_SUPPORTED)
1553
/* Write the pCAL chunk (described in the PNG extensions document) */
1554
void /* PRIVATE */
A
Andreas Dilger 已提交
1555 1556 1557
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)
{
1558 1559 1560
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_pCAL;
#endif
1561
   png_size_t purpose_len, units_len, total_len;
A
Andreas Dilger 已提交
1562 1563
   png_uint_32p params_len;
   png_byte buf[10];
1564
   png_charp new_purpose;
A
Andreas Dilger 已提交
1565 1566
   int i;

1567
   png_debug1(1, "in png_write_pCAL (%d parameters)", nparams);
A
Andreas Dilger 已提交
1568 1569 1570 1571
   if (type >= PNG_EQUATION_LAST)
      png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");

   purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
1572
   png_debug1(3, "pCAL purpose length = %d", (int)purpose_len);
A
Andreas Dilger 已提交
1573
   units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
1574
   png_debug1(3, "pCAL units length = %d", (int)units_len);
A
Andreas Dilger 已提交
1575 1576
   total_len = purpose_len + units_len + 10;

1577
   params_len = (png_uint_32p)png_malloc(png_ptr,
1578
      (png_alloc_size_t)(nparams * png_sizeof(png_uint_32)));
A
Andreas Dilger 已提交
1579 1580 1581 1582 1583 1584

   /* Find the length of each parameter, making sure we don't count the
      null terminator for the last parameter. */
   for (i = 0; i < nparams; i++)
   {
      params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
1585
      png_debug2(3, "pCAL parameter %d length = %lu", i,
1586
        (unsigned long) params_len[i]);
A
Andreas Dilger 已提交
1587 1588 1589
      total_len += (png_size_t)params_len[i];
   }

1590
   png_debug1(3, "pCAL total length = %d", (int)total_len);
1591
   png_write_chunk_start(png_ptr, (png_bytep)png_pCAL, (png_uint_32)total_len);
1592 1593
   png_write_chunk_data(png_ptr, (png_bytep)new_purpose,
     (png_size_t)purpose_len);
A
Andreas Dilger 已提交
1594 1595 1596 1597
   png_save_int_32(buf, X0);
   png_save_int_32(buf + 4, X1);
   buf[8] = (png_byte)type;
   buf[9] = (png_byte)nparams;
1598 1599
   png_write_chunk_data(png_ptr, buf, (png_size_t)10);
   png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
A
Andreas Dilger 已提交
1600 1601 1602 1603 1604 1605 1606 1607 1608

   png_free(png_ptr, new_purpose);

   for (i = 0; i < nparams; i++)
   {
      png_write_chunk_data(png_ptr, (png_bytep)params[i],
         (png_size_t)params_len[i]);
   }

1609
   png_free(png_ptr, params_len);
A
Andreas Dilger 已提交
1610 1611 1612 1613
   png_write_chunk_end(png_ptr);
}
#endif

1614
#if defined(PNG_WRITE_sCAL_SUPPORTED)
1615
/* Write the sCAL chunk */
1616
#if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
1617
void /* PRIVATE */
1618
png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
1619 1620 1621 1622
{
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_sCAL;
#endif
1623
   char buf[64];
1624
   png_size_t total_len;
1625

1626
   png_debug(1, "in png_write_sCAL");
1627

1628
   buf[0] = (char)unit;
1629
   png_snprintf(buf + 1, 63, "%12.12e", width);
1630
   total_len = 1 + png_strlen(buf + 1) + 1;
1631
   png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
1632
   total_len += png_strlen(buf + total_len);
1633

1634
   png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);
1635
   png_write_chunk(png_ptr, (png_bytep)png_sCAL, (png_bytep)buf, total_len);
1636
}
1637 1638
#else
#ifdef PNG_FIXED_POINT_SUPPORTED
1639
void /* PRIVATE */
1640
png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
1641 1642 1643 1644 1645
   png_charp height)
{
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_sCAL;
#endif
1646 1647
   png_byte buf[64];
   png_size_t wlen, hlen, total_len;
1648

1649
   png_debug(1, "in png_write_sCAL_s");
1650

1651 1652 1653 1654 1655 1656 1657 1658
   wlen = png_strlen(width);
   hlen = png_strlen(height);
   total_len = wlen + hlen + 2;
   if (total_len > 64)
   {
      png_warning(png_ptr, "Can't write sCAL (buffer too small)");
      return;
   }
1659

1660
   buf[0] = (png_byte)unit;
1661 1662
   png_memcpy(buf + 1, width, wlen + 1);      /* Append the '\0' here */
   png_memcpy(buf + wlen + 2, height, hlen);  /* Do NOT append the '\0' here */
1663

1664
   png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);
1665
   png_write_chunk(png_ptr, (png_bytep)png_sCAL, buf, total_len);
1666 1667
}
#endif
1668 1669
#endif
#endif
1670

A
Andreas Dilger 已提交
1671
#if defined(PNG_WRITE_pHYs_SUPPORTED)
1672
/* Write the pHYs chunk */
1673
void /* PRIVATE */
A
Andreas Dilger 已提交
1674 1675
png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
   png_uint_32 y_pixels_per_unit,
G
Guy Schalnat 已提交
1676 1677
   int unit_type)
{
1678 1679 1680
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_pHYs;
#endif
G
Guy Schalnat 已提交
1681 1682
   png_byte buf[9];

1683
   png_debug(1, "in png_write_pHYs");
A
Andreas Dilger 已提交
1684 1685
   if (unit_type >= PNG_RESOLUTION_LAST)
      png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
G
Guy Schalnat 已提交
1686

A
Andreas Dilger 已提交
1687 1688
   png_save_uint_32(buf, x_pixels_per_unit);
   png_save_uint_32(buf + 4, y_pixels_per_unit);
G
Guy Schalnat 已提交
1689
   buf[8] = (png_byte)unit_type;
G
Guy Schalnat 已提交
1690

1691
   png_write_chunk(png_ptr, (png_bytep)png_pHYs, buf, (png_size_t)9);
G
Guy Schalnat 已提交
1692
}
G
Guy Schalnat 已提交
1693
#endif
G
Guy Schalnat 已提交
1694

G
Guy Schalnat 已提交
1695
#if defined(PNG_WRITE_tIME_SUPPORTED)
1696 1697 1698
/* Write the tIME chunk.  Use either png_convert_from_struct_tm()
 * or png_convert_from_time_t(), or fill in the structure yourself.
 */
1699
void /* PRIVATE */
G
Guy Schalnat 已提交
1700
png_write_tIME(png_structp png_ptr, png_timep mod_time)
G
Guy Schalnat 已提交
1701
{
1702 1703 1704
#ifdef PNG_USE_LOCAL_ARRAYS
   PNG_tIME;
#endif
G
Guy Schalnat 已提交
1705 1706
   png_byte buf[7];

1707
   png_debug(1, "in png_write_tIME");
G
Guy Schalnat 已提交
1708 1709 1710 1711 1712 1713 1714 1715
   if (mod_time->month  > 12 || mod_time->month  < 1 ||
       mod_time->day    > 31 || mod_time->day    < 1 ||
       mod_time->hour   > 23 || mod_time->second > 60)
   {
      png_warning(png_ptr, "Invalid time specified for tIME chunk");
      return;
   }

G
Guy Schalnat 已提交
1716 1717 1718 1719 1720 1721 1722
   png_save_uint_16(buf, mod_time->year);
   buf[2] = mod_time->month;
   buf[3] = mod_time->day;
   buf[4] = mod_time->hour;
   buf[5] = mod_time->minute;
   buf[6] = mod_time->second;

1723
   png_write_chunk(png_ptr, (png_bytep)png_tIME, buf, (png_size_t)7);
G
Guy Schalnat 已提交
1724
}
G
Guy Schalnat 已提交
1725
#endif
G
Guy Schalnat 已提交
1726

1727
/* Initializes the row writing capability of libpng */
1728
void /* PRIVATE */
G
Guy Schalnat 已提交
1729
png_write_start_row(png_structp png_ptr)
G
Guy Schalnat 已提交
1730
{
1731
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
1732
#ifdef PNG_USE_LOCAL_ARRAYS
1733
   /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1734

1735
   /* Start of interlace block */
1736
   int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1737

1738
   /* Offset to next interlace block */
1739
   int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1740

1741
   /* Start of interlace block in the y direction */
1742
   int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
1743

1744
   /* Offset to next interlace block in the y direction */
1745
   int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
1746
#endif
1747
#endif
1748

A
Andreas Dilger 已提交
1749 1750
   png_size_t buf_size;

1751
   png_debug(1, "in png_write_start_row");
1752
   buf_size = (png_size_t)(PNG_ROWBYTES(
1753
      png_ptr->usr_channels*png_ptr->usr_bit_depth, png_ptr->width) + 1);
A
Andreas Dilger 已提交
1754

1755
   /* Set up row buffer */
1756
   png_ptr->row_buf = (png_bytep)png_malloc(png_ptr,
1757
     (png_alloc_size_t)buf_size);
A
Andreas Dilger 已提交
1758
   png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
G
Guy Schalnat 已提交
1759

1760
#ifndef PNG_NO_WRITE_FILTER
1761
   /* Set up filtering buffer, if using this filter */
G
Guy Schalnat 已提交
1762
   if (png_ptr->do_filter & PNG_FILTER_SUB)
G
Guy Schalnat 已提交
1763
   {
A
Andreas Dilger 已提交
1764
      png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
1765
         (png_alloc_size_t)(png_ptr->rowbytes + 1));
A
Andreas Dilger 已提交
1766
      png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
G
Guy Schalnat 已提交
1767 1768
   }

A
Andreas Dilger 已提交
1769
   /* We only need to keep the previous row if we are using one of these. */
G
Guy Schalnat 已提交
1770 1771
   if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
   {
1772
     /* Set up previous row buffer */
1773 1774
#ifdef PNG_CALLOC_SUPPORTED
     png_ptr->prev_row = (png_bytep)png_calloc(png_ptr,
1775
        (png_alloc_size_t)buf_size);
1776 1777 1778 1779 1780
#else
     png_ptr->prev_row = (png_bytep)png_malloc(png_ptr,
        (png_uint_32)buf_size);
     png_memset(png_ptr->prev_row, 0, buf_size);
#endif
G
Guy Schalnat 已提交
1781 1782 1783

      if (png_ptr->do_filter & PNG_FILTER_UP)
      {
1784
         png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
1785
           (png_size_t)(png_ptr->rowbytes + 1));
A
Andreas Dilger 已提交
1786
         png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
G
Guy Schalnat 已提交
1787 1788 1789 1790
      }

      if (png_ptr->do_filter & PNG_FILTER_AVG)
      {
1791
         png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
1792
           (png_alloc_size_t)(png_ptr->rowbytes + 1));
A
Andreas Dilger 已提交
1793
         png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
G
Guy Schalnat 已提交
1794 1795 1796 1797
      }

      if (png_ptr->do_filter & PNG_FILTER_PAETH)
      {
1798
         png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
1799
           (png_size_t)(png_ptr->rowbytes + 1));
A
Andreas Dilger 已提交
1800
         png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
G
Guy Schalnat 已提交
1801
      }
G
Guy Schalnat 已提交
1802
   }
1803
#endif /* PNG_NO_WRITE_FILTER */
G
Guy Schalnat 已提交
1804

1805
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
1806
   /* If interlaced, we need to set up width and height of pass */
G
Guy Schalnat 已提交
1807
   if (png_ptr->interlaced)
G
Guy Schalnat 已提交
1808 1809 1810 1811 1812
   {
      if (!(png_ptr->transformations & PNG_INTERLACE))
      {
         png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
            png_pass_ystart[0]) / png_pass_yinc[0];
A
Andreas Dilger 已提交
1813 1814
         png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
            png_pass_start[0]) / png_pass_inc[0];
G
Guy Schalnat 已提交
1815 1816 1817 1818 1819 1820 1821 1822
      }
      else
      {
         png_ptr->num_rows = png_ptr->height;
         png_ptr->usr_width = png_ptr->width;
      }
   }
   else
1823
#endif
G
Guy Schalnat 已提交
1824
   {
G
Guy Schalnat 已提交
1825 1826 1827
      png_ptr->num_rows = png_ptr->height;
      png_ptr->usr_width = png_ptr->width;
   }
A
Andreas Dilger 已提交
1828 1829
   png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
   png_ptr->zstream.next_out = png_ptr->zbuf;
G
Guy Schalnat 已提交
1830 1831
}

A
Andreas Dilger 已提交
1832
/* Internal use only.  Called when finished processing a row of data. */
1833
void /* PRIVATE */
G
Guy Schalnat 已提交
1834
png_write_finish_row(png_structp png_ptr)
G
Guy Schalnat 已提交
1835
{
1836
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
1837
#ifdef PNG_USE_LOCAL_ARRAYS
1838
   /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1839

1840
   /* Start of interlace block */
1841
   int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1842

1843
   /* Offset to next interlace block */
1844
   int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1845

1846
   /* Start of interlace block in the y direction */
1847
   int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
1848

1849
   /* Offset to next interlace block in the y direction */
1850
   int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
1851
#endif
1852
#endif
1853

G
Guy Schalnat 已提交
1854 1855
   int ret;

1856
   png_debug(1, "in png_write_finish_row");
1857
   /* Next row */
G
Guy Schalnat 已提交
1858
   png_ptr->row_number++;
G
Guy Schalnat 已提交
1859

1860
   /* See if we are done */
G
Guy Schalnat 已提交
1861
   if (png_ptr->row_number < png_ptr->num_rows)
G
Guy Schalnat 已提交
1862
      return;
G
Guy Schalnat 已提交
1863

1864
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
1865
   /* If interlaced, go to next pass */
G
Guy Schalnat 已提交
1866 1867 1868 1869 1870 1871 1872 1873 1874
   if (png_ptr->interlaced)
   {
      png_ptr->row_number = 0;
      if (png_ptr->transformations & PNG_INTERLACE)
      {
         png_ptr->pass++;
      }
      else
      {
1875
         /* Loop until we find a non-zero width or height pass */
G
Guy Schalnat 已提交
1876 1877 1878 1879 1880
         do
         {
            png_ptr->pass++;
            if (png_ptr->pass >= 7)
               break;
G
Guy Schalnat 已提交
1881
            png_ptr->usr_width = (png_ptr->width +
G
Guy Schalnat 已提交
1882 1883 1884 1885 1886 1887 1888
               png_pass_inc[png_ptr->pass] - 1 -
               png_pass_start[png_ptr->pass]) /
               png_pass_inc[png_ptr->pass];
            png_ptr->num_rows = (png_ptr->height +
               png_pass_yinc[png_ptr->pass] - 1 -
               png_pass_ystart[png_ptr->pass]) /
               png_pass_yinc[png_ptr->pass];
G
Guy Schalnat 已提交
1889 1890
            if (png_ptr->transformations & PNG_INTERLACE)
               break;
G
Guy Schalnat 已提交
1891 1892 1893 1894
         } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);

      }

1895
      /* Reset the row above the image for the next pass */
G
Guy Schalnat 已提交
1896
      if (png_ptr->pass < 7)
G
Guy Schalnat 已提交
1897
      {
A
Andreas Dilger 已提交
1898
         if (png_ptr->prev_row != NULL)
1899
            png_memset(png_ptr->prev_row, 0,
1900
               (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
1901
               png_ptr->usr_bit_depth, png_ptr->width)) + 1);
G
Guy Schalnat 已提交
1902
         return;
G
Guy Schalnat 已提交
1903
      }
G
Guy Schalnat 已提交
1904
   }
1905
#endif
G
Guy Schalnat 已提交
1906

1907
   /* If we get here, we've just written the last row, so we need
G
Guy Schalnat 已提交
1908 1909 1910
      to flush the compressor */
   do
   {
1911
      /* Tell the compressor we are done */
A
Andreas Dilger 已提交
1912
      ret = deflate(&png_ptr->zstream, Z_FINISH);
1913
      /* Check for an error */
1914 1915
      if (ret == Z_OK)
      {
1916
         /* Check to see if we need more room */
1917 1918 1919 1920 1921 1922 1923 1924
         if (!(png_ptr->zstream.avail_out))
         {
            png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
            png_ptr->zstream.next_out = png_ptr->zbuf;
            png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
         }
      }
      else if (ret != Z_STREAM_END)
G
Guy Schalnat 已提交
1925
      {
A
Andreas Dilger 已提交
1926
         if (png_ptr->zstream.msg != NULL)
A
Andreas Dilger 已提交
1927
            png_error(png_ptr, png_ptr->zstream.msg);
G
Guy Schalnat 已提交
1928
         else
G
Guy Schalnat 已提交
1929
            png_error(png_ptr, "zlib error");
G
Guy Schalnat 已提交
1930 1931 1932
      }
   } while (ret != Z_STREAM_END);

1933
   /* Write any extra space */
A
Andreas Dilger 已提交
1934
   if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
G
Guy Schalnat 已提交
1935 1936
   {
      png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
A
Andreas Dilger 已提交
1937
         png_ptr->zstream.avail_out);
G
Guy Schalnat 已提交
1938 1939
   }

A
Andreas Dilger 已提交
1940
   deflateReset(&png_ptr->zstream);
1941
   png_ptr->zstream.data_type = Z_BINARY;
G
Guy Schalnat 已提交
1942 1943
}

G
Guy Schalnat 已提交
1944
#if defined(PNG_WRITE_INTERLACING_SUPPORTED)
1945 1946 1947 1948 1949 1950 1951
/* Pick out the correct pixels for the interlace pass.
 * The basic idea here is to go through the row with a source
 * pointer and a destination pointer (sp and dp), and copy the
 * correct pixels for the pass.  As the row gets compacted,
 * sp will always be >= dp, so we should never overwrite anything.
 * See the default: case for the easiest code to understand.
 */
1952
void /* PRIVATE */
G
Guy Schalnat 已提交
1953
png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
G
Guy Schalnat 已提交
1954
{
1955
#ifdef PNG_USE_LOCAL_ARRAYS
1956
   /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1957

1958
   /* Start of interlace block */
1959
   int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1960

1961
   /* Offset to next interlace block */
1962
   int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1963
#endif
1964

1965
   png_debug(1, "in png_do_write_interlace");
1966
   /* We don't have to do anything on the last pass (6) */
A
Andreas Dilger 已提交
1967
   if (pass < 6)
G
Guy Schalnat 已提交
1968
   {
1969
      /* Each pixel depth is handled separately */
G
Guy Schalnat 已提交
1970
      switch (row_info->pixel_depth)
G
Guy Schalnat 已提交
1971
      {
G
Guy Schalnat 已提交
1972 1973
         case 1:
         {
G
Guy Schalnat 已提交
1974 1975
            png_bytep sp;
            png_bytep dp;
G
Guy Schalnat 已提交
1976 1977 1978
            int shift;
            int d;
            int value;
1979 1980
            png_uint_32 i;
            png_uint_32 row_width = row_info->width;
G
Guy Schalnat 已提交
1981 1982 1983 1984

            dp = row;
            d = 0;
            shift = 7;
1985
            for (i = png_pass_start[pass]; i < row_width;
G
Guy Schalnat 已提交
1986 1987 1988
               i += png_pass_inc[pass])
            {
               sp = row + (png_size_t)(i >> 3);
1989
               value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
G
Guy Schalnat 已提交
1990 1991 1992 1993 1994
               d |= (value << shift);

               if (shift == 0)
               {
                  shift = 7;
G
Guy Schalnat 已提交
1995
                  *dp++ = (png_byte)d;
G
Guy Schalnat 已提交
1996 1997 1998 1999 2000 2001 2002
                  d = 0;
               }
               else
                  shift--;

            }
            if (shift != 7)
G
Guy Schalnat 已提交
2003
               *dp = (png_byte)d;
G
Guy Schalnat 已提交
2004 2005 2006
            break;
         }
         case 2:
G
Guy Schalnat 已提交
2007
         {
G
Guy Schalnat 已提交
2008 2009
            png_bytep sp;
            png_bytep dp;
G
Guy Schalnat 已提交
2010 2011 2012
            int shift;
            int d;
            int value;
2013 2014
            png_uint_32 i;
            png_uint_32 row_width = row_info->width;
G
Guy Schalnat 已提交
2015 2016 2017 2018

            dp = row;
            shift = 6;
            d = 0;
2019
            for (i = png_pass_start[pass]; i < row_width;
G
Guy Schalnat 已提交
2020 2021 2022
               i += png_pass_inc[pass])
            {
               sp = row + (png_size_t)(i >> 2);
2023
               value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
G
Guy Schalnat 已提交
2024 2025 2026 2027 2028
               d |= (value << shift);

               if (shift == 0)
               {
                  shift = 6;
G
Guy Schalnat 已提交
2029
                  *dp++ = (png_byte)d;
G
Guy Schalnat 已提交
2030 2031 2032 2033 2034 2035
                  d = 0;
               }
               else
                  shift -= 2;
            }
            if (shift != 6)
G
Guy Schalnat 已提交
2036
                   *dp = (png_byte)d;
G
Guy Schalnat 已提交
2037 2038 2039 2040
            break;
         }
         case 4:
         {
G
Guy Schalnat 已提交
2041 2042
            png_bytep sp;
            png_bytep dp;
G
Guy Schalnat 已提交
2043
            int shift;
G
Guy Schalnat 已提交
2044 2045
            int d;
            int value;
2046 2047
            png_uint_32 i;
            png_uint_32 row_width = row_info->width;
G
Guy Schalnat 已提交
2048 2049 2050 2051

            dp = row;
            shift = 4;
            d = 0;
2052
            for (i = png_pass_start[pass]; i < row_width;
G
Guy Schalnat 已提交
2053 2054 2055
               i += png_pass_inc[pass])
            {
               sp = row + (png_size_t)(i >> 1);
2056
               value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
G
Guy Schalnat 已提交
2057 2058 2059 2060
               d |= (value << shift);

               if (shift == 0)
               {
G
Guy Schalnat 已提交
2061 2062
                  shift = 4;
                  *dp++ = (png_byte)d;
G
Guy Schalnat 已提交
2063 2064 2065 2066 2067 2068
                  d = 0;
               }
               else
                  shift -= 4;
            }
            if (shift != 4)
G
Guy Schalnat 已提交
2069
               *dp = (png_byte)d;
G
Guy Schalnat 已提交
2070 2071 2072 2073
            break;
         }
         default:
         {
G
Guy Schalnat 已提交
2074 2075
            png_bytep sp;
            png_bytep dp;
2076 2077
            png_uint_32 i;
            png_uint_32 row_width = row_info->width;
A
Andreas Dilger 已提交
2078
            png_size_t pixel_bytes;
G
Guy Schalnat 已提交
2079

2080
            /* Start at the beginning */
G
Guy Schalnat 已提交
2081
            dp = row;
2082
            /* Find out how many bytes each pixel takes up */
G
Guy Schalnat 已提交
2083
            pixel_bytes = (row_info->pixel_depth >> 3);
2084
            /* Loop through the row, only looking at the pixels that
G
Guy Schalnat 已提交
2085
               matter */
2086
            for (i = png_pass_start[pass]; i < row_width;
G
Guy Schalnat 已提交
2087 2088
               i += png_pass_inc[pass])
            {
2089
               /* Find out where the original pixel is */
2090
               sp = row + (png_size_t)i * pixel_bytes;
2091
               /* Move the pixel */
G
Guy Schalnat 已提交
2092
               if (dp != sp)
G
Guy Schalnat 已提交
2093
                  png_memcpy(dp, sp, pixel_bytes);
2094
               /* Next pixel */
G
Guy Schalnat 已提交
2095 2096
               dp += pixel_bytes;
            }
G
Guy Schalnat 已提交
2097
            break;
G
Guy Schalnat 已提交
2098 2099
         }
      }
2100
      /* Set new row width */
G
Guy Schalnat 已提交
2101 2102 2103 2104
      row_info->width = (row_info->width +
         png_pass_inc[pass] - 1 -
         png_pass_start[pass]) /
         png_pass_inc[pass];
2105 2106
         row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
            row_info->width);
G
Guy Schalnat 已提交
2107 2108
   }
}
G
Guy Schalnat 已提交
2109
#endif
G
Guy Schalnat 已提交
2110

A
Andreas Dilger 已提交
2111 2112
/* This filters the row, chooses which filter to use, if it has not already
 * been specified by the application, and then writes the row out with the
2113 2114
 * chosen filter.
 */
2115
#define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
A
Andreas Dilger 已提交
2116
#define PNG_HISHIFT 10
2117 2118
#define PNG_LOMASK ((png_uint_32)0xffffL)
#define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
2119
void /* PRIVATE */
G
Guy Schalnat 已提交
2120
png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
G
Guy Schalnat 已提交
2121
{
2122 2123 2124
   png_bytep best_row;
#ifndef PNG_NO_WRITE_FILTER
   png_bytep prev_row, row_buf;
A
Andreas Dilger 已提交
2125
   png_uint_32 mins, bpp;
2126
   png_byte filter_to_do = png_ptr->do_filter;
2127 2128 2129 2130
   png_uint_32 row_bytes = row_info->rowbytes;
#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
   int num_p_filters = (int)png_ptr->num_prev_filters;
#endif
G
Guy Schalnat 已提交
2131

2132
   png_debug(1, "in png_write_find_filter");
2133
   /* Find out how many bytes offset each pixel is */
2134
   bpp = (row_info->pixel_depth + 7) >> 3;
G
Guy Schalnat 已提交
2135 2136

   prev_row = png_ptr->prev_row;
2137 2138 2139 2140
#endif
   best_row = png_ptr->row_buf;
#ifndef PNG_NO_WRITE_FILTER
   row_buf = best_row;
A
Andreas Dilger 已提交
2141 2142 2143 2144
   mins = PNG_MAXSUM;

   /* The prediction method we use is to find which method provides the
    * smallest value when summing the absolute values of the distances
2145
    * from zero, using anything >= 128 as negative numbers.  This is known
A
Andreas Dilger 已提交
2146
    * as the "minimum sum of absolute differences" heuristic.  Other
2147
    * heuristics are the "weighted minimum sum of absolute differences"
A
Andreas Dilger 已提交
2148
    * (experimental and can in theory improve compression), and the "zlib
2149 2150 2151
    * predictive" method (not implemented yet), which does test compressions
    * of lines using different filter methods, and then chooses the
    * (series of) filter(s) that give minimum compressed data size (VERY
A
Andreas Dilger 已提交
2152
    * computationally expensive).
2153 2154 2155 2156 2157 2158 2159 2160 2161
    *
    * GRR 980525:  consider also
    *   (1) minimum sum of absolute differences from running average (i.e.,
    *       keep running sum of non-absolute differences & count of bytes)
    *       [track dispersion, too?  restart average if dispersion too large?]
    *  (1b) minimum sum of absolute differences from sliding average, probably
    *       with window size <= deflate window (usually 32K)
    *   (2) minimum sum of squared differences from zero or running average
    *       (i.e., ~ root-mean-square approach)
A
Andreas Dilger 已提交
2162
    */
G
Guy Schalnat 已提交
2163

2164

G
Guy Schalnat 已提交
2165
   /* We don't need to test the 'no filter' case if this is the only filter
A
Andreas Dilger 已提交
2166 2167
    * that has been chosen, as it doesn't actually do anything to the data.
    */
2168
   if ((filter_to_do & PNG_FILTER_NONE) &&
2169
       filter_to_do != PNG_FILTER_NONE)
G
Guy Schalnat 已提交
2170
   {
G
Guy Schalnat 已提交
2171 2172
      png_bytep rp;
      png_uint_32 sum = 0;
2173
      png_uint_32 i;
A
Andreas Dilger 已提交
2174
      int v;
G
Guy Schalnat 已提交
2175

2176
      for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
G
Guy Schalnat 已提交
2177 2178 2179 2180
      {
         v = *rp;
         sum += (v < 128) ? v : 256 - v;
      }
A
Andreas Dilger 已提交
2181 2182 2183 2184 2185

#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
         png_uint_32 sumhi, sumlo;
2186
         int j;
A
Andreas Dilger 已提交
2187 2188 2189 2190
         sumlo = sum & PNG_LOMASK;
         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */

         /* Reduce the sum if we match any of the previous rows */
2191
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2192
         {
2193
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
A
Andreas Dilger 已提交
2194
            {
2195
               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
A
Andreas Dilger 已提交
2196
                  PNG_WEIGHT_SHIFT;
2197
               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
A
Andreas Dilger 已提交
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
                  PNG_WEIGHT_SHIFT;
            }
         }

         /* Factor in the cost of this filter (this is here for completeness,
          * but it makes no sense to have a "cost" for the NONE filter, as
          * it has the minimum possible computational cost - none).
          */
         sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
            PNG_COST_SHIFT;
         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
            PNG_COST_SHIFT;

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
      }
#endif
G
Guy Schalnat 已提交
2217 2218
      mins = sum;
   }
G
Guy Schalnat 已提交
2219

2220
   /* Sub filter */
2221
   if (filter_to_do == PNG_FILTER_SUB)
2222
   /* It's the only filter so no testing is needed */
2223 2224
   {
      png_bytep rp, lp, dp;
2225
      png_uint_32 i;
2226 2227 2228 2229 2230
      for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
           i++, rp++, dp++)
      {
         *dp = *rp;
      }
2231
      for (lp = row_buf + 1; i < row_bytes;
2232 2233 2234 2235 2236 2237 2238 2239
         i++, rp++, lp++, dp++)
      {
         *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
      }
      best_row = png_ptr->sub_row;
   }

   else if (filter_to_do & PNG_FILTER_SUB)
G
Guy Schalnat 已提交
2240 2241
   {
      png_bytep rp, dp, lp;
A
Andreas Dilger 已提交
2242
      png_uint_32 sum = 0, lmins = mins;
2243
      png_uint_32 i;
A
Andreas Dilger 已提交
2244 2245 2246
      int v;

#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
2247
      /* We temporarily increase the "minimum sum" by the factor we
A
Andreas Dilger 已提交
2248 2249 2250 2251 2252
       * would reduce the sum of this filter, so that we can do the
       * early exit comparison without scaling the sum each time.
       */
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2253
         int j;
A
Andreas Dilger 已提交
2254 2255 2256 2257
         png_uint_32 lmhi, lmlo;
         lmlo = lmins & PNG_LOMASK;
         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;

2258
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2259
         {
2260
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
A
Andreas Dilger 已提交
2261
            {
2262
               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
A
Andreas Dilger 已提交
2263
                  PNG_WEIGHT_SHIFT;
2264
               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
A
Andreas Dilger 已提交
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
                  PNG_WEIGHT_SHIFT;
            }
         }

         lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
            PNG_COST_SHIFT;
         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
            PNG_COST_SHIFT;

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
         else
            lmins = (lmhi << PNG_HISHIFT) + lmlo;
      }
#endif
G
Guy Schalnat 已提交
2280

G
Guy Schalnat 已提交
2281 2282 2283 2284
      for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
           i++, rp++, dp++)
      {
         v = *dp = *rp;
G
Guy Schalnat 已提交
2285

G
Guy Schalnat 已提交
2286 2287
         sum += (v < 128) ? v : 256 - v;
      }
2288
      for (lp = row_buf + 1; i < row_bytes;
2289
         i++, rp++, lp++, dp++)
G
Guy Schalnat 已提交
2290 2291 2292 2293
      {
         v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);

         sum += (v < 128) ? v : 256 - v;
A
Andreas Dilger 已提交
2294 2295 2296 2297 2298 2299 2300 2301

         if (sum > lmins)  /* We are already worse, don't continue. */
            break;
      }

#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2302
         int j;
A
Andreas Dilger 已提交
2303 2304 2305 2306
         png_uint_32 sumhi, sumlo;
         sumlo = sum & PNG_LOMASK;
         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;

2307
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2308
         {
2309
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
A
Andreas Dilger 已提交
2310
            {
2311
               sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
A
Andreas Dilger 已提交
2312
                  PNG_WEIGHT_SHIFT;
2313
               sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
A
Andreas Dilger 已提交
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326
                  PNG_WEIGHT_SHIFT;
            }
         }

         sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
            PNG_COST_SHIFT;
         sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
            PNG_COST_SHIFT;

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
G
Guy Schalnat 已提交
2327
      }
A
Andreas Dilger 已提交
2328 2329
#endif

G
Guy Schalnat 已提交
2330 2331 2332 2333 2334
      if (sum < mins)
      {
         mins = sum;
         best_row = png_ptr->sub_row;
      }
G
Guy Schalnat 已提交
2335 2336
   }

2337
   /* Up filter */
2338 2339 2340
   if (filter_to_do == PNG_FILTER_UP)
   {
      png_bytep rp, dp, pp;
2341
      png_uint_32 i;
2342 2343

      for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
2344
           pp = prev_row + 1; i < row_bytes;
2345 2346 2347 2348 2349 2350 2351 2352
           i++, rp++, pp++, dp++)
      {
         *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
      }
      best_row = png_ptr->up_row;
   }

   else if (filter_to_do & PNG_FILTER_UP)
G
Guy Schalnat 已提交
2353 2354
   {
      png_bytep rp, dp, pp;
A
Andreas Dilger 已提交
2355
      png_uint_32 sum = 0, lmins = mins;
2356
      png_uint_32 i;
A
Andreas Dilger 已提交
2357 2358
      int v;

2359

A
Andreas Dilger 已提交
2360 2361 2362
#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2363
         int j;
A
Andreas Dilger 已提交
2364 2365 2366 2367
         png_uint_32 lmhi, lmlo;
         lmlo = lmins & PNG_LOMASK;
         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;

2368
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2369
         {
2370
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
A
Andreas Dilger 已提交
2371
            {
2372
               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
A
Andreas Dilger 已提交
2373
                  PNG_WEIGHT_SHIFT;
2374
               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
A
Andreas Dilger 已提交
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
                  PNG_WEIGHT_SHIFT;
            }
         }

         lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
            PNG_COST_SHIFT;
         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
            PNG_COST_SHIFT;

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
         else
            lmins = (lmhi << PNG_HISHIFT) + lmlo;
      }
#endif
G
Guy Schalnat 已提交
2390

G
Guy Schalnat 已提交
2391
      for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
2392
           pp = prev_row + 1; i < row_bytes; i++)
G
Guy Schalnat 已提交
2393
      {
2394
         v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
G
Guy Schalnat 已提交
2395 2396

         sum += (v < 128) ? v : 256 - v;
A
Andreas Dilger 已提交
2397 2398 2399

         if (sum > lmins)  /* We are already worse, don't continue. */
            break;
G
Guy Schalnat 已提交
2400
      }
A
Andreas Dilger 已提交
2401 2402 2403 2404

#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2405
         int j;
A
Andreas Dilger 已提交
2406 2407 2408 2409
         png_uint_32 sumhi, sumlo;
         sumlo = sum & PNG_LOMASK;
         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;

2410
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2411
         {
2412
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
A
Andreas Dilger 已提交
2413
            {
2414
               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
A
Andreas Dilger 已提交
2415
                  PNG_WEIGHT_SHIFT;
2416
               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
A
Andreas Dilger 已提交
2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
                  PNG_WEIGHT_SHIFT;
            }
         }

         sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
            PNG_COST_SHIFT;
         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
            PNG_COST_SHIFT;

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
      }
#endif

G
Guy Schalnat 已提交
2433 2434 2435 2436 2437 2438 2439
      if (sum < mins)
      {
         mins = sum;
         best_row = png_ptr->up_row;
      }
   }

2440
   /* Avg filter */
2441 2442 2443
   if (filter_to_do == PNG_FILTER_AVG)
   {
      png_bytep rp, dp, pp, lp;
2444
      png_uint_32 i;
2445
      for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
2446
           pp = prev_row + 1; i < bpp; i++)
2447
      {
2448
         *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
2449
      }
2450
      for (lp = row_buf + 1; i < row_bytes; i++)
2451
      {
2452 2453
         *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
                 & 0xff);
2454 2455 2456 2457 2458
      }
      best_row = png_ptr->avg_row;
   }

   else if (filter_to_do & PNG_FILTER_AVG)
G
Guy Schalnat 已提交
2459
   {
G
Guy Schalnat 已提交
2460
      png_bytep rp, dp, pp, lp;
A
Andreas Dilger 已提交
2461
      png_uint_32 sum = 0, lmins = mins;
2462
      png_uint_32 i;
A
Andreas Dilger 已提交
2463 2464 2465 2466 2467
      int v;

#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2468
         int j;
A
Andreas Dilger 已提交
2469 2470 2471 2472
         png_uint_32 lmhi, lmlo;
         lmlo = lmins & PNG_LOMASK;
         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;

2473
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2474
         {
2475
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
A
Andreas Dilger 已提交
2476
            {
2477
               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
A
Andreas Dilger 已提交
2478
                  PNG_WEIGHT_SHIFT;
2479
               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
A
Andreas Dilger 已提交
2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
                  PNG_WEIGHT_SHIFT;
            }
         }

         lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
            PNG_COST_SHIFT;
         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
            PNG_COST_SHIFT;

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
         else
            lmins = (lmhi << PNG_HISHIFT) + lmlo;
      }
#endif
G
Guy Schalnat 已提交
2495

G
Guy Schalnat 已提交
2496
      for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
2497
           pp = prev_row + 1; i < bpp; i++)
G
Guy Schalnat 已提交
2498
      {
2499
         v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
G
Guy Schalnat 已提交
2500

G
Guy Schalnat 已提交
2501 2502
         sum += (v < 128) ? v : 256 - v;
      }
2503
      for (lp = row_buf + 1; i < row_bytes; i++)
G
Guy Schalnat 已提交
2504
      {
2505
         v = *dp++ =
2506
          (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
G
Guy Schalnat 已提交
2507

G
Guy Schalnat 已提交
2508
         sum += (v < 128) ? v : 256 - v;
A
Andreas Dilger 已提交
2509 2510 2511

         if (sum > lmins)  /* We are already worse, don't continue. */
            break;
G
Guy Schalnat 已提交
2512
      }
A
Andreas Dilger 已提交
2513 2514 2515 2516

#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2517
         int j;
A
Andreas Dilger 已提交
2518 2519 2520 2521
         png_uint_32 sumhi, sumlo;
         sumlo = sum & PNG_LOMASK;
         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;

2522
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2523
         {
2524
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
A
Andreas Dilger 已提交
2525
            {
2526
               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
A
Andreas Dilger 已提交
2527
                  PNG_WEIGHT_SHIFT;
2528
               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
A
Andreas Dilger 已提交
2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544
                  PNG_WEIGHT_SHIFT;
            }
         }

         sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
            PNG_COST_SHIFT;
         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
            PNG_COST_SHIFT;

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
      }
#endif

G
Guy Schalnat 已提交
2545 2546 2547 2548 2549 2550
      if (sum < mins)
      {
         mins = sum;
         best_row = png_ptr->avg_row;
      }
   }
G
Guy Schalnat 已提交
2551

A
Andreas Dilger 已提交
2552
   /* Paeth filter */
2553 2554 2555
   if (filter_to_do == PNG_FILTER_PAETH)
   {
      png_bytep rp, dp, pp, cp, lp;
2556
      png_uint_32 i;
2557
      for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
2558
           pp = prev_row + 1; i < bpp; i++)
2559
      {
2560
         *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
2561 2562
      }

2563
      for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
2564 2565 2566
      {
         int a, b, c, pa, pb, pc, p;

2567 2568 2569
         b = *pp++;
         c = *cp++;
         a = *lp++;
2570

2571 2572
         p = b - c;
         pc = a - c;
2573 2574

#ifdef PNG_USE_ABS
2575 2576 2577
         pa = abs(p);
         pb = abs(pc);
         pc = abs(p + pc);
2578
#else
2579 2580 2581
         pa = p < 0 ? -p : p;
         pb = pc < 0 ? -pc : pc;
         pc = (p + pc) < 0 ? -(p + pc) : p + pc;
2582 2583 2584 2585
#endif

         p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;

2586
         *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
2587 2588 2589 2590 2591
      }
      best_row = png_ptr->paeth_row;
   }

   else if (filter_to_do & PNG_FILTER_PAETH)
G
Guy Schalnat 已提交
2592 2593
   {
      png_bytep rp, dp, pp, cp, lp;
A
Andreas Dilger 已提交
2594
      png_uint_32 sum = 0, lmins = mins;
2595
      png_uint_32 i;
A
Andreas Dilger 已提交
2596 2597 2598 2599 2600
      int v;

#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2601
         int j;
A
Andreas Dilger 已提交
2602 2603 2604 2605
         png_uint_32 lmhi, lmlo;
         lmlo = lmins & PNG_LOMASK;
         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;

2606
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2607
         {
2608
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
A
Andreas Dilger 已提交
2609
            {
2610
               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
A
Andreas Dilger 已提交
2611
                  PNG_WEIGHT_SHIFT;
2612
               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
A
Andreas Dilger 已提交
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
                  PNG_WEIGHT_SHIFT;
            }
         }

         lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
            PNG_COST_SHIFT;
         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
            PNG_COST_SHIFT;

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
         else
            lmins = (lmhi << PNG_HISHIFT) + lmlo;
      }
#endif
G
Guy Schalnat 已提交
2628

G
Guy Schalnat 已提交
2629
      for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
2630
           pp = prev_row + 1; i < bpp; i++)
G
Guy Schalnat 已提交
2631
      {
2632
         v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
G
Guy Schalnat 已提交
2633

G
Guy Schalnat 已提交
2634 2635
         sum += (v < 128) ? v : 256 - v;
      }
2636

2637
      for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
G
Guy Schalnat 已提交
2638 2639
      {
         int a, b, c, pa, pb, pc, p;
G
Guy Schalnat 已提交
2640

2641 2642 2643
         b = *pp++;
         c = *cp++;
         a = *lp++;
2644 2645

#ifndef PNG_SLOW_PAETH
2646 2647
         p = b - c;
         pc = a - c;
2648
#ifdef PNG_USE_ABS
2649 2650 2651
         pa = abs(p);
         pb = abs(pc);
         pc = abs(p + pc);
2652
#else
2653 2654 2655
         pa = p < 0 ? -p : p;
         pb = pc < 0 ? -pc : pc;
         pc = (p + pc) < 0 ? -(p + pc) : p + pc;
2656 2657 2658
#endif
         p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
#else /* PNG_SLOW_PAETH */
2659
         p = a + b - c;
2660 2661 2662
         pa = abs(p - a);
         pb = abs(p - b);
         pc = abs(p - c);
G
Guy Schalnat 已提交
2663 2664 2665 2666 2667 2668
         if (pa <= pb && pa <= pc)
            p = a;
         else if (pb <= pc)
            p = b;
         else
            p = c;
2669
#endif /* PNG_SLOW_PAETH */
G
Guy Schalnat 已提交
2670

2671
         v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
G
Guy Schalnat 已提交
2672

G
Guy Schalnat 已提交
2673
         sum += (v < 128) ? v : 256 - v;
A
Andreas Dilger 已提交
2674 2675 2676

         if (sum > lmins)  /* We are already worse, don't continue. */
            break;
G
Guy Schalnat 已提交
2677
      }
A
Andreas Dilger 已提交
2678 2679 2680 2681

#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2682
         int j;
A
Andreas Dilger 已提交
2683 2684 2685 2686
         png_uint_32 sumhi, sumlo;
         sumlo = sum & PNG_LOMASK;
         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;

2687
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2688
         {
2689
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
A
Andreas Dilger 已提交
2690
            {
2691
               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
A
Andreas Dilger 已提交
2692
                  PNG_WEIGHT_SHIFT;
2693
               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
A
Andreas Dilger 已提交
2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709
                  PNG_WEIGHT_SHIFT;
            }
         }

         sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
            PNG_COST_SHIFT;
         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
            PNG_COST_SHIFT;

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
      }
#endif

G
Guy Schalnat 已提交
2710 2711 2712 2713
      if (sum < mins)
      {
         best_row = png_ptr->paeth_row;
      }
G
Guy Schalnat 已提交
2714
   }
2715
#endif /* PNG_NO_WRITE_FILTER */
A
Andreas Dilger 已提交
2716
   /* Do the actual writing of the filtered row data from the chosen filter. */
2717

G
Guy Schalnat 已提交
2718
   png_write_filtered_row(png_ptr, best_row);
A
Andreas Dilger 已提交
2719

2720
#ifndef PNG_NO_WRITE_FILTER
A
Andreas Dilger 已提交
2721 2722 2723 2724
#if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
   /* Save the type of filter we picked this time for future calculations */
   if (png_ptr->num_prev_filters > 0)
   {
2725 2726
      int j;
      for (j = 1; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2727
      {
2728
         png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
A
Andreas Dilger 已提交
2729
      }
2730
      png_ptr->prev_filters[j] = best_row[0];
A
Andreas Dilger 已提交
2731 2732
   }
#endif
2733
#endif /* PNG_NO_WRITE_FILTER */
G
Guy Schalnat 已提交
2734
}
G
Guy Schalnat 已提交
2735

G
Guy Schalnat 已提交
2736

A
Andreas Dilger 已提交
2737
/* Do the actual writing of a previously filtered row. */
2738
void /* PRIVATE */
G
Guy Schalnat 已提交
2739 2740
png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
{
2741 2742
   png_debug(1, "in png_write_filtered_row");
   png_debug1(2, "filter = %d", filtered_row[0]);
2743
   /* Set up the zlib input buffer */
2744

A
Andreas Dilger 已提交
2745 2746
   png_ptr->zstream.next_in = filtered_row;
   png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
2747
   /* Repeat until we have compressed all the data */
G
Guy Schalnat 已提交
2748
   do
G
Guy Schalnat 已提交
2749
   {
2750
      int ret; /* Return of zlib */
G
Guy Schalnat 已提交
2751

2752
      /* Compress the data */
A
Andreas Dilger 已提交
2753
      ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
2754
      /* Check for compression errors */
G
Guy Schalnat 已提交
2755 2756
      if (ret != Z_OK)
      {
A
Andreas Dilger 已提交
2757
         if (png_ptr->zstream.msg != NULL)
A
Andreas Dilger 已提交
2758
            png_error(png_ptr, png_ptr->zstream.msg);
G
Guy Schalnat 已提交
2759 2760 2761
         else
            png_error(png_ptr, "zlib error");
      }
G
Guy Schalnat 已提交
2762

2763
      /* See if it is time to write another IDAT */
A
Andreas Dilger 已提交
2764
      if (!(png_ptr->zstream.avail_out))
G
Guy Schalnat 已提交
2765
      {
2766
         /* Write the IDAT and reset the zlib output buffer */
G
Guy Schalnat 已提交
2767
         png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
A
Andreas Dilger 已提交
2768 2769
         png_ptr->zstream.next_out = png_ptr->zbuf;
         png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
G
Guy Schalnat 已提交
2770
      }
2771
   /* Repeat until all data has been compressed */
A
Andreas Dilger 已提交
2772
   } while (png_ptr->zstream.avail_in);
G
Guy Schalnat 已提交
2773

2774
   /* Swap the current and previous rows */
A
Andreas Dilger 已提交
2775
   if (png_ptr->prev_row != NULL)
G
Guy Schalnat 已提交
2776 2777 2778 2779 2780 2781 2782 2783
   {
      png_bytep tptr;

      tptr = png_ptr->prev_row;
      png_ptr->prev_row = png_ptr->row_buf;
      png_ptr->row_buf = tptr;
   }

2784
   /* Finish row - updates counters and flushes zlib if last row */
G
Guy Schalnat 已提交
2785
   png_write_finish_row(png_ptr);
G
Guy Schalnat 已提交
2786

G
Guy Schalnat 已提交
2787 2788 2789 2790 2791 2792 2793
#if defined(PNG_WRITE_FLUSH_SUPPORTED)
   png_ptr->flush_rows++;

   if (png_ptr->flush_dist > 0 &&
       png_ptr->flush_rows >= png_ptr->flush_dist)
   {
      png_write_flush(png_ptr);
G
Guy Schalnat 已提交
2794
   }
2795
#endif
G
Guy Schalnat 已提交
2796
}
2797
#endif /* PNG_WRITE_SUPPORTED */