pngwutil.c 80.2 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.5.0 [August 2, 2010]
5
 * Copyright (c) 1998-2010 Glenn Randers-Pehrson
6 7
 * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
 * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
8
 *
9
 * This code is released under the libpng license.
10
 * For conditions of distribution and use, see the disclaimer
11
 * and license in png.h
12
 */
A
Andreas Dilger 已提交
13

14
#include "pngpriv.h"
G
Guy Schalnat 已提交
15

16 17
#ifdef PNG_WRITE_SUPPORTED

18
#ifdef PNG_WRITE_INT_FUNCTIONS_SUPPORTED
A
Andreas Dilger 已提交
19 20 21 22
/* 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.
 */
23
void PNGAPI
G
Guy Schalnat 已提交
24
png_save_uint_32(png_bytep buf, png_uint_32 i)
G
Guy Schalnat 已提交
25 26 27 28 29 30 31
{
   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);
}

32
#ifdef PNG_SAVE_INT_32_SUPPORTED
A
Andreas Dilger 已提交
33
/* The png_save_int_32 function assumes integers are stored in two's
34
 * complement format.  If this isn't the case, then this routine needs to
G
[devel]  
Glenn Randers-Pehrson 已提交
35 36 37
 * be modified to write data in two's complement format.  Note that,
 * the following works correctly even if png_int_32 has more than 32 bits
 * (compare the more complex code required on read for sign extention.)
38
 */
39
void PNGAPI
A
Andreas Dilger 已提交
40
png_save_int_32(png_bytep buf, png_int_32 i)
G
Guy Schalnat 已提交
41 42 43 44 45 46
{
   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);
}
47
#endif
G
Guy Schalnat 已提交
48

49 50 51 52
/* 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.
 */
53
void PNGAPI
54
png_save_uint_16(png_bytep buf, unsigned int i)
G
Guy Schalnat 已提交
55 56 57 58
{
   buf[0] = (png_byte)((i >> 8) & 0xff);
   buf[1] = (png_byte)(i & 0xff);
}
59
#endif
G
Guy Schalnat 已提交
60

61 62 63 64 65 66
/* 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.
 */
67
void PNGAPI
68 69 70
png_write_sig(png_structp png_ptr)
{
   png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
71

72 73 74 75 76
#ifdef PNG_IO_STATE_SUPPORTED
   /* Inform the I/O callback that the signature is being written */
   png_ptr->io_state = PNG_IO_WRITING | PNG_IO_SIGNATURE;
#endif

77
   /* Write the rest of the 8 byte signature */
78
   png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
79
      (png_size_t)(8 - png_ptr->sig_bytes));
80

81
   if (png_ptr->sig_bytes < 3)
82 83 84
      png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
}

A
Andreas Dilger 已提交
85
/* Write a PNG chunk all at once.  The type is an array of ASCII characters
86 87 88 89 90 91 92 93
 * 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.
 */
94
void PNGAPI
A
Andreas Dilger 已提交
95
png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
A
Andreas Dilger 已提交
96
   png_bytep data, png_size_t length)
G
Guy Schalnat 已提交
97
{
98 99
   if (png_ptr == NULL)
      return;
A
Andreas Dilger 已提交
100
   png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
101
   png_write_chunk_data(png_ptr, data, (png_size_t)length);
A
Andreas Dilger 已提交
102
   png_write_chunk_end(png_ptr);
G
Guy Schalnat 已提交
103 104
}

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

115 116 117 118 119 120
   png_debug2(0, "Writing %s chunk, length = %lu", chunk_name,
      (unsigned long)length);

   if (png_ptr == NULL)
      return;

121 122 123 124 125 126 127
#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

128
   /* Write the length and the chunk name */
A
Andreas Dilger 已提交
129
   png_save_uint_32(buf, length);
130
   png_memcpy(buf + 4, chunk_name, 4);
131
   png_write_data(png_ptr, buf, (png_size_t)8);
132
   /* Put the chunk name into png_ptr->chunk_name */
133
   png_memcpy(png_ptr->chunk_name, chunk_name, 4);
134
   /* Reset the crc and run it over the chunk name */
G
Guy Schalnat 已提交
135
   png_reset_crc(png_ptr);
136 137 138 139 140 141 142 143
   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 已提交
144 145
}

A
Andreas Dilger 已提交
146
/* Write the data of a PNG chunk started with png_write_chunk_start().
147 148 149 150
 * 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().
 */
151
void PNGAPI
A
Andreas Dilger 已提交
152
png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
G
Guy Schalnat 已提交
153
{
154 155 156
   /* Write the data, and run the CRC over it */
   if (png_ptr == NULL)
      return;
157

A
Andreas Dilger 已提交
158
   if (data != NULL && length > 0)
G
Guy Schalnat 已提交
159
   {
G
Guy Schalnat 已提交
160
      png_write_data(png_ptr, data, length);
161
      /* Update the CRC after writing the data,
162 163 164
       * in case that the user I/O routine alters it.
       */
      png_calculate_crc(png_ptr, data, length);
G
Guy Schalnat 已提交
165 166 167
   }
}

A
Andreas Dilger 已提交
168
/* Finish a chunk started with png_write_chunk_start(). */
169
void PNGAPI
G
Guy Schalnat 已提交
170
png_write_chunk_end(png_structp png_ptr)
G
Guy Schalnat 已提交
171
{
A
Andreas Dilger 已提交
172 173
   png_byte buf[4];

174 175
   if (png_ptr == NULL) return;

176 177 178 179 180 181 182
#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

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

186
   png_write_data(png_ptr, buf, (png_size_t)4);
G
Guy Schalnat 已提交
187 188
}

189
#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
190
/* This pair of functions encapsulates the operation of (a) compressing a
191 192 193 194 195 196 197
 * 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
{
198 199 200 201 202
   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 */
203 204
} compression_state;

205
/* Compress given text into storage in the png_ptr structure */
206
static int /* PRIVATE */
207
png_text_compress(png_structp png_ptr,
208 209
    png_charp text, png_size_t text_len, int compression,
    compression_state *comp)
210 211 212
{
   int ret;

213 214
   comp->num_output_ptr = 0;
   comp->max_output_ptr = 0;
215 216
   comp->output_ptr = NULL;
   comp->input = NULL;
217
   comp->input_len = 0;
218

219
   /* We may just want to pass the text right through */
220 221
   if (compression == PNG_TEXT_COMPRESSION_NONE)
   {
222 223 224
      comp->input = text;
      comp->input_len = text_len;
      return((int)text_len);
225 226 227 228
   }

   if (compression >= PNG_TEXT_COMPRESSION_LAST)
   {
229
#ifdef PNG_CONSOLE_IO_SUPPORTED
230
      char msg[50];
231
      png_snprintf(msg, 50, "Unknown compression type %d", compression);
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
      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).
    */

253
   /* Set up the compression buffers */
254 255 256 257 258
   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;

259
   /* This is the same compression loop as in png_write_row() */
260 261
   do
   {
262
      /* Compress the data */
263
      ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
264

265 266
      if (ret != Z_OK)
      {
267
         /* Error */
268 269 270 271 272
         if (png_ptr->zstream.msg != NULL)
            png_error(png_ptr, png_ptr->zstream.msg);
         else
            png_error(png_ptr, "zlib error");
      }
273

274
      /* Check to see if we need more room */
275
      if (!(png_ptr->zstream.avail_out))
276
      {
277
         /* Make sure the output array has room */
278 279 280 281 282 283 284 285 286 287 288 289
         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,
290 291
                   (png_alloc_size_t)
                   (comp->max_output_ptr * png_sizeof(png_charpp)));
292
               png_memcpy(comp->output_ptr, old_ptr, old_max
293
                   * png_sizeof(png_charp));
294 295 296 297
               png_free(png_ptr, old_ptr);
            }
            else
               comp->output_ptr = (png_charpp)png_malloc(png_ptr,
298 299
                   (png_alloc_size_t)
                   (comp->max_output_ptr * png_sizeof(png_charp)));
300 301
         }

302
         /* Save the data */
303
         comp->output_ptr[comp->num_output_ptr] =
304 305
             (png_charp)png_malloc(png_ptr,
             (png_alloc_size_t)png_ptr->zbuf_size);
306
         png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
307
             png_ptr->zbuf_size);
308
         comp->num_output_ptr++;
309 310 311 312 313

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

317
   /* Finish the compression */
318 319
   do
   {
320
      /* Tell zlib we are finished */
321 322
      ret = deflate(&png_ptr->zstream, Z_FINISH);

323
      if (ret == Z_OK)
324
      {
325
         /* Check to see if we need more room */
326
         if (!(png_ptr->zstream.avail_out))
327
         {
328
            /* Check to make sure our output array has room */
329
            if (comp->num_output_ptr >= comp->max_output_ptr)
330
            {
331 332 333 334 335 336 337 338 339 340 341
               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,
342 343
                      (png_alloc_size_t)(comp->max_output_ptr *
                      png_sizeof(png_charp)));
344
                  png_memcpy(comp->output_ptr, old_ptr,
345
                      old_max * png_sizeof(png_charp));
346 347
                  png_free(png_ptr, old_ptr);
               }
348

349 350
               else
                  comp->output_ptr = (png_charpp)png_malloc(png_ptr,
351 352
                      (png_alloc_size_t)(comp->max_output_ptr *
                      png_sizeof(png_charp)));
353 354
            }

355
            /* Save the data */
356
            comp->output_ptr[comp->num_output_ptr] =
357 358
                (png_charp)png_malloc(png_ptr,
                (png_alloc_size_t)png_ptr->zbuf_size);
359

360
            png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
361
                png_ptr->zbuf_size);
362

363
            comp->num_output_ptr++;
364

365 366 367 368 369 370 371
            /* 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)
      {
372
         /* We got an error */
373 374
         if (png_ptr->zstream.msg != NULL)
            png_error(png_ptr, png_ptr->zstream.msg);
375

376 377
         else
            png_error(png_ptr, "zlib error");
378 379 380
      }
   } while (ret != Z_STREAM_END);

381
   /* Text length is number of buffers plus last buffer */
382 383 384 385
   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;

386
   return((int)text_len);
387 388
}

389
/* Ship the compressed text out via chunk writes */
390
static void /* PRIVATE */
391 392 393 394
png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
{
   int i;

395
   /* Handle the no-compression case */
396 397
   if (comp->input)
   {
398
      png_write_chunk_data(png_ptr, (png_bytep)comp->input,
399
          (png_size_t)comp->input_len);
400

401
      return;
402 403
   }

404
   /* Write saved output buffers, if any */
405 406
   for (i = 0; i < comp->num_output_ptr; i++)
   {
407
      png_write_chunk_data(png_ptr, (png_bytep)comp->output_ptr[i],
408
          (png_size_t)png_ptr->zbuf_size);
409

410 411 412 413
      png_free(png_ptr, comp->output_ptr[i]);
   }
   if (comp->max_output_ptr != 0)
      png_free(png_ptr, comp->output_ptr);
414

415
   /* Write anything left in zbuf */
416 417
   if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
      png_write_chunk_data(png_ptr, png_ptr->zbuf,
418
          (png_size_t)(png_ptr->zbuf_size - png_ptr->zstream.avail_out));
419

420
   /* Reset zlib for another zTXt/iTXt or image data */
421
   deflateReset(&png_ptr->zstream);
422
   png_ptr->zstream.data_type = Z_BINARY;
423 424 425
}
#endif

