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

A
Andreas Dilger 已提交
2
/* pngwutil.c - utilities to write a PNG file
3
 *
4
 * Last changed in libpng 1.5.0 [August 11, 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
95 96
png_write_chunk(png_structp png_ptr, png_const_bytep chunk_name,
   png_const_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
110
png_write_chunk_start(png_structp png_ptr, png_const_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
152 153
png_write_chunk_data(png_structp png_ptr, png_const_bytep data,
    png_size_t length)
G
Guy Schalnat 已提交
154
{
155 156 157
   /* Write the data, and run the CRC over it */
   if (png_ptr == NULL)
      return;
158

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

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

175 176
   if (png_ptr == NULL) return;

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

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

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

190
#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
191
/* This pair of functions encapsulates the operation of (a) compressing a
192 193 194 195 196 197 198
 * 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
{
199
   png_const_bytep input;   /* The uncompressed input data */
200 201 202
   int input_len;   /* Its length */
   int num_output_ptr; /* Number of output pointers used */
   int max_output_ptr; /* Size of output_ptr */
203
   png_bytep *output_ptr; /* Array of pointers to output */
204 205
} compression_state;

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

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

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

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

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

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

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

275
      /* Check to see if we need more room */
276
      if (!(png_ptr->zstream.avail_out))
277
      {
278
         /* Make sure the output array has room */
279 280 281 282 283 284 285 286
         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)
            {
287
               png_bytepp old_ptr;
288 289

               old_ptr = comp->output_ptr;
290
               comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
291 292
                   (png_alloc_size_t)
                   (comp->max_output_ptr * png_sizeof(png_charpp)));
293
               png_memcpy(comp->output_ptr, old_ptr, old_max
294
                   * png_sizeof(png_charp));
295 296 297
               png_free(png_ptr, old_ptr);
            }
            else
298
               comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
299 300
                   (png_alloc_size_t)
                   (comp->max_output_ptr * png_sizeof(png_charp)));
301 302
         }

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

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

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

324
      if (ret == Z_OK)