G
Guy Schalnat 已提交
426
/* Write the IHDR chunk, and update the png_struct with the necessary
427 428 429
 * information.  Note that the rest of this code depends upon this
 * information being correct.
 */
430
void /* PRIVATE */
G
Guy Schalnat 已提交
431
png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
432 433
    int bit_depth, int color_type, int compression_type, int filter_type,
    int interlace_type)
G
Guy Schalnat 已提交
434
{
435
   PNG_IHDR;
436 437
   int ret;

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

440
   png_debug(1, "in png_write_IHDR");
441

G
Guy Schalnat 已提交
442
   /* Check that we have valid input data from the application info */
G
Guy Schalnat 已提交
443 444
   switch (color_type)
   {
A
Andreas Dilger 已提交
445
      case PNG_COLOR_TYPE_GRAY:
G
Guy Schalnat 已提交
446 447 448 449 450 451
         switch (bit_depth)
         {
            case 1:
            case 2:
            case 4:
            case 8:
452 453 454 455 456
            case 16:
               png_ptr->channels = 1; break;
            default:
               png_error(png_ptr,
                   "Invalid bit depth for grayscale image");
G
Guy Schalnat 已提交
457
         }
G
Guy Schalnat 已提交
458
         break;
459

A
Andreas Dilger 已提交
460
      case PNG_COLOR_TYPE_RGB:
G
Guy Schalnat 已提交
461 462
         if (bit_depth != 8 && bit_depth != 16)
            png_error(png_ptr, "Invalid bit depth for RGB image");
463

G
Guy Schalnat 已提交
464 465
         png_ptr->channels = 3;
         break;
466

A
Andreas Dilger 已提交
467
      case PNG_COLOR_TYPE_PALETTE:
G
Guy Schalnat 已提交
468 469 470 471 472
         switch (bit_depth)
         {
            case 1:
            case 2:
            case 4:
473 474 475 476 477
            case 8:
               png_ptr->channels = 1;
               break;
            default:
               png_error(png_ptr, "Invalid bit depth for paletted image");
G
Guy Schalnat 已提交
478 479
         }
         break;
480

A
Andreas Dilger 已提交
481
      case PNG_COLOR_TYPE_GRAY_ALPHA:
G
Guy Schalnat 已提交
482 483
         if (bit_depth != 8 && bit_depth != 16)
            png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
484

G
Guy Schalnat 已提交
485 486
         png_ptr->channels = 2;
         break;
487

A
Andreas Dilger 已提交
488
      case PNG_COLOR_TYPE_RGB_ALPHA:
G
Guy Schalnat 已提交
489 490
         if (bit_depth != 8 && bit_depth != 16)
            png_error(png_ptr, "Invalid bit depth for RGBA image");
491

G
Guy Schalnat 已提交
492 493
         png_ptr->channels = 4;
         break;
494

G
Guy Schalnat 已提交
495 496 497 498
      default:
         png_error(png_ptr, "Invalid image color type specified");
   }

A
Andreas Dilger 已提交
499
   if (compression_type != PNG_COMPRESSION_TYPE_BASE)
G
Guy Schalnat 已提交
500 501
   {
      png_warning(png_ptr, "Invalid compression type specified");
A
Andreas Dilger 已提交
502
      compression_type = PNG_COMPRESSION_TYPE_BASE;
G
Guy Schalnat 已提交
503 504
   }

505 506 507 508 509 510 511 512 513
   /* 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
    */
514
   if (
515
#ifdef PNG_MNG_FEATURES_SUPPORTED
516 517 518 519 520
       !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
       ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
       (color_type == PNG_COLOR_TYPE_RGB ||
        color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
       (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
521
#endif
522
       filter_type != PNG_FILTER_TYPE_BASE)
G
Guy Schalnat 已提交
523 524
   {
      png_warning(png_ptr, "Invalid filter type specified");
A
Andreas Dilger 已提交
525
      filter_type = PNG_FILTER_TYPE_BASE;
G
Guy Schalnat 已提交
526 527
   }

528
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
A
Andreas Dilger 已提交
529
   if (interlace_type != PNG_INTERLACE_NONE &&
530
       interlace_type != PNG_INTERLACE_ADAM7)
G
Guy Schalnat 已提交
531 532
   {
      png_warning(png_ptr, "Invalid interlace type specified");
A
Andreas Dilger 已提交
533
      interlace_type = PNG_INTERLACE_ADAM7;
G
Guy Schalnat 已提交
534
   }
535 536 537
#else
   interlace_type=PNG_INTERLACE_NONE;
#endif
G
Guy Schalnat 已提交
538

539
   /* Save the relevent information */
G
Guy Schalnat 已提交
540 541 542
   png_ptr->bit_depth = (png_byte)bit_depth;
   png_ptr->color_type = (png_byte)color_type;
   png_ptr->interlaced = (png_byte)interlace_type;
543
#ifdef PNG_MNG_FEATURES_SUPPORTED
544
   png_ptr->filter_type = (png_byte)filter_type;
545
#endif
546
   png_ptr->compression_type = (png_byte)compression_type;
G
Guy Schalnat 已提交
547 548 549
   png_ptr->width = width;
   png_ptr->height = height;

G
Guy Schalnat 已提交
550
   png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
551
   png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
552
   /* Set the usr info, so any transformations can modify it */
G
Guy Schalnat 已提交
553 554
   png_ptr->usr_width = png_ptr->width;
   png_ptr->usr_bit_depth = png_ptr->bit_depth;
G
Guy Schalnat 已提交
555 556
   png_ptr->usr_channels = png_ptr->channels;

557
   /* Pack the header information into the buffer */
G
Guy Schalnat 已提交
558 559 560 561 562 563 564
   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 已提交
565

566
   /* Write the chunk */
567
   png_write_chunk(png_ptr, (png_bytep)png_IHDR, buf, (png_size_t)13);
G
Guy Schalnat 已提交
568

569
   /* Initialize zlib with PNG info */
A
Andreas Dilger 已提交
570 571 572
   png_ptr->zstream.zalloc = png_zalloc;
   png_ptr->zstream.zfree = png_zfree;
   png_ptr->zstream.opaque = (voidpf)png_ptr;
573

G
Guy Schalnat 已提交
574
   if (!(png_ptr->do_filter))
G
Guy Schalnat 已提交
575
   {
A
Andreas Dilger 已提交
576
      if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
577
          png_ptr->bit_depth < 8)
G
Guy Schalnat 已提交
578
         png_ptr->do_filter = PNG_FILTER_NONE;
579

G
Guy Schalnat 已提交
580
      else
G
Guy Schalnat 已提交
581
         png_ptr->do_filter = PNG_ALL_FILTERS;
G
Guy Schalnat 已提交
582
   }
G
Guy Schalnat 已提交
583
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
G
Guy Schalnat 已提交
584
   {
G
Guy Schalnat 已提交
585
      if (png_ptr->do_filter != PNG_FILTER_NONE)
G
Guy Schalnat 已提交
586
         png_ptr->zlib_strategy = Z_FILTERED;
587

G
Guy Schalnat 已提交
588 589 590
      else
         png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
   }
G
Guy Schalnat 已提交
591
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
G
Guy Schalnat 已提交
592
      png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
593

G
Guy Schalnat 已提交
594
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
G
Guy Schalnat 已提交
595
      png_ptr->zlib_mem_level = 8;
596

G
Guy Schalnat 已提交
597
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
598
      png_ptr->zlib_window_bits = 15;
599

G
Guy Schalnat 已提交
600
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
G
Guy Schalnat 已提交
601
      png_ptr->zlib_method = 8;
602

603
   ret = deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
604 605
       png_ptr->zlib_method, png_ptr->zlib_window_bits,
       png_ptr->zlib_mem_level, png_ptr->zlib_strategy);
606

607 608
   if (ret != Z_OK)
   {
609 610 611
      if (ret == Z_VERSION_ERROR)
         png_error(png_ptr,
            "zlib failed to initialize compressor -- version error");
612

613 614 615
      if (ret == Z_STREAM_ERROR)
         png_error(png_ptr,
             "zlib failed to initialize compressor -- stream error");
616

617 618 619
      if (ret == Z_MEM_ERROR)
         png_error(png_ptr,
             "zlib failed to initialize compressor -- mem error");
620

621 622
      png_error(png_ptr, "zlib failed to initialize compressor");
   }
623

A
Andreas Dilger 已提交
624 625
   png_ptr->zstream.next_out = png_ptr->zbuf;
   png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
626
   /* libpng is not interested in zstream.data_type */
627
   /* Set it to a predefined value, to avoid its evaluation inside zlib */
628
   png_ptr->zstream.data_type = Z_BINARY;
G
Guy Schalnat 已提交
629

G
Guy Schalnat 已提交
630
   png_ptr->mode = PNG_HAVE_IHDR;
G
Guy Schalnat 已提交
631 632
}

633
/* Write the palette.  We are careful not to trust png_color to be in the
634
 * correct order for PNG, so people can redefine it to any convenient
635 636
 * structure.
 */
637
void /* PRIVATE */
A
Andreas Dilger 已提交
638
png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
G
Guy Schalnat 已提交
639
{
640
   PNG_PLTE;
A
Andreas Dilger 已提交
641
   png_uint_32 i;
G
Guy Schalnat 已提交
642
   png_colorp pal_ptr;
G
Guy Schalnat 已提交
643 644
   png_byte buf[3];

645
   png_debug(1, "in png_write_PLTE");
646

647
   if ((
648
#ifdef PNG_MNG_FEATURES_SUPPORTED
649
       !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
650
#endif
651
       num_pal == 0) || num_pal > 256)
652
   {
653 654 655 656
      if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
      {
         png_error(png_ptr, "Invalid number of colors in palette");
      }
657

658 659 660 661 662
      else
      {
         png_warning(png_ptr, "Invalid number of colors in palette");
         return;
      }
663 664 665 666 667
   }

   if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
   {
      png_warning(png_ptr,
668
          "Ignoring request to write a PLTE chunk in grayscale PNG");
669

670
      return;
G
Guy Schalnat 已提交
671 672
   }

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

676
   png_write_chunk_start(png_ptr, (png_bytep)png_PLTE,
677
       (png_uint_32)(num_pal * 3));
678
#ifdef PNG_POINTER_INDEXING_SUPPORTED
679

A
Andreas Dilger 已提交
680
   for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
G
Guy Schalnat 已提交
681 682 683 684
   {
      buf[0] = pal_ptr->red;
      buf[1] = pal_ptr->green;
      buf[2] = pal_ptr->blue;
685
      png_write_chunk_data(png_ptr, buf, (png_size_t)3);
G
Guy Schalnat 已提交
686
   }
687

688
#else
689 690 691
   /* This is a little slower but some buggy compilers need to do this
    * instead
    */
692
   pal_ptr=palette;
693

694 695 696 697 698
   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;
699
      png_write_chunk_data(png_ptr, buf, (png_size_t)3);
700
   }
701

702
#endif
G
Guy Schalnat 已提交
703
   png_write_chunk_end(png_ptr);
G
Guy Schalnat 已提交
704
   png_ptr->mode |= PNG_HAVE_PLTE;
G
Guy Schalnat 已提交
705 706
}

707
/* Write an IDAT chunk */
708
void /* PRIVATE */
A
Andreas Dilger 已提交
709
png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
G
Guy Schalnat 已提交
710
{
711
   PNG_IDAT;
712

713
   png_debug(1, "in png_write_IDAT");
714

715 716 717 718 719 720 721 722
   /* 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)
      {
723 724 725 726 727
         /* Avoid memory underflows and multiplication overflows.
          *
          * The conditions below are practically always satisfied;
          * however, they still must be checked.
          */
728 729 730 731
         if (length >= 2 &&
             png_ptr->height < 16384 && png_ptr->width < 16384)
         {
            png_uint_32 uncompressed_idat_size = png_ptr->height *
732 733
                ((png_ptr->width *
                png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
734 735 736
            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 &&
737
                half_z_window_size >= 256)
738 739 740 741 742 743 744 745 746 747 748 749 750
            {
               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);
            }
         }
      }
751

752 753
      else
         png_error(png_ptr,
754
             "Invalid zlib compression method or flags in IDAT");
755 756
   }

757
   png_write_chunk(png_ptr, (png_bytep)png_IDAT, data, length);
G
Guy Schalnat 已提交
758
   png_ptr->mode |= PNG_HAVE_IDAT;
G
Guy Schalnat 已提交
759 760
}

761
/* Write an IEND chunk */
762
void /* PRIVATE */
G
Guy Schalnat 已提交
763
png_write_IEND(png_structp png_ptr)
G
Guy Schalnat 已提交
764
{
765
   PNG_IEND;
766

767
   png_debug(1, "in png_write_IEND");
768

769
   png_write_chunk(png_ptr, (png_bytep)png_IEND, NULL, (png_size_t)0);
A
Andreas Dilger 已提交
770
   png_ptr->mode |= PNG_HAVE_IEND;
G
Guy Schalnat 已提交
771 772
}

773
#ifdef PNG_WRITE_gAMA_SUPPORTED
774
/* Write a gAMA chunk */
775
void /* PRIVATE */
776
png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
777 778 779 780
{
   PNG_gAMA;
   png_byte buf[4];

781
   png_debug(1, "in png_write_gAMA");
782

783
   /* file_gamma is saved in 1/100,000ths */
784
   png_save_uint_32(buf, (png_uint_32)file_gamma);
785
   png_write_chunk(png_ptr, (png_bytep)png_gAMA, buf, (png_size_t)4);
786 787
}
#endif
G
Guy Schalnat 已提交
788

789
#ifdef PNG_WRITE_sRGB_SUPPORTED
790
/* Write a sRGB chunk */
791
void /* PRIVATE */
792
png_write_sRGB(png_structp png_ptr, int srgb_intent)
793
{
794
   PNG_sRGB;
795 796
   png_byte buf[1];

797
   png_debug(1, "in png_write_sRGB");
798

799
   if (srgb_intent >= PNG_sRGB_INTENT_LAST)
800 801
      png_warning(png_ptr,
          "Invalid sRGB rendering intent specified");
802

803
   buf[0]=(png_byte)srgb_intent;
804
   png_write_chunk(png_ptr, (png_bytep)png_sRGB, buf, (png_size_t)1);
805 806 807
}
#endif

808
#ifdef PNG_WRITE_iCCP_SUPPORTED
809
/* Write an iCCP chunk */
810
void /* PRIVATE */
811
png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
812
    png_charp profile, int profile_len)
813 814 815 816 817
{
   PNG_iCCP;
   png_size_t name_len;
   png_charp new_name;
   compression_state comp;
818
   int embedded_profile_len = 0;
819

820
   png_debug(1, "in png_write_iCCP");
821 822 823 824 825 826 827

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

828
   if ((name_len = png_check_keyword(png_ptr, name, &new_name)) == 0)
829 830
      return;

831
   if (compression_type != PNG_COMPRESSION_TYPE_BASE)
832
      png_warning(png_ptr, "Unknown compression type in iCCP chunk");
833

834
   if (profile == NULL)
835 836
      profile_len = 0;

837
   if (profile_len > 3)
838
      embedded_profile_len =
839 840 841 842
          ((*( (png_bytep)profile    ))<<24) |
          ((*( (png_bytep)profile + 1))<<16) |
          ((*( (png_bytep)profile + 2))<< 8) |
          ((*( (png_bytep)profile + 3))    );
843

844 845 846
   if (embedded_profile_len < 0)
   {
      png_warning(png_ptr,
847
          "Embedded profile length in iCCP chunk is negative");
848 849 850 851
      png_free(png_ptr, new_name);
      return;
   }

852
   if (profile_len < embedded_profile_len)
853 854
   {
      png_warning(png_ptr,
855
          "Embedded profile length too large in iCCP chunk");
856
      png_free(png_ptr, new_name);
857 858
      return;
   }
859 860

   if (profile_len > embedded_profile_len)
861 862
   {
      png_warning(png_ptr,
863
          "Truncating profile to actual length in iCCP chunk");
864 865
      profile_len = embedded_profile_len;
   }
866

867
   if (profile_len)
868
      profile_len = png_text_compress(png_ptr, profile,
869
          (png_size_t)profile_len, PNG_COMPRESSION_TYPE_BASE, &comp);
870

871
   /* Make sure we include the NULL after the name and the compression type */
872
   png_write_chunk_start(png_ptr, (png_bytep)png_iCCP,
873
       (png_uint_32)(name_len + profile_len + 2));
874

875
   new_name[name_len + 1] = 0x00;
876

877
   png_write_chunk_data(png_ptr, (png_bytep)new_name,
878
       (png_size_t)(name_len + 2));
879 880 881 882 883 884 885 886 887

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

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

888
#ifdef PNG_WRITE_sPLT_SUPPORTED
889
/* Write a sPLT chunk */
890
void /* PRIVATE */
891
png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
892 893 894 895 896
{
   PNG_sPLT;
   png_size_t name_len;
   png_charp new_name;
   png_byte entrybuf[10];
897 898
   png_size_t entry_size = (spalette->depth == 8 ? 6 : 10);
   png_size_t palette_size = entry_size * spalette->nentries;
899
   png_sPLT_entryp ep;
900
#ifndef PNG_POINTER_INDEXING_SUPPORTED
901 902
   int i;
#endif
903

904
   png_debug(1, "in png_write_sPLT");
905

906 907
   if ((name_len = png_check_keyword(png_ptr,spalette->name, &new_name))==0)
      return;
908

909
   /* Make sure we include the NULL after the name */
910
   png_write_chunk_start(png_ptr, (png_bytep)png_sPLT,
911
       (png_uint_32)(name_len + 2 + palette_size));
912

913
   png_write_chunk_data(png_ptr, (png_bytep)new_name,
914
       (png_size_t)(name_len + 1));
915

916
   png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, (png_size_t)1);
917

918
   /* Loop through each palette entry, writing appropriately */
919
#ifdef PNG_POINTER_INDEXING_SUPPORTED
920
   for (ep = spalette->entries; ep<spalette->entries + spalette->nentries; ep++)
921
   {
922 923
      if (spalette->depth == 8)
      {
924 925 926 927 928
         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);
929
      }
930

931 932
      else
      {
933 934 935 936 937
         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);
938
      }
939
      png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
940
   }
941 942
#else
   ep=spalette->entries;
943
   for (i = 0; i>spalette->nentries; i++)
944
   {
945 946
      if (spalette->depth == 8)
      {
947 948 949 950 951
         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);
952
      }
953

954 955
      else
      {
956 957 958 959 960
         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);
961
      }
962
      png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
963 964
   }
#endif
965 966 967 968 969 970

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

971
#ifdef PNG_WRITE_sBIT_SUPPORTED
972
/* Write the sBIT chunk */
973
void /* PRIVATE */
G
Guy Schalnat 已提交
974
png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
G
Guy Schalnat 已提交
975
{
976
   PNG_sBIT;
G
Guy Schalnat 已提交
977
   png_byte buf[4];
A
Andreas Dilger 已提交
978
   png_size_t size;
G
Guy Schalnat 已提交
979

980
   png_debug(1, "in png_write_sBIT");
981

982
   /* Make sure we don't depend upon the order of PNG_COLOR_8 */
G
Guy Schalnat 已提交
983 984
   if (color_type & PNG_COLOR_MASK_COLOR)
   {
985
      png_byte maxbits;
G
Guy Schalnat 已提交
986

987
      maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
988
          png_ptr->usr_bit_depth);
989

990 991
      if (sbit->red == 0 || sbit->red > maxbits ||
          sbit->green == 0 || sbit->green > maxbits ||
G
Guy Schalnat 已提交
992 993 994 995 996
          sbit->blue == 0 || sbit->blue > maxbits)
      {
         png_warning(png_ptr, "Invalid sBIT depth specified");
         return;
      }
997

G
Guy Schalnat 已提交
998 999 1000 1001 1002
      buf[0] = sbit->red;
      buf[1] = sbit->green;
      buf[2] = sbit->blue;
      size = 3;
   }
1003

G
Guy Schalnat 已提交
1004 1005
   else
   {
G
Guy Schalnat 已提交
1006 1007 1008 1009 1010
      if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
      {
         png_warning(png_ptr, "Invalid sBIT depth specified");
         return;
      }
G
Guy Schalnat 已提交
1011 1012 1013 1014 1015 1016
      buf[0] = sbit->gray;
      size = 1;
   }

   if (color_type & PNG_COLOR_MASK_ALPHA)
   {
G
Guy Schalnat 已提交
1017 1018 1019 1020 1021
      if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
      {
         png_warning(png_ptr, "Invalid sBIT depth specified");
         return;
      }
G
Guy Schalnat 已提交
1022 1023 1024
      buf[size++] = sbit->alpha;
   }

1025
   png_write_chunk(png_ptr, (png_bytep)png_sBIT, buf, size);
G
Guy Schalnat 已提交
1026
}
G
Guy Schalnat 已提交
1027
#endif
G
Guy Schalnat 已提交
1028

1029
#ifdef PNG_WRITE_cHRM_SUPPORTED
1030
/* Write the cHRM chunk */
1031
void /* PRIVATE */
1032
png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
1033 1034 1035
    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)
1036 1037 1038 1039
{
   PNG_cHRM;
   png_byte buf[32];

1040
   png_debug(1, "in png_write_cHRM");
1041

1042
   /* Each value is saved in 1/100,000ths */
1043
#ifdef PNG_CHECK_cHRM_SUPPORTED
1044
   if (png_check_cHRM_fixed(png_ptr, white_x, white_y, red_x, red_y,
1045
       green_x, green_y, blue_x, blue_y))
1046
#endif
1047
   {
1048 1049
      png_save_uint_32(buf, (png_uint_32)white_x);
      png_save_uint_32(buf + 4, (png_uint_32)white_y);
1050

1051 1052
      png_save_uint_32(buf + 8, (png_uint_32)red_x);
      png_save_uint_32(buf + 12, (png_uint_32)red_y);
1053

1054 1055
      png_save_uint_32(buf + 16, (png_uint_32)green_x);
      png_save_uint_32(buf + 20, (png_uint_32)green_y);
1056

1057 1058
      png_save_uint_32(buf + 24, (png_uint_32)blue_x);
      png_save_uint_32(buf + 28, (png_uint_32)blue_y);
1059

1060
      png_write_chunk(png_ptr, (png_bytep)png_cHRM, buf, (png_size_t)32);
1061
   }
1062 1063
}
#endif
G
Guy Schalnat 已提交
1064

1065
#ifdef PNG_WRITE_tRNS_SUPPORTED
1066
/* Write the tRNS chunk */
1067
void /* PRIVATE */
1068
png_write_tRNS(png_structp png_ptr, png_bytep trans_alpha, png_color_16p tran,
1069
    int num_trans, int color_type)