325
      {
326
         /* Check to see if we need more room */
327
         if (!(png_ptr->zstream.avail_out))
328
         {
329
            /* Check to make sure our output array has room */
330
            if (comp->num_output_ptr >= comp->max_output_ptr)
331
            {
332 333 334 335 336 337
               int old_max;

               old_max = comp->max_output_ptr;
               comp->max_output_ptr = comp->num_output_ptr + 4;
               if (comp->output_ptr != NULL)
               {
338
                  png_bytepp old_ptr;
339 340 341

                  old_ptr = comp->output_ptr;
                  /* This could be optimized to realloc() */
342
                  comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
343 344
                      (png_alloc_size_t)(comp->max_output_ptr *
                      png_sizeof(png_charp)));
345
                  png_memcpy(comp->output_ptr, old_ptr,
346
                      old_max * png_sizeof(png_charp));
347 348
                  png_free(png_ptr, old_ptr);
               }
349

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

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

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

364
            comp->num_output_ptr++;
365

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

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

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

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

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

396
   /* Handle the no-compression case */
397 398
   if (comp->input)
   {
399
      png_write_chunk_data(png_ptr, comp->input, (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, 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_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 */
638 639
png_write_PLTE(png_structp png_ptr, png_const_colorp palette,
    png_uint_32 num_pal)
G
Guy Schalnat 已提交
640
{
641
   PNG_PLTE;
A
Andreas Dilger 已提交
642
   png_uint_32 i;
643
   png_const_colorp pal_ptr;
G
Guy Schalnat 已提交
644 645
   png_byte buf[3];

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

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

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

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

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

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

677
   png_write_chunk_start(png_ptr, png_PLTE, (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_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_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_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_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 812
png_write_iCCP(png_structp png_ptr, png_const_charp name, int compression_type,
    png_const_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_const_bytep)profile    ))<<24) |
          ((*( (png_const_bytep)profile + 1))<<16) |
          ((*( (png_const_bytep)profile + 2))<< 8) |
          ((*( (png_const_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_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_const_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_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, &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 */
974
png_write_sBIT(png_structp png_ptr, png_const_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_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_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 1069
png_write_tRNS(png_structp png_ptr, png_const_bytep trans_alpha,
    png_const_color_16p tran, 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_tRNS, trans_alpha, (png_size_t)num_trans);
G
Guy Schalnat 已提交
1086
   }
1087

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

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

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

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

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

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

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

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

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

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

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

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

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

1191
   if (num_hist > (int)png_ptr->num_palette)
G
Guy Schalnat 已提交
1192
   {
1193
      png_debug2(3, "num_hist = %d, num_palette = %d", num_hist,
1194
          png_ptr->num_palette);
1195

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

A
Andreas Dilger 已提交
1379
   if (text_len)
1380 1381
      png_write_chunk_data(png_ptr, (png_const_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 */
1391
png_write_zTXt(png_structp png_ptr, png_const_charp key, png_const_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;
1396
   png_byte buf;
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_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 = (png_byte)compression;
1438

1439
   /* Write compression */
1440
   png_write_chunk_data(png_ptr, &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 1454
png_write_iTXt(png_structp png_ptr, int compression, png_const_charp key,
    png_const_charp lang, png_const_charp lang_key, png_const_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
   png_write_chunk_start(png_ptr, png_iTXt, (png_uint_32)(
1501 1502 1503 1504 1505
        5 /* comp byte, comp flag, terminators for key, lang and lang_key */
        + key_len
        + lang_len
        + lang_key_len
        + text_len));
G
Guy Schalnat 已提交
1506

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

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

1519 1520
   else /* compression == PNG_ITXT_COMPRESSION_zTXt */
       cbuf[0] = 1;
1521

1522
   /* Set the compression method */
1523
   cbuf[1] = 0;
1524

1525
   png_write_chunk_data(png_ptr, cbuf, (png_size_t)2);
1526

1527
   cbuf[0] = 0;
1528
   png_write_chunk_data(png_ptr, (new_lang ? (png_const_bytep)new_lang : cbuf),
1529
     (png_size_t)(lang_len + 1));
1530

1531
   png_write_chunk_data(png_ptr, (lang_key ? (png_const_bytep)lang_key : cbuf),
1532
     (png_size_t)(lang_key_len + 1));
1533

1534
   png_write_compressed_data_out(png_ptr, &comp);
G
Guy Schalnat 已提交
1535 1536

   png_write_chunk_end(png_ptr);
1537

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

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

1552
   png_debug(1, "in png_write_oFFs");
1553

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

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

1561
   png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
G
Guy Schalnat 已提交
1562
}
G
Guy Schalnat 已提交
1563
#endif
1564
#ifdef PNG_WRITE_pCAL_SUPPORTED
1565
/* Write the pCAL chunk (described in the PNG extensions document) */
1566
void /* PRIVATE */
A
Andreas Dilger 已提交
1567
png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
1568 1569
   png_int_32 X1, int type, int nparams, png_const_charp units,
   png_charpp params)
A
Andreas Dilger 已提交
1570
{
1571
   PNG_pCAL;
1572
   png_size_t purpose_len, units_len, total_len;
A
Andreas Dilger 已提交
1573 1574
   png_uint_32p params_len;
   png_byte buf[10];
1575
   png_charp new_purpose;
A
Andreas Dilger 已提交
1576 1577
   int i;

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

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

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

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

1603
   png_debug1(3, "pCAL total length = %d", (int)total_len);
1604 1605
   png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
   png_write_chunk_data(png_ptr, (png_const_bytep)new_purpose,
1606
       (png_size_t)purpose_len);
A
Andreas Dilger 已提交
1607 1608 1609 1610
   png_save_int_32(buf, X0);
   png_save_int_32(buf + 4, X1);
   buf[8] = (png_byte)type;
   buf[9] = (png_byte)nparams;
1611
   png_write_chunk_data(png_ptr, buf, (png_size_t)10);
1612
   png_write_chunk_data(png_ptr, (png_const_bytep)units, (png_size_t)units_len);
A
Andreas Dilger 已提交
1613 1614 1615 1616 1617

   png_free(png_ptr, new_purpose);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

A
Andreas Dilger 已提交
1732 1733
   png_size_t buf_size;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

G
Guy Schalnat 已提交
1839 1840
   int ret;

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

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

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

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

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

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

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

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

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

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

      }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

G
Guy Schalnat 已提交
2030 2031 2032 2033
               else
                  shift -= 2;
            }
            if (shift != 6)
2034 2035
               *dp = (png_byte)d;

G
Guy Schalnat 已提交
2036 2037 2038 2039
            break;
         }
         case 4:
         {
G
Guy Schalnat 已提交
2040 2041
            png_bytep sp;
            png_bytep dp;
G
Guy Schalnat 已提交
2042
            int shift;
G
Guy Schalnat 已提交
2043 2044
            int d;
            int value;
2045 2046
            png_uint_32 i;
            png_uint_32 row_width = row_info->width;
G
Guy Schalnat 已提交
2047 2048 2049 2050

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

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

2079
            /* Start at the beginning */
G
Guy Schalnat 已提交
2080
            dp = row;
2081
            /* Find out how many bytes each pixel takes up */
G
Guy Schalnat 已提交
2082
            pixel_bytes = (row_info->pixel_depth >> 3);
2083 2084

            /* Loop through the row, only looking at the pixels that matter */
2085
            for (i = png_pass_start[pass]; i < row_width;
G
Guy Schalnat 已提交
2086 2087
               i += png_pass_inc[pass])
            {
2088
               /* Find out where the original pixel is */
2089
               sp = row + (png_size_t)i * pixel_bytes;
2090
               /* Move the pixel */
G
Guy Schalnat 已提交
2091
               if (dp != sp)
G
Guy Schalnat 已提交
2092
                  png_memcpy(dp, sp, pixel_bytes);
2093

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

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

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

   png_debug(1, "in png_write_find_filter");

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

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

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

2174

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

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

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

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

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

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

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2224

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

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

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

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

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

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

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

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

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

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

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

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
2293

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

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

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

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

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

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

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

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

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

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

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2345

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

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

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

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

2380

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

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

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

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

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

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
2409

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

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

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

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

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

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

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

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

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

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2454

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

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

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

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

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

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

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

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

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

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

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

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
2522

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

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

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

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

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

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

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

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

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

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

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

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2575

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
2663

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

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

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

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

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

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

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

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

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

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

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

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

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

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

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2747

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

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

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

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

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

G
Guy Schalnat 已提交
2780

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

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

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

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

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

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

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

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

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

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

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