G
Guy Schalnat 已提交
1070
{
1071
   PNG_tRNS;
G
Guy Schalnat 已提交
1072 1073
   png_byte buf[6];

1074
   png_debug(1, "in png_write_tRNS");
1075

G
Guy Schalnat 已提交
1076 1077
   if (color_type == PNG_COLOR_TYPE_PALETTE)
   {
1078
      if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
G
Guy Schalnat 已提交
1079
      {
1080
         png_warning(png_ptr, "Invalid number of transparent colors specified");
G
Guy Schalnat 已提交
1081 1082
         return;
      }
1083

1084
      /* Write the chunk out as it is */
1085
      png_write_chunk(png_ptr, (png_bytep)png_tRNS, trans_alpha,
1086
        (png_size_t)num_trans);
G
Guy Schalnat 已提交
1087
   }
1088

G
Guy Schalnat 已提交
1089 1090
   else if (color_type == PNG_COLOR_TYPE_GRAY)
   {
1091
      /* One 16 bit value */
1092
      if (tran->gray >= (1 << png_ptr->bit_depth))
1093 1094
      {
         png_warning(png_ptr,
1095
             "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
1096 1097
         return;
      }
G
Guy Schalnat 已提交
1098
      png_save_uint_16(buf, tran->gray);
1099
      png_write_chunk(png_ptr, (png_bytep)png_tRNS, buf, (png_size_t)2);
G
Guy Schalnat 已提交
1100
   }
1101

G
Guy Schalnat 已提交
1102 1103
   else if (color_type == PNG_COLOR_TYPE_RGB)
   {
1104
      /* Three 16 bit values */
G
Guy Schalnat 已提交
1105 1106 1107
      png_save_uint_16(buf, tran->red);
      png_save_uint_16(buf + 2, tran->green);
      png_save_uint_16(buf + 4, tran->blue);
1108
      if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
1109 1110
      {
         png_warning(png_ptr,
1111
           "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
1112 1113
         return;
      }
1114
      png_write_chunk(png_ptr, (png_bytep)png_tRNS, buf, (png_size_t)6);
G
Guy Schalnat 已提交
1115
   }
1116

G
Guy Schalnat 已提交
1117 1118
   else
   {
1119
      png_warning(png_ptr, "Can't write tRNS with an alpha channel");
G
Guy Schalnat 已提交
1120
   }
G
Guy Schalnat 已提交
1121
}
G
Guy Schalnat 已提交
1122
#endif
G
Guy Schalnat 已提交
1123

1124
#ifdef PNG_WRITE_bKGD_SUPPORTED
1125
/* Write the background chunk */
1126
void /* PRIVATE */
G
Guy Schalnat 已提交
1127
png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
G
Guy Schalnat 已提交
1128
{
1129
   PNG_bKGD;
G
Guy Schalnat 已提交
1130 1131
   png_byte buf[6];

1132
   png_debug(1, "in png_write_bKGD");
1133

G
Guy Schalnat 已提交
1134 1135
   if (color_type == PNG_COLOR_TYPE_PALETTE)
   {
1136
      if (
1137
#ifdef PNG_MNG_FEATURES_SUPPORTED
1138 1139
          (png_ptr->num_palette ||
          (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
1140
#endif
1141
         back->index >= png_ptr->num_palette)
G
Guy Schalnat 已提交
1142 1143 1144 1145
      {
         png_warning(png_ptr, "Invalid background palette index");
         return;
      }
1146

G
Guy Schalnat 已提交
1147
      buf[0] = back->index;
1148
      png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)1);
G
Guy Schalnat 已提交
1149
   }
1150

G
Guy Schalnat 已提交
1151 1152 1153 1154 1155
   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);
1156
      if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
1157 1158
      {
         png_warning(png_ptr,
1159
             "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
1160

1161 1162
         return;
      }
1163
      png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)6);
G
Guy Schalnat 已提交
1164
   }
1165

G
Guy Schalnat 已提交
1166
   else
G
Guy Schalnat 已提交
1167
   {
1168
      if (back->gray >= (1 << png_ptr->bit_depth))
1169 1170
      {
         png_warning(png_ptr,
1171
             "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
1172

1173 1174
         return;
      }
G
Guy Schalnat 已提交
1175
      png_save_uint_16(buf, back->gray);
1176
      png_write_chunk(png_ptr, (png_bytep)png_bKGD, buf, (png_size_t)2);
G
Guy Schalnat 已提交
1177 1178
   }
}
G
Guy Schalnat 已提交
1179
#endif
G
Guy Schalnat 已提交
1180

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

1190
   png_debug(1, "in png_write_hIST");
1191

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,
1195
          png_ptr->num_palette);
1196

G
Guy Schalnat 已提交
1197 1198 1199 1200
      png_warning(png_ptr, "Invalid number of histogram entries specified");
      return;
   }

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

1212 1213
#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
    defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
A
Andreas Dilger 已提交
1214 1215 1216 1217 1218
/* 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 已提交
1219 1220 1221 1222
 *
 * 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 已提交
1223
 */
1224
png_size_t /* PRIVATE */
1225
png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
A
Andreas Dilger 已提交
1226
{
A
Andreas Dilger 已提交
1227
   png_size_t key_len;
1228
   png_charp kp, dp;
A
Andreas Dilger 已提交
1229
   int kflag;
1230
   int kwarn=0;
A
Andreas Dilger 已提交
1231

1232
   png_debug(1, "in png_check_keyword");
1233

A
Andreas Dilger 已提交
1234 1235 1236
   *new_key = NULL;

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

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

1244
   *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
1245

1246 1247 1248
   if (*new_key == NULL)
   {
      png_warning(png_ptr, "Out of memory while procesing keyword");
1249
      return ((png_size_t)0);
1250
   }
1251

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

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

A
Andreas Dilger 已提交
1270 1271 1272 1273
      else
      {
         *dp = *kp;
      }
A
Andreas Dilger 已提交
1274
   }
A
Andreas Dilger 已提交
1275
   *dp = '\0';
A
Andreas Dilger 已提交
1276

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

      while (*kp == ' ')
      {
1285 1286
         *(kp--) = '\0';
         key_len--;
A
Andreas Dilger 已提交
1287
      }
A
Andreas Dilger 已提交
1288 1289 1290
   }

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

      while (*kp == ' ')
      {
1298 1299
         kp++;
         key_len--;
A
Andreas Dilger 已提交
1300
      }
A
Andreas Dilger 已提交
1301 1302
   }

1303
   png_debug1(2, "Checking for multiple internal spaces in '%s'", kp);
A
Andreas Dilger 已提交
1304 1305 1306

   /* Remove multiple internal spaces. */
   for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
A
Andreas Dilger 已提交
1307
   {
A
Andreas Dilger 已提交
1308
      if (*kp == ' ' && kflag == 0)
A
Andreas Dilger 已提交
1309
      {
A
Andreas Dilger 已提交
1310 1311
         *(dp++) = *kp;
         kflag = 1;
A
Andreas Dilger 已提交
1312
      }
1313

A
Andreas Dilger 已提交
1314
      else if (*kp == ' ')
A
Andreas Dilger 已提交
1315 1316
      {
         key_len--;
1317
         kwarn = 1;
A
Andreas Dilger 已提交
1318
      }
1319

A
Andreas Dilger 已提交
1320 1321
      else
      {
A
Andreas Dilger 已提交
1322 1323
         *(dp++) = *kp;
         kflag = 0;
A
Andreas Dilger 已提交
1324 1325
      }
   }
A
Andreas Dilger 已提交
1326
   *dp = '\0';
1327
   if (kwarn)
1328
      png_warning(png_ptr, "extra interior spaces removed from keyword");
A
Andreas Dilger 已提交
1329 1330

   if (key_len == 0)
A
Andreas Dilger 已提交
1331
   {
1332
      png_free(png_ptr, *new_key);
1333
      png_warning(png_ptr, "Zero length keyword");
A
Andreas Dilger 已提交
1334 1335 1336 1337
   }

   if (key_len > 79)
   {
1338
      png_warning(png_ptr, "keyword length must be 1 - 79 characters");
1339
      (*new_key)[79] = '\0';
A
Andreas Dilger 已提交
1340 1341
      key_len = 79;
   }
A
Andreas Dilger 已提交
1342

1343
   return (key_len);
A
Andreas Dilger 已提交
1344 1345 1346
}
#endif

1347
#ifdef PNG_WRITE_tEXt_SUPPORTED
1348
/* Write a tEXt chunk */
1349
void /* PRIVATE */
G
Guy Schalnat 已提交
1350
png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
1351
    png_size_t text_len)
G
Guy Schalnat 已提交
1352
{
1353
   PNG_tEXt;
A
Andreas Dilger 已提交
1354
   png_size_t key_len;
1355
   png_charp new_key;
A
Andreas Dilger 已提交
1356

1357
   png_debug(1, "in png_write_tEXt");
1358

1359
   if ((key_len = png_check_keyword(png_ptr, key, &new_key))==0)
G
Guy Schalnat 已提交
1360 1361
      return;

A
Andreas Dilger 已提交
1362
   if (text == NULL || *text == '\0')
A
Andreas Dilger 已提交
1363
      text_len = 0;
1364

1365 1366
   else
      text_len = png_strlen(text);
A
Andreas Dilger 已提交
1367

1368
   /* Make sure we include the 0 after the key */
1369
   png_write_chunk_start(png_ptr, (png_bytep)png_tEXt,
1370
      (png_uint_32)(key_len + text_len + 1));
1371 1372 1373 1374
   /*
    * 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.
1375
    * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
1376
    */
1377 1378
   png_write_chunk_data(png_ptr, (png_bytep)new_key,
     (png_size_t)(key_len + 1));
1379

A
Andreas Dilger 已提交
1380
   if (text_len)
1381
      png_write_chunk_data(png_ptr, (png_bytep)text, (png_size_t)text_len);
A
Andreas Dilger 已提交
1382

G
Guy Schalnat 已提交
1383
   png_write_chunk_end(png_ptr);
A
Andreas Dilger 已提交
1384
   png_free(png_ptr, new_key);
G
Guy Schalnat 已提交
1385
}
G
Guy Schalnat 已提交
1386
#endif
G
Guy Schalnat 已提交
1387

1388
#ifdef PNG_WRITE_zTXt_SUPPORTED
1389
/* Write a compressed text chunk */
1390
void /* PRIVATE */
G
Guy Schalnat 已提交
1391
png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
1392
    png_size_t text_len, int compression)
G
Guy Schalnat 已提交
1393
{
1394
   PNG_zTXt;
A
Andreas Dilger 已提交
1395
   png_size_t key_len;
G
Guy Schalnat 已提交
1396
   char buf[1];
1397
   png_charp new_key;
1398
   compression_state comp;
G
Guy Schalnat 已提交
1399

1400
   png_debug(1, "in png_write_zTXt");
A
Andreas Dilger 已提交
1401

1402 1403 1404 1405 1406 1407
   comp.num_output_ptr = 0;
   comp.max_output_ptr = 0;
   comp.output_ptr = NULL;
   comp.input = NULL;
   comp.input_len = 0;

1408
   if ((key_len = png_check_keyword(png_ptr, key, &new_key)) == 0)
A
Andreas Dilger 已提交
1409
   {
1410
      png_free(png_ptr, new_key);
G
Guy Schalnat 已提交
1411
      return;
A
Andreas Dilger 已提交
1412
   }
A
Andreas Dilger 已提交
1413

A
Andreas Dilger 已提交
1414 1415
   if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
   {
1416
      png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
A
Andreas Dilger 已提交
1417 1418 1419 1420
      png_free(png_ptr, new_key);
      return;
   }

1421 1422
   text_len = png_strlen(text);

1423
   /* Compute the compressed data; do it now for the length */
1424 1425
   text_len = png_text_compress(png_ptr, text, text_len, compression,
       &comp);
G
Guy Schalnat 已提交
1426

1427
   /* Write start of chunk */
1428
   png_write_chunk_start(png_ptr, (png_bytep)png_zTXt,
1429
       (png_uint_32)(key_len+text_len + 2));
1430

1431
   /* Write key */
1432
   png_write_chunk_data(png_ptr, (png_bytep)new_key,
1433
       (png_size_t)(key_len + 1));
1434

1435 1436
   png_free(png_ptr, new_key);

1437
   buf[0] = (png_byte)compression;
1438

1439
   /* Write compression */
1440
   png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
1441

1442
   /* Write the compressed data */
1443
   png_write_compressed_data_out(png_ptr, &comp);
G
Guy Schalnat 已提交
1444

1445
   /* Close the chunk */
1446 1447 1448
   png_write_chunk_end(png_ptr);
}
#endif
G
Guy Schalnat 已提交
1449

1450
#ifdef PNG_WRITE_iTXt_SUPPORTED
1451
/* Write an iTXt chunk */
1452
void /* PRIVATE */
1453
png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
1454
    png_charp lang, png_charp lang_key, png_charp text)
1455 1456
{
   PNG_iTXt;
1457
   png_size_t lang_len, key_len, lang_key_len, text_len;
1458 1459
   png_charp new_lang;
   png_charp new_key = NULL;
1460 1461
   png_byte cbuf[2];
   compression_state comp;
G
Guy Schalnat 已提交
1462

1463
   png_debug(1, "in png_write_iTXt");
G
Guy Schalnat 已提交
1464

1465 1466 1467 1468 1469
   comp.num_output_ptr = 0;
   comp.max_output_ptr = 0;
   comp.output_ptr = NULL;
   comp.input = NULL;

1470
   if ((key_len = png_check_keyword(png_ptr, key, &new_key)) == 0)
1471
      return;
1472

1473
   if ((lang_len = png_check_keyword(png_ptr, lang, &new_lang)) == 0)
1474
   {
1475
      png_warning(png_ptr, "Empty language field in iTXt chunk");
1476
      new_lang = NULL;
1477
      lang_len = 0;
1478
   }
G
Guy Schalnat 已提交
1479

1480
   if (lang_key == NULL)
1481
      lang_key_len = 0;
1482

1483
   else
1484
      lang_key_len = png_strlen(lang_key);
1485 1486

   if (text == NULL)
1487
      text_len = 0;
1488

1489
   else
1490
      text_len = png_strlen(text);
G
Guy Schalnat 已提交
1491

1492
   /* Compute the compressed data; do it now for the length */
1493
   text_len = png_text_compress(png_ptr, text, text_len, compression - 2,
1494
      &comp);
G
Guy Schalnat 已提交
1495

1496

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

1500 1501 1502 1503 1504 1505 1506
   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 已提交
1507

1508
   /* We leave it to the application to meet PNG-1.0 requirements on the
1509 1510 1511 1512
    * 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.
    */
1513
   png_write_chunk_data(png_ptr, (png_bytep)new_key,
1514
       (png_size_t)(key_len + 1));
1515

1516
   /* Set the compression flag */
1517
   if (compression == PNG_ITXT_COMPRESSION_NONE ||
1518 1519
       compression == PNG_TEXT_COMPRESSION_NONE)
       cbuf[0] = 0;
1520

1521 1522
   else /* compression == PNG_ITXT_COMPRESSION_zTXt */
       cbuf[0] = 1;
1523

1524
   /* Set the compression method */
1525
   cbuf[1] = 0;
1526

1527
   png_write_chunk_data(png_ptr, cbuf, (png_size_t)2);
1528

1529
   cbuf[0] = 0;
1530 1531
   png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf),
     (png_size_t)(lang_len + 1));
1532

1533 1534
   png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf),
     (png_size_t)(lang_key_len + 1));
1535

1536
   png_write_compressed_data_out(png_ptr, &comp);
G
Guy Schalnat 已提交
1537 1538

   png_write_chunk_end(png_ptr);
1539

1540
   png_free(png_ptr, new_key);
1541
   png_free(png_ptr, new_lang);
G
Guy Schalnat 已提交
1542
}
G
Guy Schalnat 已提交
1543
#endif
G
Guy Schalnat 已提交
1544

1545
#ifdef PNG_WRITE_oFFs_SUPPORTED
1546
/* Write the oFFs chunk */
1547
void /* PRIVATE */
1548
png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
1549
    int unit_type)
G
Guy Schalnat 已提交
1550
{
1551
   PNG_oFFs;
G
Guy Schalnat 已提交
1552 1553
   png_byte buf[9];

1554
   png_debug(1, "in png_write_oFFs");
1555

A
Andreas Dilger 已提交
1556 1557
   if (unit_type >= PNG_OFFSET_LAST)
      png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
G
Guy Schalnat 已提交
1558

1559 1560
   png_save_int_32(buf, x_offset);
   png_save_int_32(buf + 4, y_offset);
G
Guy Schalnat 已提交
1561
   buf[8] = (png_byte)unit_type;
G
Guy Schalnat 已提交
1562

1563
   png_write_chunk(png_ptr, (png_bytep)png_oFFs, buf, (png_size_t)9);
G
Guy Schalnat 已提交
1564
}
G
Guy Schalnat 已提交
1565
#endif
1566
#ifdef PNG_WRITE_pCAL_SUPPORTED
1567
/* Write the pCAL chunk (described in the PNG extensions document) */
1568
void /* PRIVATE */
A
Andreas Dilger 已提交
1569 1570 1571
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)
{
1572
   PNG_pCAL;
1573
   png_size_t purpose_len, units_len, total_len;
A
Andreas Dilger 已提交
1574 1575
   png_uint_32p params_len;
   png_byte buf[10];
1576
   png_charp new_purpose;
A
Andreas Dilger 已提交
1577 1578
   int i;

1579
   png_debug1(1, "in png_write_pCAL (%d parameters)", nparams);
1580

A
Andreas Dilger 已提交
1581 1582 1583 1584
   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;
1585
   png_debug1(3, "pCAL purpose length = %d", (int)purpose_len);
A
Andreas Dilger 已提交
1586
   units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
1587
   png_debug1(3, "pCAL units length = %d", (int)units_len);
A
Andreas Dilger 已提交
1588 1589
   total_len = purpose_len + units_len + 10;

1590
   params_len = (png_uint_32p)png_malloc(png_ptr,
1591
       (png_alloc_size_t)(nparams * png_sizeof(png_uint_32)));
A
Andreas Dilger 已提交
1592 1593

   /* Find the length of each parameter, making sure we don't count the
1594 1595
    * null terminator for the last parameter.
    */
A
Andreas Dilger 已提交
1596 1597 1598
   for (i = 0; i < nparams; i++)
   {
      params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
1599
      png_debug2(3, "pCAL parameter %d length = %lu", i,
1600
          (unsigned long) params_len[i]);
A
Andreas Dilger 已提交
1601 1602 1603
      total_len += (png_size_t)params_len[i];
   }

1604
   png_debug1(3, "pCAL total length = %d", (int)total_len);
1605
   png_write_chunk_start(png_ptr, (png_bytep)png_pCAL, (png_uint_32)total_len);
1606
   png_write_chunk_data(png_ptr, (png_bytep)new_purpose,
1607
       (png_size_t)purpose_len);
A
Andreas Dilger 已提交
1608 1609 1610 1611
   png_save_int_32(buf, X0);
   png_save_int_32(buf + 4, X1);
   buf[8] = (png_byte)type;
   buf[9] = (png_byte)nparams;
1612 1613
   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 已提交
1614 1615 1616 1617 1618 1619

   png_free(png_ptr, new_purpose);

   for (i = 0; i < nparams; i++)
   {
      png_write_chunk_data(png_ptr, (png_bytep)params[i],
1620
          (png_size_t)params_len[i]);
A
Andreas Dilger 已提交
1621 1622
   }

1623
   png_free(png_ptr, params_len);
A
Andreas Dilger 已提交
1624 1625 1626 1627
   png_write_chunk_end(png_ptr);
}
#endif

1628
#ifdef PNG_WRITE_sCAL_SUPPORTED
1629
/* Write the sCAL chunk */
1630
void /* PRIVATE */
1631
png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
1632
    png_charp height)
1633 1634
{
   PNG_sCAL;
1635 1636
   png_byte buf[64];
   png_size_t wlen, hlen, total_len;
1637

1638
   png_debug(1, "in png_write_sCAL_s");
1639

1640 1641 1642
   wlen = png_strlen(width);
   hlen = png_strlen(height);
   total_len = wlen + hlen + 2;
1643

1644 1645 1646 1647 1648
   if (total_len > 64)
   {
      png_warning(png_ptr, "Can't write sCAL (buffer too small)");
      return;
   }
1649

1650
   buf[0] = (png_byte)unit;
1651 1652
   png_memcpy(buf + 1, width, wlen + 1);      /* Append the '\0' here */
   png_memcpy(buf + wlen + 2, height, hlen);  /* Do NOT append the '\0' here */
1653

1654
   png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);
1655
   png_write_chunk(png_ptr, (png_bytep)png_sCAL, buf, total_len);
1656 1657 1658
}
#endif

1659
#ifdef PNG_WRITE_pHYs_SUPPORTED
1660
/* Write the pHYs chunk */
1661
void /* PRIVATE */
A
Andreas Dilger 已提交
1662
png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
1663 1664
    png_uint_32 y_pixels_per_unit,
    int unit_type)
G
Guy Schalnat 已提交
1665
{
1666
   PNG_pHYs;
G
Guy Schalnat 已提交
1667 1668
   png_byte buf[9];

1669
   png_debug(1, "in png_write_pHYs");
1670

A
Andreas Dilger 已提交
1671 1672
   if (unit_type >= PNG_RESOLUTION_LAST)
      png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
G
Guy Schalnat 已提交
1673

A
Andreas Dilger 已提交
1674 1675
   png_save_uint_32(buf, x_pixels_per_unit);
   png_save_uint_32(buf + 4, y_pixels_per_unit);
G
Guy Schalnat 已提交
1676
   buf[8] = (png_byte)unit_type;
G
Guy Schalnat 已提交
1677

1678
   png_write_chunk(png_ptr, (png_bytep)png_pHYs, buf, (png_size_t)9);
G
Guy Schalnat 已提交
1679
}
G
Guy Schalnat 已提交
1680
#endif
G
Guy Schalnat 已提交
1681

1682
#ifdef PNG_WRITE_tIME_SUPPORTED
1683 1684 1685
/* Write the tIME chunk.  Use either png_convert_from_struct_tm()
 * or png_convert_from_time_t(), or fill in the structure yourself.
 */
1686
void /* PRIVATE */
G
Guy Schalnat 已提交
1687
png_write_tIME(png_structp png_ptr, png_timep mod_time)
G
Guy Schalnat 已提交
1688
{
1689
   PNG_tIME;
G
Guy Schalnat 已提交
1690 1691
   png_byte buf[7];

1692
   png_debug(1, "in png_write_tIME");
1693

G
Guy Schalnat 已提交
1694 1695 1696 1697 1698 1699 1700 1701
   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 已提交
1702 1703 1704 1705 1706 1707 1708
   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;

1709
   png_write_chunk(png_ptr, (png_bytep)png_tIME, buf, (png_size_t)7);
G
Guy Schalnat 已提交
1710
}
G
Guy Schalnat 已提交
1711
#endif
G
Guy Schalnat 已提交
1712

1713
/* Initializes the row writing capability of libpng */
1714
void /* PRIVATE */
G
Guy Schalnat 已提交
1715
png_write_start_row(png_structp png_ptr)
G
Guy Schalnat 已提交
1716
{
1717
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
1718
   /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1719

1720
   /* Start of interlace block */
1721
   int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1722

1723
   /* Offset to next interlace block */
1724
   int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1725

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

1729
   /* Offset to next interlace block in the y direction */
1730
   int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
1731
#endif
1732

A
Andreas Dilger 已提交
1733 1734
   png_size_t buf_size;

1735
   png_debug(1, "in png_write_start_row");
1736

1737
   buf_size = (png_size_t)(PNG_ROWBYTES(
1738
       png_ptr->usr_channels*png_ptr->usr_bit_depth, png_ptr->width) + 1);
A
Andreas Dilger 已提交
1739

1740
   /* Set up row buffer */
1741
   png_ptr->row_buf = (png_bytep)png_malloc(png_ptr,
1742
       (png_alloc_size_t)buf_size);
1743

A
Andreas Dilger 已提交
1744
   png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
G
Guy Schalnat 已提交
1745

1746
#ifdef PNG_WRITE_FILTER_SUPPORTED
1747
   /* Set up filtering buffer, if using this filter */
G
Guy Schalnat 已提交
1748
   if (png_ptr->do_filter & PNG_FILTER_SUB)
G
Guy Schalnat 已提交
1749
   {
A
Andreas Dilger 已提交
1750
      png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
1751
          (png_alloc_size_t)(png_ptr->rowbytes + 1));
1752

A
Andreas Dilger 已提交
1753
      png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
G
Guy Schalnat 已提交
1754 1755
   }

A
Andreas Dilger 已提交
1756
   /* We only need to keep the previous row if we are using one of these. */
G
Guy Schalnat 已提交
1757 1758
   if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
   {
1759 1760
      /* Set up previous row buffer */
      png_ptr->prev_row = (png_bytep)png_calloc(png_ptr,
1761
          (png_alloc_size_t)buf_size);
G
Guy Schalnat 已提交
1762 1763 1764

      if (png_ptr->do_filter & PNG_FILTER_UP)
      {
1765
         png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
1766
             (png_size_t)(png_ptr->rowbytes + 1));
1767

A
Andreas Dilger 已提交
1768
         png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
G
Guy Schalnat 已提交
1769 1770 1771 1772
      }

      if (png_ptr->do_filter & PNG_FILTER_AVG)
      {
1773
         png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
1774
             (png_alloc_size_t)(png_ptr->rowbytes + 1));
1775

A
Andreas Dilger 已提交
1776
         png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
G
Guy Schalnat 已提交
1777 1778 1779 1780
      }

      if (png_ptr->do_filter & PNG_FILTER_PAETH)
      {
1781
         png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
1782
             (png_size_t)(png_ptr->rowbytes + 1));
1783

A
Andreas Dilger 已提交
1784
         png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
G
Guy Schalnat 已提交
1785
      }
G
Guy Schalnat 已提交
1786
   }
1787
#endif /* PNG_WRITE_FILTER_SUPPORTED */
G
Guy Schalnat 已提交
1788

1789
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
1790
   /* If interlaced, we need to set up width and height of pass */
G
Guy Schalnat 已提交
1791
   if (png_ptr->interlaced)
G
Guy Schalnat 已提交
1792 1793 1794 1795
   {
      if (!(png_ptr->transformations & PNG_INTERLACE))
      {
         png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
1796
             png_pass_ystart[0]) / png_pass_yinc[0];
1797

A
Andreas Dilger 已提交
1798
         png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
1799
             png_pass_start[0]) / png_pass_inc[0];
G
Guy Schalnat 已提交
1800
      }
1801

G
Guy Schalnat 已提交
1802 1803 1804 1805 1806 1807
      else
      {
         png_ptr->num_rows = png_ptr->height;
         png_ptr->usr_width = png_ptr->width;
      }
   }
1808

G
Guy Schalnat 已提交
1809
   else
1810
#endif
G
Guy Schalnat 已提交
1811
   {
G
Guy Schalnat 已提交
1812 1813 1814
      png_ptr->num_rows = png_ptr->height;
      png_ptr->usr_width = png_ptr->width;
   }
1815

A
Andreas Dilger 已提交
1816 1817
   png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
   png_ptr->zstream.next_out = png_ptr->zbuf;
G
Guy Schalnat 已提交
1818 1819
}

A
Andreas Dilger 已提交
1820
/* Internal use only.  Called when finished processing a row of data. */
1821
void /* PRIVATE */
G
Guy Schalnat 已提交
1822
png_write_finish_row(png_structp png_ptr)
G
Guy Schalnat 已提交
1823
{
1824
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
1825
   /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1826

1827
   /* Start of interlace block */
1828
   int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1829

1830
   /* Offset to next interlace block */
1831
   int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1832

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

1836
   /* Offset to next interlace block in the y direction */
1837
   int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
1838
#endif
1839

G
Guy Schalnat 已提交
1840 1841
   int ret;

1842
   png_debug(1, "in png_write_finish_row");
1843

1844
   /* Next row */
G
Guy Schalnat 已提交
1845
   png_ptr->row_number++;
G
Guy Schalnat 已提交
1846

1847
   /* See if we are done */
G
Guy Schalnat 已提交
1848
   if (png_ptr->row_number < png_ptr->num_rows)
G
Guy Schalnat 已提交
1849
      return;
G
Guy Schalnat 已提交
1850

1851
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
1852
   /* If interlaced, go to next pass */
G
Guy Schalnat 已提交
1853 1854 1855 1856 1857 1858 1859
   if (png_ptr->interlaced)
   {
      png_ptr->row_number = 0;
      if (png_ptr->transformations & PNG_INTERLACE)
      {
         png_ptr->pass++;
      }
1860

G
Guy Schalnat 已提交
1861 1862
      else
      {
1863
         /* Loop until we find a non-zero width or height pass */
G
Guy Schalnat 已提交
1864 1865 1866
         do
         {
            png_ptr->pass++;
1867

G
Guy Schalnat 已提交
1868 1869
            if (png_ptr->pass >= 7)
               break;
1870

G
Guy Schalnat 已提交
1871
            png_ptr->usr_width = (png_ptr->width +
G
Guy Schalnat 已提交
1872 1873 1874
               png_pass_inc[png_ptr->pass] - 1 -
               png_pass_start[png_ptr->pass]) /
               png_pass_inc[png_ptr->pass];
1875

G
Guy Schalnat 已提交
1876 1877 1878 1879
            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];
1880

G
Guy Schalnat 已提交
1881 1882
            if (png_ptr->transformations & PNG_INTERLACE)
               break;
1883

G
Guy Schalnat 已提交
1884 1885 1886 1887
         } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);

      }

1888
      /* Reset the row above the image for the next pass */
G
Guy Schalnat 已提交
1889
      if (png_ptr->pass < 7)
G
Guy Schalnat 已提交
1890
      {
A
Andreas Dilger 已提交
1891
         if (png_ptr->prev_row != NULL)
1892
            png_memset(png_ptr->prev_row, 0,
1893 1894
                (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
                png_ptr->usr_bit_depth, png_ptr->width)) + 1);
1895

G
Guy Schalnat 已提交
1896
         return;
G
Guy Schalnat 已提交
1897
      }
G
Guy Schalnat 已提交
1898
   }
1899
#endif
G
Guy Schalnat 已提交
1900

1901
   /* If we get here, we've just written the last row, so we need
G
Guy Schalnat 已提交
1902 1903 1904
      to flush the compressor */
   do
   {
1905
      /* Tell the compressor we are done */
A
Andreas Dilger 已提交
1906
      ret = deflate(&png_ptr->zstream, Z_FINISH);
1907

1908
      /* Check for an error */
1909 1910
      if (ret == Z_OK)
      {
1911
         /* Check to see if we need more room */
1912 1913 1914 1915 1916 1917 1918
         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;
         }
      }
1919

1920
      else if (ret != Z_STREAM_END)
G
Guy Schalnat 已提交
1921
      {
A
Andreas Dilger 已提交
1922
         if (png_ptr->zstream.msg != NULL)
A
Andreas Dilger 已提交
1923
            png_error(png_ptr, png_ptr->zstream.msg);
G
Guy Schalnat 已提交
1924
         else
G
Guy Schalnat 已提交
1925
            png_error(png_ptr, "zlib error");
G
Guy Schalnat 已提交
1926 1927 1928
      }
   } while (ret != Z_STREAM_END);

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

A
Andreas Dilger 已提交
1936
   deflateReset(&png_ptr->zstream);
1937
   png_ptr->zstream.data_type = Z_BINARY;
G
Guy Schalnat 已提交
1938 1939
}

1940
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
1941 1942 1943 1944 1945 1946 1947
/* 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.
 */
1948
void /* PRIVATE */
G
Guy Schalnat 已提交
1949
png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
G
Guy Schalnat 已提交
1950
{
1951
   /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1952

1953
   /* Start of interlace block */
1954
   int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1955

1956
   /* Offset to next interlace block */
1957
   int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1958

1959
   png_debug(1, "in png_do_write_interlace");
1960

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

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

               if (shift == 0)
               {
                  shift = 7;
G
Guy Schalnat 已提交
1990
                  *dp++ = (png_byte)d;
G
Guy Schalnat 已提交
1991 1992
                  d = 0;
               }
1993

G
Guy Schalnat 已提交
1994 1995 1996 1997 1998
               else
                  shift--;

            }
            if (shift != 7)
G
Guy Schalnat 已提交
1999
               *dp = (png_byte)d;
2000

G
Guy Schalnat 已提交
2001 2002 2003
            break;
         }
         case 2:
G
Guy Schalnat 已提交
2004
         {
G
Guy Schalnat 已提交
2005 2006
            png_bytep sp;
            png_bytep dp;
G
Guy Schalnat 已提交
2007 2008 2009
            int shift;
            int d;
            int value;
2010 2011
            png_uint_32 i;
            png_uint_32 row_width = row_info->width;
G
Guy Schalnat 已提交
2012 2013 2014 2015

            dp = row;
            shift = 6;
            d = 0;
2016

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

               if (shift == 0)
               {
                  shift = 6;
G
Guy Schalnat 已提交
2027
                  *dp++ = (png_byte)d;
G
Guy Schalnat 已提交
2028 2029
                  d = 0;
               }
2030

G
Guy Schalnat 已提交
2031 2032 2033 2034
               else
                  shift -= 2;
            }
            if (shift != 6)
2035 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;
2053
                i += png_pass_inc[pass])
G
Guy Schalnat 已提交
2054 2055
            {
               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 2085

            /* Loop through the row, only looking at the pixels that 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

2095
               /* Next pixel */
G
Guy Schalnat 已提交
2096 2097
               dp += pixel_bytes;
            }
G
Guy Schalnat 已提交
2098
            break;
G
Guy Schalnat 已提交
2099 2100
         }
      }
2101
      /* Set new row width */
G
Guy Schalnat 已提交
2102
      row_info->width = (row_info->width +
2103 2104 2105
          png_pass_inc[pass] - 1 -
          png_pass_start[pass]) /
          png_pass_inc[pass];
2106

2107 2108
      row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
          row_info->width);
G
Guy Schalnat 已提交
2109 2110
   }
}
G
Guy Schalnat 已提交
2111
#endif
G
Guy Schalnat 已提交
2112

A
Andreas Dilger 已提交
2113 2114
/* 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
2115 2116
 * chosen filter.
 */
2117
#define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
A
Andreas Dilger 已提交
2118
#define PNG_HISHIFT 10
2119 2120
#define PNG_LOMASK ((png_uint_32)0xffffL)
#define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
2121
void /* PRIVATE */
G
Guy Schalnat 已提交
2122
png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
G
Guy Schalnat 已提交
2123
{
2124
   png_bytep best_row;
2125
#ifdef PNG_WRITE_FILTER_SUPPORTED
2126
   png_bytep prev_row, row_buf;
A
Andreas Dilger 已提交
2127
   png_uint_32 mins, bpp;
2128
   png_byte filter_to_do = png_ptr->do_filter;
2129
   png_uint_32 row_bytes = row_info->rowbytes;
2130
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2131
   int num_p_filters = (int)png_ptr->num_prev_filters;
2132
#endif
2133 2134 2135 2136

   png_debug(1, "in png_write_find_filter");

#ifndef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2137
  if (png_ptr->row_number == 0 && filter_to_do == PNG_ALL_FILTERS)
2138 2139 2140 2141
  {
      /* These will never be selected so we need not test them. */
      filter_to_do &= ~(PNG_FILTER_UP | PNG_FILTER_PAETH);
  }
2142
#endif
G
Guy Schalnat 已提交
2143

2144
   /* Find out how many bytes offset each pixel is */
2145
   bpp = (row_info->pixel_depth + 7) >> 3;
G
Guy Schalnat 已提交
2146 2147

   prev_row = png_ptr->prev_row;
2148 2149
#endif
   best_row = png_ptr->row_buf;
2150
#ifdef PNG_WRITE_FILTER_SUPPORTED
2151
   row_buf = best_row;
A
Andreas Dilger 已提交
2152 2153 2154 2155
   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
2156
    * from zero, using anything >= 128 as negative numbers.  This is known
A
Andreas Dilger 已提交
2157
    * as the "minimum sum of absolute differences" heuristic.  Other
2158
    * heuristics are the "weighted minimum sum of absolute differences"
A
Andreas Dilger 已提交
2159
    * (experimental and can in theory improve compression), and the "zlib
2160 2161 2162
    * 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 已提交
2163
    * computationally expensive).
2164 2165 2166 2167 2168 2169 2170 2171 2172
    *
    * 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 已提交
2173
    */
G
Guy Schalnat 已提交
2174

2175

G
Guy Schalnat 已提交
2176
   /* We don't need to test the 'no filter' case if this is the only filter
A
Andreas Dilger 已提交
2177 2178
    * that has been chosen, as it doesn't actually do anything to the data.
    */
2179
   if ((filter_to_do & PNG_FILTER_NONE) && filter_to_do != PNG_FILTER_NONE)
G
Guy Schalnat 已提交
2180
   {
G
Guy Schalnat 已提交
2181 2182
      png_bytep rp;
      png_uint_32 sum = 0;
2183
      png_uint_32 i;
A
Andreas Dilger 已提交
2184
      int v;
G
Guy Schalnat 已提交
2185

2186
      for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
G
Guy Schalnat 已提交
2187 2188 2189 2190
      {
         v = *rp;
         sum += (v < 128) ? v : 256 - v;
      }
A
Andreas Dilger 已提交
2191

2192
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2193 2194 2195
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
         png_uint_32 sumhi, sumlo;
2196
         int j;
A
Andreas Dilger 已提交
2197 2198 2199 2200
         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 */
2201
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2202
         {
2203
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
A
Andreas Dilger 已提交
2204
            {
2205
               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2206
                   PNG_WEIGHT_SHIFT;
2207

2208
               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2209
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2210 2211 2212 2213 2214 2215 2216 2217
            }
         }

         /* 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]) >>
2218
             PNG_COST_SHIFT;
2219

A
Andreas Dilger 已提交
2220
         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
2221
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2222 2223 2224

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2225

A
Andreas Dilger 已提交
2226 2227 2228 2229
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
      }
#endif
G
Guy Schalnat 已提交
2230 2231
      mins = sum;
   }
G
Guy Schalnat 已提交
2232

2233
   /* Sub filter */
2234
   if (filter_to_do == PNG_FILTER_SUB)
2235
   /* It's the only filter so no testing is needed */
2236 2237
   {
      png_bytep rp, lp, dp;
2238
      png_uint_32 i;
2239

2240 2241 2242 2243 2244
      for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
           i++, rp++, dp++)
      {
         *dp = *rp;
      }
2245

2246
      for (lp = row_buf + 1; i < row_bytes;
2247 2248 2249 2250
         i++, rp++, lp++, dp++)
      {
         *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
      }
2251

2252 2253 2254 2255
      best_row = png_ptr->sub_row;
   }

   else if (filter_to_do & PNG_FILTER_SUB)
G
Guy Schalnat 已提交
2256 2257
   {
      png_bytep rp, dp, lp;
A
Andreas Dilger 已提交
2258
      png_uint_32 sum = 0, lmins = mins;
2259
      png_uint_32 i;
A
Andreas Dilger 已提交
2260 2261
      int v;

2262
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2263
      /* We temporarily increase the "minimum sum" by the factor we
A
Andreas Dilger 已提交
2264 2265 2266 2267 2268
       * 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)
      {
2269
         int j;
A
Andreas Dilger 已提交
2270 2271 2272 2273
         png_uint_32 lmhi, lmlo;
         lmlo = lmins & PNG_LOMASK;
         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;

2274
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2275
         {
2276
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
A
Andreas Dilger 已提交
2277
            {
2278
               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
A
Andreas Dilger 已提交
2279
                  PNG_WEIGHT_SHIFT;
2280

2281
               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
A
Andreas Dilger 已提交
2282 2283 2284 2285 2286
                  PNG_WEIGHT_SHIFT;
            }
         }

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

A
Andreas Dilger 已提交
2289
         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2290
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2291 2292 2293

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
2294

A
Andreas Dilger 已提交
2295 2296 2297 2298
         else
            lmins = (lmhi << PNG_HISHIFT) + lmlo;
      }
#endif
G
Guy Schalnat 已提交
2299

G
Guy Schalnat 已提交
2300 2301 2302 2303
      for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
           i++, rp++, dp++)
      {
         v = *dp = *rp;
G
Guy Schalnat 已提交
2304

G
Guy Schalnat 已提交
2305 2306
         sum += (v < 128) ? v : 256 - v;
      }
2307
      for (lp = row_buf + 1; i < row_bytes;
2308
         i++, rp++, lp++, dp++)
G
Guy Schalnat 已提交
2309 2310 2311 2312
      {
         v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);

         sum += (v < 128) ? v : 256 - v;
A
Andreas Dilger 已提交
2313 2314 2315 2316 2317

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

2318
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2319 2320
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2321
         int j;
A
Andreas Dilger 已提交
2322 2323 2324 2325
         png_uint_32 sumhi, sumlo;
         sumlo = sum & PNG_LOMASK;
         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;

2326
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2327
         {
2328
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
A
Andreas Dilger 已提交
2329
            {
2330
               sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
2331
                   PNG_WEIGHT_SHIFT;
2332

2333
               sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
2334
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2335 2336 2337 2338
            }
         }

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

A
Andreas Dilger 已提交
2341
         sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2342
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2343 2344 2345

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2346

A
Andreas Dilger 已提交
2347 2348
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
G
Guy Schalnat 已提交
2349
      }
A
Andreas Dilger 已提交
2350 2351
#endif

G
Guy Schalnat 已提交
2352 2353 2354 2355 2356
      if (sum < mins)
      {
         mins = sum;
         best_row = png_ptr->sub_row;
      }
G
Guy Schalnat 已提交
2357 2358
   }

2359
   /* Up filter */
2360 2361 2362
   if (filter_to_do == PNG_FILTER_UP)
   {
      png_bytep rp, dp, pp;
2363
      png_uint_32 i;
2364 2365

      for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
2366 2367
          pp = prev_row + 1; i < row_bytes;
          i++, rp++, pp++, dp++)
2368 2369 2370 2371 2372 2373 2374
      {
         *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 已提交
2375 2376
   {
      png_bytep rp, dp, pp;
A
Andreas Dilger 已提交
2377
      png_uint_32 sum = 0, lmins = mins;
2378
      png_uint_32 i;
A
Andreas Dilger 已提交
2379 2380
      int v;

2381

2382
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2383 2384
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2385
         int j;
A
Andreas Dilger 已提交
2386 2387 2388 2389
         png_uint_32 lmhi, lmlo;
         lmlo = lmins & PNG_LOMASK;
         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;

2390
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2391
         {
2392
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
A
Andreas Dilger 已提交
2393
            {
2394
               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2395
                   PNG_WEIGHT_SHIFT;
2396

2397
               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2398
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2399 2400 2401 2402
            }
         }

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

A
Andreas Dilger 已提交
2405
         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
2406
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2407 2408 2409

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
2410

A
Andreas Dilger 已提交
2411 2412 2413 2414
         else
            lmins = (lmhi << PNG_HISHIFT) + lmlo;
      }
#endif
G
Guy Schalnat 已提交
2415

G
Guy Schalnat 已提交
2416
      for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
2417
          pp = prev_row + 1; i < row_bytes; i++)
G
Guy Schalnat 已提交
2418
      {
2419
         v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
G
Guy Schalnat 已提交
2420 2421

         sum += (v < 128) ? v : 256 - v;
A
Andreas Dilger 已提交
2422 2423 2424

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

2427
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2428 2429
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2430
         int j;
A
Andreas Dilger 已提交
2431 2432 2433 2434
         png_uint_32 sumhi, sumlo;
         sumlo = sum & PNG_LOMASK;
         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;

2435
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2436
         {
2437
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
A
Andreas Dilger 已提交
2438
            {
2439
               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2440
                   PNG_WEIGHT_SHIFT;
2441

2442
               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2443
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2444 2445 2446 2447
            }
         }

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

A
Andreas Dilger 已提交
2450
         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
2451
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2452 2453 2454

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2455

A
Andreas Dilger 已提交
2456 2457 2458 2459 2460
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
      }
#endif

G
Guy Schalnat 已提交
2461 2462 2463 2464 2465 2466 2467
      if (sum < mins)
      {
         mins = sum;
         best_row = png_ptr->up_row;
      }
   }

2468
   /* Avg filter */
2469 2470 2471
   if (filter_to_do == PNG_FILTER_AVG)
   {
      png_bytep rp, dp, pp, lp;
2472
      png_uint_32 i;
2473

2474
      for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
2475
           pp = prev_row + 1; i < bpp; i++)
2476
      {
2477
         *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
2478
      }
2479

2480
      for (lp = row_buf + 1; i < row_bytes; i++)
2481
      {
2482 2483
         *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
                 & 0xff);
2484 2485 2486 2487 2488
      }
      best_row = png_ptr->avg_row;
   }

   else if (filter_to_do & PNG_FILTER_AVG)
G
Guy Schalnat 已提交
2489
   {
G
Guy Schalnat 已提交
2490
      png_bytep rp, dp, pp, lp;
A
Andreas Dilger 已提交
2491
      png_uint_32 sum = 0, lmins = mins;
2492
      png_uint_32 i;
A
Andreas Dilger 已提交
2493 2494
      int v;

2495
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2496 2497
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2498
         int j;
A
Andreas Dilger 已提交
2499 2500 2501 2502
         png_uint_32 lmhi, lmlo;
         lmlo = lmins & PNG_LOMASK;
         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;

2503
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2504
         {
2505
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
A
Andreas Dilger 已提交
2506
            {
2507
               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2508
                   PNG_WEIGHT_SHIFT;
2509

2510
               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2511
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2512 2513 2514 2515
            }
         }

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

A
Andreas Dilger 已提交
2518
         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
2519
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2520 2521 2522

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
2523

A
Andreas Dilger 已提交
2524 2525 2526 2527
         else
            lmins = (lmhi << PNG_HISHIFT) + lmlo;
      }
#endif
G
Guy Schalnat 已提交
2528

G
Guy Schalnat 已提交
2529
      for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
2530
           pp = prev_row + 1; i < bpp; i++)
G
Guy Schalnat 已提交
2531
      {
2532
         v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
G
Guy Schalnat 已提交
2533

G
Guy Schalnat 已提交
2534 2535
         sum += (v < 128) ? v : 256 - v;
      }
2536

2537
      for (lp = row_buf + 1; i < row_bytes; i++)
G
Guy Schalnat 已提交
2538
      {
2539
         v = *dp++ =
2540
             (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
G
Guy Schalnat 已提交
2541

G
Guy Schalnat 已提交
2542
         sum += (v < 128) ? v : 256 - v;
A
Andreas Dilger 已提交
2543 2544 2545

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

2548
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2549 2550
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2551
         int j;
A
Andreas Dilger 已提交
2552 2553 2554 2555
         png_uint_32 sumhi, sumlo;
         sumlo = sum & PNG_LOMASK;
         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;

2556
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2557
         {
2558
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
A
Andreas Dilger 已提交
2559
            {
2560
               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2561
                   PNG_WEIGHT_SHIFT;
2562

2563
               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2564
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2565 2566 2567 2568
            }
         }

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

A
Andreas Dilger 已提交
2571
         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
2572
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2573 2574 2575

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2576

A
Andreas Dilger 已提交
2577 2578 2579 2580 2581
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
      }
#endif

G
Guy Schalnat 已提交
2582 2583 2584 2585 2586 2587
      if (sum < mins)
      {
         mins = sum;
         best_row = png_ptr->avg_row;
      }
   }
G
Guy Schalnat 已提交
2588

A
Andreas Dilger 已提交
2589
   /* Paeth filter */
2590 2591 2592
   if (filter_to_do == PNG_FILTER_PAETH)
   {
      png_bytep rp, dp, pp, cp, lp;
2593
      png_uint_32 i;
2594

2595
      for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
2596
          pp = prev_row + 1; i < bpp; i++)
2597
      {
2598
         *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
2599 2600
      }

2601
      for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
2602 2603 2604
      {
         int a, b, c, pa, pb, pc, p;

2605 2606 2607
         b = *pp++;
         c = *cp++;
         a = *lp++;
2608

2609 2610
         p = b - c;
         pc = a - c;
2611 2612

#ifdef PNG_USE_ABS
2613 2614 2615
         pa = abs(p);
         pb = abs(pc);
         pc = abs(p + pc);
2616
#else
2617 2618 2619
         pa = p < 0 ? -p : p;
         pb = pc < 0 ? -pc : pc;
         pc = (p + pc) < 0 ? -(p + pc) : p + pc;
2620 2621 2622 2623
#endif

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

2624
         *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
2625 2626 2627 2628 2629
      }
      best_row = png_ptr->paeth_row;
   }

   else if (filter_to_do & PNG_FILTER_PAETH)
G
Guy Schalnat 已提交
2630 2631
   {
      png_bytep rp, dp, pp, cp, lp;
A
Andreas Dilger 已提交
2632
      png_uint_32 sum = 0, lmins = mins;
2633
      png_uint_32 i;
A
Andreas Dilger 已提交
2634 2635
      int v;

2636
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2637 2638
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2639
         int j;
A
Andreas Dilger 已提交
2640 2641 2642 2643
         png_uint_32 lmhi, lmlo;
         lmlo = lmins & PNG_LOMASK;
         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;

2644
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2645
         {
2646
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
A
Andreas Dilger 已提交
2647
            {
2648
               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2649
                   PNG_WEIGHT_SHIFT;
2650

2651
               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2652
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2653 2654 2655 2656
            }
         }

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

A
Andreas Dilger 已提交
2659
         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2660
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2661 2662 2663

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
2664

A
Andreas Dilger 已提交
2665 2666 2667 2668
         else
            lmins = (lmhi << PNG_HISHIFT) + lmlo;
      }
#endif
G
Guy Schalnat 已提交
2669

G
Guy Schalnat 已提交
2670
      for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
2671
          pp = prev_row + 1; i < bpp; i++)
G
Guy Schalnat 已提交
2672
      {
2673
         v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
G
Guy Schalnat 已提交
2674

G
Guy Schalnat 已提交
2675 2676
         sum += (v < 128) ? v : 256 - v;
      }
2677

2678
      for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
G
Guy Schalnat 已提交
2679 2680
      {
         int a, b, c, pa, pb, pc, p;
G
Guy Schalnat 已提交
2681

2682 2683 2684
         b = *pp++;
         c = *cp++;
         a = *lp++;
2685 2686

#ifndef PNG_SLOW_PAETH
2687 2688
         p = b - c;
         pc = a - c;
2689
#ifdef PNG_USE_ABS
2690 2691 2692
         pa = abs(p);
         pb = abs(pc);
         pc = abs(p + pc);
2693
#else
2694 2695 2696
         pa = p < 0 ? -p : p;
         pb = pc < 0 ? -pc : pc;
         pc = (p + pc) < 0 ? -(p + pc) : p + pc;
2697 2698 2699
#endif
         p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
#else /* PNG_SLOW_PAETH */
2700
         p = a + b - c;
2701 2702 2703
         pa = abs(p - a);
         pb = abs(p - b);
         pc = abs(p - c);
G
Guy Schalnat 已提交
2704 2705 2706 2707 2708 2709
         if (pa <= pb && pa <= pc)
            p = a;
         else if (pb <= pc)
            p = b;
         else
            p = c;
2710
#endif /* PNG_SLOW_PAETH */
G
Guy Schalnat 已提交
2711

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

G
Guy Schalnat 已提交
2714
         sum += (v < 128) ? v : 256 - v;
A
Andreas Dilger 已提交
2715 2716 2717

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

2720
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2721 2722
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2723
         int j;
A
Andreas Dilger 已提交
2724 2725 2726 2727
         png_uint_32 sumhi, sumlo;
         sumlo = sum & PNG_LOMASK;
         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;

2728
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2729
         {
2730
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
A
Andreas Dilger 已提交
2731
            {
2732
               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2733
                   PNG_WEIGHT_SHIFT;
2734

2735
               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2736
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2737 2738 2739 2740
            }
         }

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

A
Andreas Dilger 已提交
2743
         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2744
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2745 2746 2747

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2748

A
Andreas Dilger 已提交
2749 2750 2751 2752 2753
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
      }
#endif

G
Guy Schalnat 已提交
2754 2755 2756 2757
      if (sum < mins)
      {
         best_row = png_ptr->paeth_row;
      }
G
Guy Schalnat 已提交
2758
   }
2759
#endif /* PNG_WRITE_FILTER_SUPPORTED */
A
Andreas Dilger 已提交
2760
   /* Do the actual writing of the filtered row data from the chosen filter. */
2761

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

2764
#ifdef PNG_WRITE_FILTER_SUPPORTED
2765
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2766 2767 2768
   /* Save the type of filter we picked this time for future calculations */
   if (png_ptr->num_prev_filters > 0)
   {
2769
      int j;
2770

2771
      for (j = 1; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2772
      {
2773
         png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
A
Andreas Dilger 已提交
2774
      }
2775
      png_ptr->prev_filters[j] = best_row[0];
A
Andreas Dilger 已提交
2776 2777
   }
#endif
2778
#endif /* PNG_WRITE_FILTER_SUPPORTED */
G
Guy Schalnat 已提交
2779
}
G
Guy Schalnat 已提交
2780

G
Guy Schalnat 已提交
2781

A
Andreas Dilger 已提交
2782
/* Do the actual writing of a previously filtered row. */
2783
void /* PRIVATE */
G
Guy Schalnat 已提交
2784 2785
png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
{
2786
   png_debug(1, "in png_write_filtered_row");
2787

2788
   png_debug1(2, "filter = %d", filtered_row[0]);
2789
   /* Set up the zlib input buffer */
2790

A
Andreas Dilger 已提交
2791 2792
   png_ptr->zstream.next_in = filtered_row;
   png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
2793
   /* Repeat until we have compressed all the data */
G
Guy Schalnat 已提交
2794
   do
G
Guy Schalnat 已提交
2795
   {
2796
      int ret; /* Return of zlib */
G
Guy Schalnat 已提交
2797

2798
      /* Compress the data */
A
Andreas Dilger 已提交
2799
      ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
2800

2801
      /* Check for compression errors */
G
Guy Schalnat 已提交
2802 2803
      if (ret != Z_OK)
      {
A
Andreas Dilger 已提交
2804
         if (png_ptr->zstream.msg != NULL)
A
Andreas Dilger 已提交
2805
            png_error(png_ptr, png_ptr->zstream.msg);
2806

G
Guy Schalnat 已提交
2807 2808 2809
         else
            png_error(png_ptr, "zlib error");
      }
G
Guy Schalnat 已提交
2810

2811
      /* See if it is time to write another IDAT */
A
Andreas Dilger 已提交
2812
      if (!(png_ptr->zstream.avail_out))
G
Guy Schalnat 已提交
2813
      {
2814
         /* Write the IDAT and reset the zlib output buffer */
G
Guy Schalnat 已提交
2815
         png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
A
Andreas Dilger 已提交
2816 2817
         png_ptr->zstream.next_out = png_ptr->zbuf;
         png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
G
Guy Schalnat 已提交
2818
      }
2819
   /* Repeat until all data has been compressed */
A
Andreas Dilger 已提交
2820
   } while (png_ptr->zstream.avail_in);
G
Guy Schalnat 已提交
2821

2822
   /* Swap the current and previous rows */
A
Andreas Dilger 已提交
2823
   if (png_ptr->prev_row != NULL)
G
Guy Schalnat 已提交
2824 2825 2826 2827 2828 2829 2830 2831
   {
      png_bytep tptr;

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

2832
   /* Finish row - updates counters and flushes zlib if last row */
G
Guy Schalnat 已提交
2833
   png_write_finish_row(png_ptr);
G
Guy Schalnat 已提交
2834

2835
#ifdef PNG_WRITE_FLUSH_SUPPORTED
G
Guy Schalnat 已提交
2836 2837 2838 2839 2840 2841
   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 已提交
2842
   }
2843
#endif
G
Guy Schalnat 已提交
2844
}
2845
#endif /* PNG_WRITE_SUPPORTED */