pngwutil.c 84.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.3 [(PENDING RELEASE)]
5
 * Copyright (c) 1998-2011 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;
100

A
Andreas Dilger 已提交
101
   png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
102
   png_write_chunk_data(png_ptr, data, (png_size_t)length);
A
Andreas Dilger 已提交
103
   png_write_chunk_end(png_ptr);
G
Guy Schalnat 已提交
104 105
}

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

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

   if (png_ptr == NULL)
      return;

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

129
   /* Write the length and the chunk name */
A
Andreas Dilger 已提交
130
   png_save_uint_32(buf, length);
131
   png_memcpy(buf + 4, chunk_name, 4);
132
   png_write_data(png_ptr, buf, (png_size_t)8);
133

134
   /* Put the chunk name into png_ptr->chunk_name */
135
   png_memcpy(png_ptr->chunk_name, chunk_name, 4);
136

137
   /* Reset the crc and run it over the chunk name */
G
Guy Schalnat 已提交
138
   png_reset_crc(png_ptr);
139

140 141 142 143 144 145 146 147
   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 已提交
148 149
}

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

A
Andreas Dilger 已提交
163
   if (data != NULL && length > 0)
G
Guy Schalnat 已提交
164
   {
G
Guy Schalnat 已提交
165
      png_write_data(png_ptr, data, length);
166

167
      /* Update the CRC after writing the data,
168 169 170
       * in case that the user I/O routine alters it.
       */
      png_calculate_crc(png_ptr, data, length);
G
Guy Schalnat 已提交
171 172 173
   }
}

A
Andreas Dilger 已提交
174
/* Finish a chunk started with png_write_chunk_start(). */
175
void PNGAPI
G
Guy Schalnat 已提交
176
png_write_chunk_end(png_structp png_ptr)
G
Guy Schalnat 已提交
177
{
A
Andreas Dilger 已提交
178 179
   png_byte buf[4];

180 181
   if (png_ptr == NULL) return;

182 183 184 185 186 187 188
#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

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

192
   png_write_data(png_ptr, buf, (png_size_t)4);
G
Guy Schalnat 已提交
193 194
}

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

211
/* Compress given text into storage in the png_ptr structure */
212
static int /* PRIVATE */
213
png_text_compress(png_structp png_ptr,
214
    png_const_charp text, png_size_t text_len, int compression,
215
    compression_state *comp)
216 217 218
{
   int ret;

219 220
   comp->num_output_ptr = 0;
   comp->max_output_ptr = 0;
221 222
   comp->output_ptr = NULL;
   comp->input = NULL;
223
   comp->input_len = 0;
224

225
   /* We may just want to pass the text right through */
226 227
   if (compression == PNG_TEXT_COMPRESSION_NONE)
   {
228
      comp->input = (png_const_bytep)text;
229 230
      comp->input_len = text_len;
      return((int)text_len);
231 232 233 234
   }

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

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
   if (!(png_ptr->mode & PNG_ZLIB_READY_FOR_ZTXT))
     {
        /* Free memory from previously opened zstream */
        deflateEnd(&png_ptr->zstream);

        /* Initialize the compressor for zTXt compression. */
        ret = deflateInit2(&png_ptr->zstream, png_ptr->zlib_text_level,
            png_ptr->zlib_text_method, png_ptr->zlib_text_window_bits,
            png_ptr->zlib_text_mem_level, png_ptr->zlib_text_strategy);

        if (ret != Z_OK)
        {
           if (ret == Z_VERSION_ERROR)
              png_error(png_ptr,
              "zlib failed to initialize compressor for text-- version error");

           if (ret == Z_STREAM_ERROR)
              png_error(png_ptr,
277 278
             "zlib failed to initialize compressor for text-- stream error");

279 280
           if (ret == Z_MEM_ERROR)
              png_error(png_ptr,
281 282
             "zlib failed to initialize compressor for text-- mem error");

283 284 285
           png_error(png_ptr, "zlib failed to initialize compressor for text");
      }
      png_ptr->mode |= PNG_ZLIB_READY_FOR_ZTXT;
286 287
   }

288
   /* Set up the compression buffers */
289

290
   /* TODO: the following cast hides a potential overflow problem. */
291
   png_ptr->zstream.avail_in = (uInt)text_len;
292

293
   /* NOTE: assume zlib doesn't overwrite the input */
294
   png_ptr->zstream.next_in = (Bytef *)text;
295 296
   png_ptr->zstream.avail_out = png_ptr->zbuf_size;
   png_ptr->zstream.next_out = png_ptr->zbuf;
297

298
   /* This is the same compression loop as in png_write_row() */
299 300
   do
   {
301
      /* Compress the data */
302
      ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
303

304 305
      if (ret != Z_OK)
      {
306
         /* Error */
307 308
         if (png_ptr->zstream.msg != NULL)
            png_error(png_ptr, png_ptr->zstream.msg);
309

310 311 312
         else
            png_error(png_ptr, "zlib error");
      }
313

314
      /* Check to see if we need more room */
315
      if (!(png_ptr->zstream.avail_out))
316
      {
317
         /* Make sure the output array has room */
318 319 320 321 322 323 324 325
         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)
            {
326
               png_bytepp old_ptr;
327 328

               old_ptr = comp->output_ptr;
329

330
               comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
331 332
                   (png_alloc_size_t)
                   (comp->max_output_ptr * png_sizeof(png_charpp)));
333

334
               png_memcpy(comp->output_ptr, old_ptr, old_max
335
                   * png_sizeof(png_charp));
336

337 338 339
               png_free(png_ptr, old_ptr);
            }
            else
340
               comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
341 342
                   (png_alloc_size_t)
                   (comp->max_output_ptr * png_sizeof(png_charp)));
343 344
         }

345
         /* Save the data */
346
         comp->output_ptr[comp->num_output_ptr] =
347
             (png_bytep)png_malloc(png_ptr,
348
             (png_alloc_size_t)png_ptr->zbuf_size);
349

350
         png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
351
             png_ptr->zbuf_size);
352

353
         comp->num_output_ptr++;
354 355 356 357 358

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

362
   /* Finish the compression */
363 364
   do
   {
365
      /* Tell zlib we are finished */
366 367
      ret = deflate(&png_ptr->zstream, Z_FINISH);

368
      if (ret == Z_OK)
369
      {
370
         /* Check to see if we need more room */
371
         if (!(png_ptr->zstream.avail_out))
372
         {
373
            /* Check to make sure our output array has room */
374
            if (comp->num_output_ptr >= comp->max_output_ptr)
375
            {
376 377 378 379 380 381
               int old_max;

               old_max = comp->max_output_ptr;
               comp->max_output_ptr = comp->num_output_ptr + 4;
               if (comp->output_ptr != NULL)
               {
382
                  png_bytepp old_ptr;
383 384

                  old_ptr = comp->output_ptr;
385

386
                  /* This could be optimized to realloc() */
387
                  comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
388 389
                      (png_alloc_size_t)(comp->max_output_ptr *
                      png_sizeof(png_charp)));
390

391
                  png_memcpy(comp->output_ptr, old_ptr,
392
                      old_max * png_sizeof(png_charp));
393

394 395
                  png_free(png_ptr, old_ptr);
               }
396

397
               else
398
                  comp->output_ptr = (png_bytepp)png_malloc(png_ptr,
399 400
                      (png_alloc_size_t)(comp->max_output_ptr *
                      png_sizeof(png_charp)));
401 402
            }

403
            /* Save the data */
404
            comp->output_ptr[comp->num_output_ptr] =
405
                (png_bytep)png_malloc(png_ptr,
406
                (png_alloc_size_t)png_ptr->zbuf_size);
407

408
            png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
409
                png_ptr->zbuf_size);
410

411
            comp->num_output_ptr++;
412

413 414 415 416 417 418 419
            /* 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)
      {
420
         /* We got an error */
421 422
         if (png_ptr->zstream.msg != NULL)
            png_error(png_ptr, png_ptr->zstream.msg);
423

424 425
         else
            png_error(png_ptr, "zlib error");
426 427 428
      }
   } while (ret != Z_STREAM_END);

429
   /* Text length is number of buffers plus last buffer */
430
   text_len = png_ptr->zbuf_size * comp->num_output_ptr;
431

432 433 434
   if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
      text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;

435
   return((int)text_len);
436 437
}

438
/* Ship the compressed text out via chunk writes */
439
static void /* PRIVATE */
440 441 442 443
png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
{
   int i;

444
   /* Handle the no-compression case */
445 446
   if (comp->input)
   {
447
      png_write_chunk_data(png_ptr, comp->input, comp->input_len);
448

449
      return;
450 451
   }

452
   /* Write saved output buffers, if any */
453 454
   for (i = 0; i < comp->num_output_ptr; i++)
   {
455
      png_write_chunk_data(png_ptr, comp->output_ptr[i],
456
          (png_size_t)png_ptr->zbuf_size);
457

458 459
      png_free(png_ptr, comp->output_ptr[i]);
   }
460

461 462
   if (comp->max_output_ptr != 0)
      png_free(png_ptr, comp->output_ptr);
463

464
   /* Write anything left in zbuf */
465 466
   if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
      png_write_chunk_data(png_ptr, png_ptr->zbuf,
467
          (png_size_t)(png_ptr->zbuf_size - png_ptr->zstream.avail_out));
468

469
   /* Reset zlib for another zTXt/iTXt or image data */
470 471 472 473
   deflateReset(&png_ptr->zstream);
}
#endif

G
Guy Schalnat 已提交
474
/* Write the IHDR chunk, and update the png_struct with the necessary
475 476 477
 * information.  Note that the rest of this code depends upon this
 * information being correct.
 */
478
void /* PRIVATE */
G
Guy Schalnat 已提交
479
png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
480 481
    int bit_depth, int color_type, int compression_type, int filter_type,
    int interlace_type)
G
Guy Schalnat 已提交
482
{
483
   PNG_IHDR;
484 485
   int ret;

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

488
   png_debug(1, "in png_write_IHDR");
489

G
Guy Schalnat 已提交
490
   /* Check that we have valid input data from the application info */
G
Guy Schalnat 已提交
491 492
   switch (color_type)
   {
A
Andreas Dilger 已提交
493
      case PNG_COLOR_TYPE_GRAY:
G
Guy Schalnat 已提交
494 495 496 497 498 499
         switch (bit_depth)
         {
            case 1:
            case 2:
            case 4:
            case 8:
500
#ifdef PNG_WRITE_16BIT_SUPPORTED
501
            case 16:
502
#endif
503
               png_ptr->channels = 1; break;
504

505 506 507
            default:
               png_error(png_ptr,
                   "Invalid bit depth for grayscale image");
G
Guy Schalnat 已提交
508
         }
G
Guy Schalnat 已提交
509
         break;
510

A
Andreas Dilger 已提交
511
      case PNG_COLOR_TYPE_RGB:
512
#ifdef PNG_WRITE_16BIT_SUPPORTED
G
Guy Schalnat 已提交
513
         if (bit_depth != 8 && bit_depth != 16)
514 515 516
#else
         if (bit_depth != 8)
#endif
G
Guy Schalnat 已提交
517
            png_error(png_ptr, "Invalid bit depth for RGB image");
518

G
Guy Schalnat 已提交
519 520
         png_ptr->channels = 3;
         break;
521

A
Andreas Dilger 已提交
522
      case PNG_COLOR_TYPE_PALETTE:
G
Guy Schalnat 已提交
523 524 525 526 527
         switch (bit_depth)
         {
            case 1:
            case 2:
            case 4:
528 529 530
            case 8:
               png_ptr->channels = 1;
               break;
531

532 533
            default:
               png_error(png_ptr, "Invalid bit depth for paletted image");
G
Guy Schalnat 已提交
534 535
         }
         break;
536

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

G
Guy Schalnat 已提交
541 542
         png_ptr->channels = 2;
         break;
543

A
Andreas Dilger 已提交
544
      case PNG_COLOR_TYPE_RGB_ALPHA:
545
#ifdef PNG_WRITE_16BIT_SUPPORTED
G
Guy Schalnat 已提交
546
         if (bit_depth != 8 && bit_depth != 16)
547 548 549
#else
         if (bit_depth != 8)
#endif
G
Guy Schalnat 已提交
550
            png_error(png_ptr, "Invalid bit depth for RGBA image");
551

G
Guy Schalnat 已提交
552 553
         png_ptr->channels = 4;
         break;
554

G
Guy Schalnat 已提交
555 556 557 558
      default:
         png_error(png_ptr, "Invalid image color type specified");
   }

A
Andreas Dilger 已提交
559
   if (compression_type != PNG_COMPRESSION_TYPE_BASE)
G
Guy Schalnat 已提交
560 561
   {
      png_warning(png_ptr, "Invalid compression type specified");
A
Andreas Dilger 已提交
562
      compression_type = PNG_COMPRESSION_TYPE_BASE;
G
Guy Schalnat 已提交
563 564
   }

565 566 567 568 569 570 571 572 573
   /* 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
    */
574
   if (
575
#ifdef PNG_MNG_FEATURES_SUPPORTED
576 577 578 579 580
       !((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)) &&
581
#endif
582
       filter_type != PNG_FILTER_TYPE_BASE)
G
Guy Schalnat 已提交
583 584
   {
      png_warning(png_ptr, "Invalid filter type specified");
A
Andreas Dilger 已提交
585
      filter_type = PNG_FILTER_TYPE_BASE;
G
Guy Schalnat 已提交
586 587
   }

588
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
A
Andreas Dilger 已提交
589
   if (interlace_type != PNG_INTERLACE_NONE &&
590
       interlace_type != PNG_INTERLACE_ADAM7)
G
Guy Schalnat 已提交
591 592
   {
      png_warning(png_ptr, "Invalid interlace type specified");
A
Andreas Dilger 已提交
593
      interlace_type = PNG_INTERLACE_ADAM7;
G
Guy Schalnat 已提交
594
   }
595 596 597
#else
   interlace_type=PNG_INTERLACE_NONE;
#endif
G
Guy Schalnat 已提交
598

599
   /* Save the relevent information */
G
Guy Schalnat 已提交
600 601 602
   png_ptr->bit_depth = (png_byte)bit_depth;
   png_ptr->color_type = (png_byte)color_type;
   png_ptr->interlaced = (png_byte)interlace_type;
603
#ifdef PNG_MNG_FEATURES_SUPPORTED
604
   png_ptr->filter_type = (png_byte)filter_type;
605
#endif
606
   png_ptr->compression_type = (png_byte)compression_type;
G
Guy Schalnat 已提交
607 608 609
   png_ptr->width = width;
   png_ptr->height = height;

G
Guy Schalnat 已提交
610
   png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
611
   png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
612
   /* Set the usr info, so any transformations can modify it */
G
Guy Schalnat 已提交
613 614
   png_ptr->usr_width = png_ptr->width;
   png_ptr->usr_bit_depth = png_ptr->bit_depth;
G
Guy Schalnat 已提交
615 616
   png_ptr->usr_channels = png_ptr->channels;

617
   /* Pack the header information into the buffer */
G
Guy Schalnat 已提交
618 619 620 621 622 623 624
   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 已提交
625

626
   /* Write the chunk */
627
   png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
G
Guy Schalnat 已提交
628

629
   /* Initialize zlib with PNG info */
A
Andreas Dilger 已提交
630 631 632
   png_ptr->zstream.zalloc = png_zalloc;
   png_ptr->zstream.zfree = png_zfree;
   png_ptr->zstream.opaque = (voidpf)png_ptr;
633

G
Guy Schalnat 已提交
634
   if (!(png_ptr->do_filter))
G
Guy Schalnat 已提交
635
   {
A
Andreas Dilger 已提交
636
      if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
637
          png_ptr->bit_depth < 8)
G
Guy Schalnat 已提交
638
         png_ptr->do_filter = PNG_FILTER_NONE;
639

G
Guy Schalnat 已提交
640
      else
G
Guy Schalnat 已提交
641
         png_ptr->do_filter = PNG_ALL_FILTERS;
G
Guy Schalnat 已提交
642
   }
643

G
Guy Schalnat 已提交
644
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
G
Guy Schalnat 已提交
645
   {
G
Guy Schalnat 已提交
646
      if (png_ptr->do_filter != PNG_FILTER_NONE)
G
Guy Schalnat 已提交
647
         png_ptr->zlib_strategy = Z_FILTERED;
648

G
Guy Schalnat 已提交
649 650 651
      else
         png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
   }
652

G
Guy Schalnat 已提交
653
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
G
Guy Schalnat 已提交
654
      png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
655

G
Guy Schalnat 已提交
656
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
G
Guy Schalnat 已提交
657
      png_ptr->zlib_mem_level = 8;
658

G
Guy Schalnat 已提交
659
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
660
      png_ptr->zlib_window_bits = 15;
661

G
Guy Schalnat 已提交
662
   if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
G
Guy Schalnat 已提交
663
      png_ptr->zlib_method = 8;
664

665 666 667
#ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION
   if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_STRATEGY))
      png_ptr->zlib_text_strategy = Z_DEFAULT_STRATEGY;
668

669 670
   if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_LEVEL))
      png_ptr->zlib_text_level = Z_DEFAULT_COMPRESSION;
671

672 673
   if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_MEM_LEVEL))
      png_ptr->zlib_text_mem_level = 8;
674

675 676
   if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_WINDOW_BITS))
      png_ptr->zlib_text_window_bits = 15;
677

678 679 680 681 682 683 684 685 686 687
   if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_METHOD))
      png_ptr->zlib_text_method = 8;
#else
   png_ptr->zlib_text_strategy = Z_DEFAULT_STRATEGY;
   png_ptr->zlib_text_level = Z_DEFAULT_COMPRESSION;
   png_ptr->zlib_text_mem_level = 8;
   png_ptr->zlib_text_window_bits = 15;
   png_ptr->zlib_text_method = 8;
#endif /* PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION */

688 689
   /* Free memory from previously opened zstream */
   deflateEnd(&png_ptr->zstream);
690 691 692 693
   /* Initialize the zlib compressor */
   ret = deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
       png_ptr->zlib_method, png_ptr->zlib_window_bits,
       png_ptr->zlib_mem_level, png_ptr->zlib_strategy);
G
Guy Schalnat 已提交
694

695
   png_ptr->mode = PNG_HAVE_IHDR; /* not READY_FOR_ZTXT */
G
Guy Schalnat 已提交
696 697
}

698
/* Write the palette.  We are careful not to trust png_color to be in the
699
 * correct order for PNG, so people can redefine it to any convenient
700 701
 * structure.
 */
702
void /* PRIVATE */
703 704
png_write_PLTE(png_structp png_ptr, png_const_colorp palette,
    png_uint_32 num_pal)
G
Guy Schalnat 已提交
705
{
706
   PNG_PLTE;
A
Andreas Dilger 已提交
707
   png_uint_32 i;
708
   png_const_colorp pal_ptr;
G
Guy Schalnat 已提交
709 710
   png_byte buf[3];

711
   png_debug(1, "in png_write_PLTE");
712

713
   if ((
714
#ifdef PNG_MNG_FEATURES_SUPPORTED
715
       !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
716
#endif
717
       num_pal == 0) || num_pal > 256)
718
   {
719 720 721 722
      if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
      {
         png_error(png_ptr, "Invalid number of colors in palette");
      }
723

724 725 726 727 728
      else
      {
         png_warning(png_ptr, "Invalid number of colors in palette");
         return;
      }
729 730 731 732 733
   }

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

736
      return;
G
Guy Schalnat 已提交
737 738
   }

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

742
   png_write_chunk_start(png_ptr, png_PLTE, (png_uint_32)(num_pal * 3));
743
#ifdef PNG_POINTER_INDEXING_SUPPORTED
744

A
Andreas Dilger 已提交
745
   for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
G
Guy Schalnat 已提交
746 747 748 749
   {
      buf[0] = pal_ptr->red;
      buf[1] = pal_ptr->green;
      buf[2] = pal_ptr->blue;
750
      png_write_chunk_data(png_ptr, buf, (png_size_t)3);
G
Guy Schalnat 已提交
751
   }
752

753
#else
754 755 756
   /* This is a little slower but some buggy compilers need to do this
    * instead
    */
757
   pal_ptr=palette;
758

759 760 761 762 763
   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;
764
      png_write_chunk_data(png_ptr, buf, (png_size_t)3);
765
   }
766

767
#endif
G
Guy Schalnat 已提交
768
   png_write_chunk_end(png_ptr);
G
Guy Schalnat 已提交
769
   png_ptr->mode |= PNG_HAVE_PLTE;
G
Guy Schalnat 已提交
770 771
}

772
/* Write an IDAT chunk */
773
void /* PRIVATE */
A
Andreas Dilger 已提交
774
png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
G
Guy Schalnat 已提交
775
{
776
   PNG_IDAT;
777

778
   png_debug(1, "in png_write_IDAT");
779

780 781 782 783 784
   /* 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)
   {
785 786 787
      int ret;
      unsigned int z_cmf;  /* zlib compression method and flags */

788 789 790 791
      if (png_ptr->mode & PNG_ZLIB_READY_FOR_ZTXT)
      {
         /* Free memory from previously opened zstream */
         deflateEnd(&png_ptr->zstream);
792

793 794 795
         ret = deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
             png_ptr->zlib_method, png_ptr->zlib_window_bits,
             png_ptr->zlib_mem_level, png_ptr->zlib_strategy);
796

797 798 799 800 801
         if (ret != Z_OK)
         {
            if (ret == Z_VERSION_ERROR)
               png_error(png_ptr,
                  "zlib failed to initialize compressor -- version error");
802

803 804 805
            if (ret == Z_STREAM_ERROR)
               png_error(png_ptr,
                   "zlib failed to initialize compressor -- stream error");
806

807 808 809
            if (ret == Z_MEM_ERROR)
               png_error(png_ptr,
                   "zlib failed to initialize compressor -- mem error");
810

811 812 813
            png_error(png_ptr, "zlib failed to initialize compressor");
         }
         png_ptr->mode &= ~PNG_ZLIB_READY_FOR_ZTXT; /* Ready for IDAT */
814 815 816 817 818 819 820 821 822 823 824
      }

      png_ptr->zstream.next_out = png_ptr->zbuf;
      png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
      /* libpng is not interested in zstream.data_type, so set it
       * to a predefined value, to avoid its evaluation inside zlib
       */
      png_ptr->zstream.data_type = Z_BINARY;

      z_cmf = data[0];

825 826
      if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
      {
827 828 829 830 831
         /* Avoid memory underflows and multiplication overflows.
          *
          * The conditions below are practically always satisfied;
          * however, they still must be checked.
          */
832 833 834 835
         if (length >= 2 &&
             png_ptr->height < 16384 && png_ptr->width < 16384)
         {
            png_uint_32 uncompressed_idat_size = png_ptr->height *
836 837
                ((png_ptr->width *
                png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
838 839 840
            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 &&
841
                half_z_window_size >= 256)
842 843 844 845
            {
               z_cinfo--;
               half_z_window_size >>= 1;
            }
846

847
            z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
848

849
            if (data[0] != z_cmf)
850
            {
851
               int tmp;
852
               data[0] = (png_byte)z_cmf;
853 854 855
               tmp = data[1] & 0xe0;
               tmp += 0x1f - ((z_cmf << 8) + tmp) % 0x1f;
               data[1] = (png_byte)tmp;
856 857 858
            }
         }
      }
859

860 861
      else
         png_error(png_ptr,
862
             "Invalid zlib compression method or flags in IDAT");
863 864
   }

865
   png_write_chunk(png_ptr, png_IDAT, data, length);
G
Guy Schalnat 已提交
866
   png_ptr->mode |= PNG_HAVE_IDAT;
G
Guy Schalnat 已提交
867 868
}

869
/* Write an IEND chunk */
870
void /* PRIVATE */
G
Guy Schalnat 已提交
871
png_write_IEND(png_structp png_ptr)
G
Guy Schalnat 已提交
872
{
873
   PNG_IEND;
874

875
   png_debug(1, "in png_write_IEND");
876

877
   png_write_chunk(png_ptr, png_IEND, NULL, (png_size_t)0);
A
Andreas Dilger 已提交
878
   png_ptr->mode |= PNG_HAVE_IEND;
G
Guy Schalnat 已提交
879 880
}

881
#ifdef PNG_WRITE_gAMA_SUPPORTED
882
/* Write a gAMA chunk */
883
void /* PRIVATE */
884
png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
885 886 887 888
{
   PNG_gAMA;
   png_byte buf[4];

889
   png_debug(1, "in png_write_gAMA");
890

891
   /* file_gamma is saved in 1/100,000ths */
892
   png_save_uint_32(buf, (png_uint_32)file_gamma);
893
   png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
894 895
}
#endif
G
Guy Schalnat 已提交
896

897
#ifdef PNG_WRITE_sRGB_SUPPORTED
898
/* Write a sRGB chunk */
899
void /* PRIVATE */
900
png_write_sRGB(png_structp png_ptr, int srgb_intent)
901
{
902
   PNG_sRGB;
903 904
   png_byte buf[1];

905
   png_debug(1, "in png_write_sRGB");
906

907
   if (srgb_intent >= PNG_sRGB_INTENT_LAST)
908 909
      png_warning(png_ptr,
          "Invalid sRGB rendering intent specified");
910

911
   buf[0]=(png_byte)srgb_intent;
912
   png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
913 914 915
}
#endif

916
#ifdef PNG_WRITE_iCCP_SUPPORTED
917
/* Write an iCCP chunk */
918
void /* PRIVATE */
919 920
png_write_iCCP(png_structp png_ptr, png_const_charp name, int compression_type,
    png_const_charp profile, int profile_len)
921 922 923 924 925
{
   PNG_iCCP;
   png_size_t name_len;
   png_charp new_name;
   compression_state comp;
926
   int embedded_profile_len = 0;
927

928
   png_debug(1, "in png_write_iCCP");
929 930 931 932 933 934 935

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

936
   if ((name_len = png_check_keyword(png_ptr, name, &new_name)) == 0)
937 938
      return;

939
   if (compression_type != PNG_COMPRESSION_TYPE_BASE)
940
      png_warning(png_ptr, "Unknown compression type in iCCP chunk");
941

942
   if (profile == NULL)
943 944
      profile_len = 0;

945
   if (profile_len > 3)
946
      embedded_profile_len =
947 948 949 950
          ((*( (png_const_bytep)profile    ))<<24) |
          ((*( (png_const_bytep)profile + 1))<<16) |
          ((*( (png_const_bytep)profile + 2))<< 8) |
          ((*( (png_const_bytep)profile + 3))    );
951

952 953 954
   if (embedded_profile_len < 0)
   {
      png_warning(png_ptr,
955
          "Embedded profile length in iCCP chunk is negative");
956

957 958 959 960
      png_free(png_ptr, new_name);
      return;
   }

961
   if (profile_len < embedded_profile_len)
962 963
   {
      png_warning(png_ptr,
964
          "Embedded profile length too large in iCCP chunk");
965

966
      png_free(png_ptr, new_name);
967 968
      return;
   }
969 970

   if (profile_len > embedded_profile_len)
971 972
   {
      png_warning(png_ptr,
973
          "Truncating profile to actual length in iCCP chunk");
974

975 976
      profile_len = embedded_profile_len;
   }
977

978
   if (profile_len)
979
      profile_len = png_text_compress(png_ptr, profile,
980
          (png_size_t)profile_len, PNG_COMPRESSION_TYPE_BASE, &comp);
981

982
   /* Make sure we include the NULL after the name and the compression type */
983
   png_write_chunk_start(png_ptr, png_iCCP,
984
       (png_uint_32)(name_len + profile_len + 2));
985

986
   new_name[name_len + 1] = 0x00;
987

988
   png_write_chunk_data(png_ptr, (png_bytep)new_name,
989
       (png_size_t)(name_len + 2));
990 991 992 993 994 995 996 997 998

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

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

999
#ifdef PNG_WRITE_sPLT_SUPPORTED
1000
/* Write a sPLT chunk */
1001
void /* PRIVATE */
1002
png_write_sPLT(png_structp png_ptr, png_const_sPLT_tp spalette)
1003 1004 1005 1006 1007
{
   PNG_sPLT;
   png_size_t name_len;
   png_charp new_name;
   png_byte entrybuf[10];
1008 1009
   png_size_t entry_size = (spalette->depth == 8 ? 6 : 10);
   png_size_t palette_size = entry_size * spalette->nentries;
1010
   png_sPLT_entryp ep;
1011
#ifndef PNG_POINTER_INDEXING_SUPPORTED
1012 1013
   int i;
#endif
1014

1015
   png_debug(1, "in png_write_sPLT");
1016

1017 1018
   if ((name_len = png_check_keyword(png_ptr,spalette->name, &new_name))==0)
      return;
1019

1020
   /* Make sure we include the NULL after the name */
1021
   png_write_chunk_start(png_ptr, png_sPLT,
1022
       (png_uint_32)(name_len + 2 + palette_size));
1023

1024
   png_write_chunk_data(png_ptr, (png_bytep)new_name,
1025
       (png_size_t)(name_len + 1));
1026

1027
   png_write_chunk_data(png_ptr, &spalette->depth, (png_size_t)1);
1028

1029
   /* Loop through each palette entry, writing appropriately */
1030
#ifdef PNG_POINTER_INDEXING_SUPPORTED
1031
   for (ep = spalette->entries; ep<spalette->entries + spalette->nentries; ep++)
1032
   {
1033 1034
      if (spalette->depth == 8)
      {
1035 1036 1037 1038 1039
         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);
1040
      }
1041

1042 1043
      else
      {
1044 1045 1046 1047 1048
         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);
1049
      }
1050

1051
      png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
1052
   }
1053 1054
#else
   ep=spalette->entries;
1055
   for (i = 0; i>spalette->nentries; i++)
1056
   {
1057 1058
      if (spalette->depth == 8)
      {
1059 1060 1061 1062 1063
         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);
1064
      }
1065

1066 1067
      else
      {
1068 1069 1070 1071 1072
         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);
1073
      }
1074

1075
      png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
1076 1077
   }
#endif
1078 1079 1080 1081 1082 1083

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

1084
#ifdef PNG_WRITE_sBIT_SUPPORTED
1085
/* Write the sBIT chunk */
1086
void /* PRIVATE */
1087
png_write_sBIT(png_structp png_ptr, png_const_color_8p sbit, int color_type)
G
Guy Schalnat 已提交
1088
{
1089
   PNG_sBIT;
G
Guy Schalnat 已提交
1090
   png_byte buf[4];
A
Andreas Dilger 已提交
1091
   png_size_t size;
G
Guy Schalnat 已提交
1092

1093
   png_debug(1, "in png_write_sBIT");
1094

1095
   /* Make sure we don't depend upon the order of PNG_COLOR_8 */
G
Guy Schalnat 已提交
1096 1097
   if (color_type & PNG_COLOR_MASK_COLOR)
   {
1098
      png_byte maxbits;
G
Guy Schalnat 已提交
1099

1100
      maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
1101
          png_ptr->usr_bit_depth);
1102

1103 1104
      if (sbit->red == 0 || sbit->red > maxbits ||
          sbit->green == 0 || sbit->green > maxbits ||
G
Guy Schalnat 已提交
1105 1106 1107 1108 1109
          sbit->blue == 0 || sbit->blue > maxbits)
      {
         png_warning(png_ptr, "Invalid sBIT depth specified");
         return;
      }
1110

G
Guy Schalnat 已提交
1111 1112 1113 1114 1115
      buf[0] = sbit->red;
      buf[1] = sbit->green;
      buf[2] = sbit->blue;
      size = 3;
   }
1116

G
Guy Schalnat 已提交
1117 1118
   else
   {
G
Guy Schalnat 已提交
1119 1120 1121 1122 1123
      if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
      {
         png_warning(png_ptr, "Invalid sBIT depth specified");
         return;
      }
1124

G
Guy Schalnat 已提交
1125 1126 1127 1128 1129 1130
      buf[0] = sbit->gray;
      size = 1;
   }

   if (color_type & PNG_COLOR_MASK_ALPHA)
   {
G
Guy Schalnat 已提交
1131 1132 1133 1134 1135
      if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
      {
         png_warning(png_ptr, "Invalid sBIT depth specified");
         return;
      }
1136

G
Guy Schalnat 已提交
1137 1138 1139
      buf[size++] = sbit->alpha;
   }

1140
   png_write_chunk(png_ptr, png_sBIT, buf, size);
G
Guy Schalnat 已提交
1141
}
G
Guy Schalnat 已提交
1142
#endif
G
Guy Schalnat 已提交
1143

1144
#ifdef PNG_WRITE_cHRM_SUPPORTED
1145
/* Write the cHRM chunk */
1146
void /* PRIVATE */
1147
png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
1148 1149 1150
    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)
1151 1152 1153 1154
{
   PNG_cHRM;
   png_byte buf[32];

1155
   png_debug(1, "in png_write_cHRM");
1156

1157
   /* Each value is saved in 1/100,000ths */
1158
#ifdef PNG_CHECK_cHRM_SUPPORTED
1159
   if (png_check_cHRM_fixed(png_ptr, white_x, white_y, red_x, red_y,
1160
       green_x, green_y, blue_x, blue_y))
1161
#endif
1162
   {
1163 1164
      png_save_uint_32(buf, (png_uint_32)white_x);
      png_save_uint_32(buf + 4, (png_uint_32)white_y);
1165

1166 1167
      png_save_uint_32(buf + 8, (png_uint_32)red_x);
      png_save_uint_32(buf + 12, (png_uint_32)red_y);
1168

1169 1170
      png_save_uint_32(buf + 16, (png_uint_32)green_x);
      png_save_uint_32(buf + 20, (png_uint_32)green_y);
1171

1172 1173
      png_save_uint_32(buf + 24, (png_uint_32)blue_x);
      png_save_uint_32(buf + 28, (png_uint_32)blue_y);
1174

1175
      png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
1176
   }
1177 1178
}
#endif
G
Guy Schalnat 已提交
1179

1180
#ifdef PNG_WRITE_tRNS_SUPPORTED
1181
/* Write the tRNS chunk */
1182
void /* PRIVATE */
1183 1184
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 已提交
1185
{
1186
   PNG_tRNS;
G
Guy Schalnat 已提交
1187 1188
   png_byte buf[6];

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

G
Guy Schalnat 已提交
1191 1192
   if (color_type == PNG_COLOR_TYPE_PALETTE)
   {
1193
      if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
G
Guy Schalnat 已提交
1194
      {
1195
         png_warning(png_ptr, "Invalid number of transparent colors specified");
G
Guy Schalnat 已提交
1196 1197
         return;
      }
1198

1199
      /* Write the chunk out as it is */
1200
      png_write_chunk(png_ptr, png_tRNS, trans_alpha, (png_size_t)num_trans);
G
Guy Schalnat 已提交
1201
   }
1202

G
Guy Schalnat 已提交
1203 1204
   else if (color_type == PNG_COLOR_TYPE_GRAY)
   {
1205
      /* One 16 bit value */
1206
      if (tran->gray >= (1 << png_ptr->bit_depth))
1207 1208
      {
         png_warning(png_ptr,
1209
             "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
1210

1211 1212
         return;
      }
1213

G
Guy Schalnat 已提交
1214
      png_save_uint_16(buf, tran->gray);
1215
      png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
G
Guy Schalnat 已提交
1216
   }
1217

G
Guy Schalnat 已提交
1218 1219
   else if (color_type == PNG_COLOR_TYPE_RGB)
   {
1220
      /* Three 16 bit values */
G
Guy Schalnat 已提交
1221 1222 1223
      png_save_uint_16(buf, tran->red);
      png_save_uint_16(buf + 2, tran->green);
      png_save_uint_16(buf + 4, tran->blue);
1224
#ifdef PNG_WRITE_16BIT_SUPPORTED
1225
      if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
1226 1227 1228
#else
      if (buf[0] | buf[2] | buf[4])
#endif
1229 1230
      {
         png_warning(png_ptr,
1231
           "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
1232 1233
         return;
      }
1234

1235
      png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
G
Guy Schalnat 已提交
1236
   }
1237

G
Guy Schalnat 已提交
1238 1239
   else
   {
1240
      png_warning(png_ptr, "Can't write tRNS with an alpha channel");
G
Guy Schalnat 已提交
1241
   }
G
Guy Schalnat 已提交
1242
}
G
Guy Schalnat 已提交
1243
#endif
G
Guy Schalnat 已提交
1244

1245
#ifdef PNG_WRITE_bKGD_SUPPORTED
1246
/* Write the background chunk */
1247
void /* PRIVATE */
1248
png_write_bKGD(png_structp png_ptr, png_const_color_16p back, int color_type)
G
Guy Schalnat 已提交
1249
{
1250
   PNG_bKGD;
G
Guy Schalnat 已提交
1251 1252
   png_byte buf[6];

1253
   png_debug(1, "in png_write_bKGD");
1254

G
Guy Schalnat 已提交
1255 1256
   if (color_type == PNG_COLOR_TYPE_PALETTE)
   {
1257
      if (
1258
#ifdef PNG_MNG_FEATURES_SUPPORTED
1259 1260
          (png_ptr->num_palette ||
          (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
1261
#endif
1262
         back->index >= png_ptr->num_palette)
G
Guy Schalnat 已提交
1263 1264 1265 1266
      {
         png_warning(png_ptr, "Invalid background palette index");
         return;
      }
1267

G
Guy Schalnat 已提交
1268
      buf[0] = back->index;
1269
      png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
G
Guy Schalnat 已提交
1270
   }
1271

G
Guy Schalnat 已提交
1272 1273 1274 1275 1276
   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);
1277
#ifdef PNG_WRITE_16BIT_SUPPORTED
1278
      if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
1279 1280 1281
#else
      if (buf[0] | buf[2] | buf[4])
#endif
1282 1283
      {
         png_warning(png_ptr,
1284
             "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
1285

1286 1287
         return;
      }
1288

1289
      png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
G
Guy Schalnat 已提交
1290
   }
1291

G
Guy Schalnat 已提交
1292
   else
G
Guy Schalnat 已提交
1293
   {
1294
      if (back->gray >= (1 << png_ptr->bit_depth))
1295 1296
      {
         png_warning(png_ptr,
1297
             "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
1298

1299 1300
         return;
      }
1301

G
Guy Schalnat 已提交
1302
      png_save_uint_16(buf, back->gray);
1303
      png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
G
Guy Schalnat 已提交
1304 1305
   }
}
G
Guy Schalnat 已提交
1306
#endif
G
Guy Schalnat 已提交
1307

1308
#ifdef PNG_WRITE_hIST_SUPPORTED
1309
/* Write the histogram */
1310
void /* PRIVATE */
1311
png_write_hIST(png_structp png_ptr, png_const_uint_16p hist, int num_hist)
G
Guy Schalnat 已提交
1312
{
1313
   PNG_hIST;
1314
   int i;
G
Guy Schalnat 已提交
1315 1316
   png_byte buf[3];

1317
   png_debug(1, "in png_write_hIST");
1318

1319
   if (num_hist > (int)png_ptr->num_palette)
G
Guy Schalnat 已提交
1320
   {
1321
      png_debug2(3, "num_hist = %d, num_palette = %d", num_hist,
1322
          png_ptr->num_palette);
1323

G
Guy Schalnat 已提交
1324 1325 1326 1327
      png_warning(png_ptr, "Invalid number of histogram entries specified");
      return;
   }

1328
   png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
1329

A
Andreas Dilger 已提交
1330
   for (i = 0; i < num_hist; i++)
G
Guy Schalnat 已提交
1331
   {
G
Guy Schalnat 已提交
1332
      png_save_uint_16(buf, hist[i]);
1333
      png_write_chunk_data(png_ptr, buf, (png_size_t)2);
G
Guy Schalnat 已提交
1334
   }
1335

G
Guy Schalnat 已提交
1336 1337
   png_write_chunk_end(png_ptr);
}
G
Guy Schalnat 已提交
1338
#endif
G
Guy Schalnat 已提交
1339

1340 1341
#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
    defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
A
Andreas Dilger 已提交
1342 1343 1344 1345 1346
/* 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 已提交
1347 1348 1349 1350
 *
 * 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 已提交
1351
 */
1352
png_size_t /* PRIVATE */
1353
png_check_keyword(png_structp png_ptr, png_const_charp key, png_charpp new_key)
A
Andreas Dilger 已提交
1354
{
A
Andreas Dilger 已提交
1355
   png_size_t key_len;
1356
   png_const_charp ikp;
1357
   png_charp kp, dp;
A
Andreas Dilger 已提交
1358
   int kflag;
1359
   int kwarn=0;
A
Andreas Dilger 已提交
1360

1361
   png_debug(1, "in png_check_keyword");
1362

A
Andreas Dilger 已提交
1363 1364 1365
   *new_key = NULL;

   if (key == NULL || (key_len = png_strlen(key)) == 0)
A
Andreas Dilger 已提交
1366
   {
1367
      png_warning(png_ptr, "zero length keyword");
1368
      return ((png_size_t)0);
A
Andreas Dilger 已提交
1369
   }
A
Andreas Dilger 已提交
1370

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

1373
   *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
1374

1375 1376 1377
   if (*new_key == NULL)
   {
      png_warning(png_ptr, "Out of memory while procesing keyword");
1378
      return ((png_size_t)0);
1379
   }
1380

A
Andreas Dilger 已提交
1381
   /* Replace non-printing characters with a blank and print a warning */
1382
   for (ikp = key, dp = *new_key; *ikp != '\0'; ikp++, dp++)
A
Andreas Dilger 已提交
1383
   {
1384 1385
      if ((png_byte)*ikp < 0x20 ||
         ((png_byte)*ikp > 0x7E && (png_byte)*ikp < 0xA1))
A
Andreas Dilger 已提交
1386
      {
1387
#ifdef PNG_CONSOLE_IO_SUPPORTED
A
Andreas Dilger 已提交
1388
         char msg[40];
A
Andreas Dilger 已提交
1389

1390
         png_snprintf(msg, 40,
1391
             "invalid keyword character 0x%02X", (png_byte)*ikp);
1392
         png_warning(png_ptr, msg);
1393
#else
1394
         png_warning(png_ptr, "invalid character in keyword");
1395
#endif
A
Andreas Dilger 已提交
1396 1397
         *dp = ' ';
      }
1398

A
Andreas Dilger 已提交
1399 1400
      else
      {
1401
         *dp = *ikp;
A
Andreas Dilger 已提交
1402
      }
A
Andreas Dilger 已提交
1403
   }
A
Andreas Dilger 已提交
1404
   *dp = '\0';
A
Andreas Dilger 已提交
1405

A
Andreas Dilger 已提交
1406 1407 1408
   /* Remove any trailing white space. */
   kp = *new_key + key_len - 1;
   if (*kp == ' ')
A
Andreas Dilger 已提交
1409
   {
1410
      png_warning(png_ptr, "trailing spaces removed from keyword");
A
Andreas Dilger 已提交
1411 1412 1413

      while (*kp == ' ')
      {
1414 1415
         *(kp--) = '\0';
         key_len--;
A
Andreas Dilger 已提交
1416
      }
A
Andreas Dilger 已提交
1417 1418 1419
   }

   /* Remove any leading white space. */
A
Andreas Dilger 已提交
1420 1421
   kp = *new_key;
   if (*kp == ' ')
A
Andreas Dilger 已提交
1422
   {
1423
      png_warning(png_ptr, "leading spaces removed from keyword");
A
Andreas Dilger 已提交
1424 1425 1426

      while (*kp == ' ')
      {
1427 1428
         kp++;
         key_len--;
A
Andreas Dilger 已提交
1429
      }
A
Andreas Dilger 已提交
1430 1431
   }

1432
   png_debug1(2, "Checking for multiple internal spaces in '%s'", kp);
A
Andreas Dilger 已提交
1433 1434 1435

   /* Remove multiple internal spaces. */
   for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
A
Andreas Dilger 已提交
1436
   {
A
Andreas Dilger 已提交
1437
      if (*kp == ' ' && kflag == 0)
A
Andreas Dilger 已提交
1438
      {
A
Andreas Dilger 已提交
1439 1440
         *(dp++) = *kp;
         kflag = 1;
A
Andreas Dilger 已提交
1441
      }
1442

A
Andreas Dilger 已提交
1443
      else if (*kp == ' ')
A
Andreas Dilger 已提交
1444 1445
      {
         key_len--;
1446
         kwarn = 1;
A
Andreas Dilger 已提交
1447
      }
1448

A
Andreas Dilger 已提交
1449 1450
      else
      {
A
Andreas Dilger 已提交
1451 1452
         *(dp++) = *kp;
         kflag = 0;
A
Andreas Dilger 已提交
1453 1454
      }
   }
A
Andreas Dilger 已提交
1455
   *dp = '\0';
1456
   if (kwarn)
1457
      png_warning(png_ptr, "extra interior spaces removed from keyword");
A
Andreas Dilger 已提交
1458 1459

   if (key_len == 0)
A
Andreas Dilger 已提交
1460
   {
1461
      png_free(png_ptr, *new_key);
1462
      png_warning(png_ptr, "Zero length keyword");
A
Andreas Dilger 已提交
1463 1464 1465 1466
   }

   if (key_len > 79)
   {
1467
      png_warning(png_ptr, "keyword length must be 1 - 79 characters");
1468
      (*new_key)[79] = '\0';
A
Andreas Dilger 已提交
1469 1470
      key_len = 79;
   }
A
Andreas Dilger 已提交
1471

1472
   return (key_len);
A
Andreas Dilger 已提交
1473 1474 1475
}
#endif

1476
#ifdef PNG_WRITE_tEXt_SUPPORTED
1477
/* Write a tEXt chunk */
1478
void /* PRIVATE */
1479
png_write_tEXt(png_structp png_ptr, png_const_charp key, png_const_charp text,
1480
    png_size_t text_len)
G
Guy Schalnat 已提交
1481
{
1482
   PNG_tEXt;
A
Andreas Dilger 已提交
1483
   png_size_t key_len;
1484
   png_charp new_key;
A
Andreas Dilger 已提交
1485

1486
   png_debug(1, "in png_write_tEXt");
1487

1488
   if ((key_len = png_check_keyword(png_ptr, key, &new_key))==0)
G
Guy Schalnat 已提交
1489 1490
      return;

A
Andreas Dilger 已提交
1491
   if (text == NULL || *text == '\0')
A
Andreas Dilger 已提交
1492
      text_len = 0;
1493

1494 1495
   else
      text_len = png_strlen(text);
A
Andreas Dilger 已提交
1496

1497
   /* Make sure we include the 0 after the key */
1498
   png_write_chunk_start(png_ptr, png_tEXt,
1499
       (png_uint_32)(key_len + text_len + 1));
1500 1501 1502 1503
   /*
    * 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.
1504
    * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
1505
    */
1506
   png_write_chunk_data(png_ptr, (png_bytep)new_key,
1507
       (png_size_t)(key_len + 1));
1508

A
Andreas Dilger 已提交
1509
   if (text_len)
1510
      png_write_chunk_data(png_ptr, (png_const_bytep)text,
1511
          (png_size_t)text_len);
A
Andreas Dilger 已提交
1512

G
Guy Schalnat 已提交
1513
   png_write_chunk_end(png_ptr);
A
Andreas Dilger 已提交
1514
   png_free(png_ptr, new_key);
G
Guy Schalnat 已提交
1515
}
G
Guy Schalnat 已提交
1516
#endif
G
Guy Schalnat 已提交
1517

1518
#ifdef PNG_WRITE_zTXt_SUPPORTED
1519
/* Write a compressed text chunk */
1520
void /* PRIVATE */
1521
png_write_zTXt(png_structp png_ptr, png_const_charp key, png_const_charp text,
1522
    png_size_t text_len, int compression)
G
Guy Schalnat 已提交
1523
{
1524
   PNG_zTXt;
A
Andreas Dilger 已提交
1525
   png_size_t key_len;
1526
   png_byte buf;
1527
   png_charp new_key;
1528
   compression_state comp;
G
Guy Schalnat 已提交
1529

1530
   png_debug(1, "in png_write_zTXt");
A
Andreas Dilger 已提交
1531

1532 1533 1534 1535 1536 1537
   comp.num_output_ptr = 0;
   comp.max_output_ptr = 0;
   comp.output_ptr = NULL;
   comp.input = NULL;
   comp.input_len = 0;

1538
   if ((key_len = png_check_keyword(png_ptr, key, &new_key)) == 0)
A
Andreas Dilger 已提交
1539
   {
1540
      png_free(png_ptr, new_key);
G
Guy Schalnat 已提交
1541
      return;
A
Andreas Dilger 已提交
1542
   }
A
Andreas Dilger 已提交
1543

A
Andreas Dilger 已提交
1544 1545
   if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
   {
1546
      png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
A
Andreas Dilger 已提交
1547 1548 1549 1550
      png_free(png_ptr, new_key);
      return;
   }

1551 1552
   text_len = png_strlen(text);

1553
   /* Compute the compressed data; do it now for the length */
1554 1555
   text_len = png_text_compress(png_ptr, text, text_len, compression,
       &comp);
G
Guy Schalnat 已提交
1556

1557
   /* Write start of chunk */
1558
   png_write_chunk_start(png_ptr, png_zTXt,
1559
       (png_uint_32)(key_len+text_len + 2));
1560

1561
   /* Write key */
1562
   png_write_chunk_data(png_ptr, (png_bytep)new_key,
1563
       (png_size_t)(key_len + 1));
1564

1565 1566
   png_free(png_ptr, new_key);

1567
   buf = (png_byte)compression;
1568

1569
   /* Write compression */
1570
   png_write_chunk_data(png_ptr, &buf, (png_size_t)1);
1571

1572
   /* Write the compressed data */
1573
   png_write_compressed_data_out(png_ptr, &comp);
G
Guy Schalnat 已提交
1574

1575
   /* Close the chunk */
1576 1577 1578
   png_write_chunk_end(png_ptr);
}
#endif
G
Guy Schalnat 已提交
1579

1580
#ifdef PNG_WRITE_iTXt_SUPPORTED
1581
/* Write an iTXt chunk */
1582
void /* PRIVATE */
1583 1584
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)
1585 1586
{
   PNG_iTXt;
1587
   png_size_t lang_len, key_len, lang_key_len, text_len;
1588 1589
   png_charp new_lang;
   png_charp new_key = NULL;
1590 1591
   png_byte cbuf[2];
   compression_state comp;
G
Guy Schalnat 已提交
1592

1593
   png_debug(1, "in png_write_iTXt");
G
Guy Schalnat 已提交
1594

1595 1596 1597 1598 1599
   comp.num_output_ptr = 0;
   comp.max_output_ptr = 0;
   comp.output_ptr = NULL;
   comp.input = NULL;

1600
   if ((key_len = png_check_keyword(png_ptr, key, &new_key)) == 0)
1601
      return;
1602

1603
   if ((lang_len = png_check_keyword(png_ptr, lang, &new_lang)) == 0)
1604
   {
1605
      png_warning(png_ptr, "Empty language field in iTXt chunk");
1606
      new_lang = NULL;
1607
      lang_len = 0;
1608
   }
G
Guy Schalnat 已提交
1609

1610
   if (lang_key == NULL)
1611
      lang_key_len = 0;
1612

1613
   else
1614
      lang_key_len = png_strlen(lang_key);
1615 1616

   if (text == NULL)
1617
      text_len = 0;
1618

1619
   else
1620
      text_len = png_strlen(text);
G
Guy Schalnat 已提交
1621

1622
   /* Compute the compressed data; do it now for the length */
1623
   text_len = png_text_compress(png_ptr, text, text_len, compression - 2,
1624
       &comp);
G
Guy Schalnat 已提交
1625

1626

1627
   /* Make sure we include the compression flag, the compression byte,
1628 1629
    * and the NULs after the key, lang, and lang_key parts
    */
G
Guy Schalnat 已提交
1630

1631
   png_write_chunk_start(png_ptr, png_iTXt, (png_uint_32)(
1632 1633 1634 1635 1636
        5 /* comp byte, comp flag, terminators for key, lang and lang_key */
        + key_len
        + lang_len
        + lang_key_len
        + text_len));
G
Guy Schalnat 已提交
1637

1638
   /* We leave it to the application to meet PNG-1.0 requirements on the
1639 1640 1641 1642
    * 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.
    */
1643
   png_write_chunk_data(png_ptr, (png_bytep)new_key, (png_size_t)(key_len + 1));
1644

1645
   /* Set the compression flag */
1646
   if (compression == PNG_ITXT_COMPRESSION_NONE ||
1647
       compression == PNG_TEXT_COMPRESSION_NONE)
1648
      cbuf[0] = 0;
1649

1650
   else /* compression == PNG_ITXT_COMPRESSION_zTXt */
1651
      cbuf[0] = 1;
1652

1653
   /* Set the compression method */
1654
   cbuf[1] = 0;
1655

1656
   png_write_chunk_data(png_ptr, cbuf, (png_size_t)2);
1657

1658
   cbuf[0] = 0;
1659
   png_write_chunk_data(png_ptr, (new_lang ? (png_const_bytep)new_lang : cbuf),
1660
       (png_size_t)(lang_len + 1));
1661

1662
   png_write_chunk_data(png_ptr, (lang_key ? (png_const_bytep)lang_key : cbuf),
1663
       (png_size_t)(lang_key_len + 1));
1664

1665
   png_write_compressed_data_out(png_ptr, &comp);
G
Guy Schalnat 已提交
1666 1667

   png_write_chunk_end(png_ptr);
1668

1669
   png_free(png_ptr, new_key);
1670
   png_free(png_ptr, new_lang);
G
Guy Schalnat 已提交
1671
}
G
Guy Schalnat 已提交
1672
#endif
G
Guy Schalnat 已提交
1673

1674
#ifdef PNG_WRITE_oFFs_SUPPORTED
1675
/* Write the oFFs chunk */
1676
void /* PRIVATE */
1677
png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
1678
    int unit_type)
G
Guy Schalnat 已提交
1679
{
1680
   PNG_oFFs;
G
Guy Schalnat 已提交
1681 1682
   png_byte buf[9];

1683
   png_debug(1, "in png_write_oFFs");
1684

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

1688 1689
   png_save_int_32(buf, x_offset);
   png_save_int_32(buf + 4, y_offset);
G
Guy Schalnat 已提交
1690
   buf[8] = (png_byte)unit_type;
G
Guy Schalnat 已提交
1691

1692
   png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
G
Guy Schalnat 已提交
1693
}
G
Guy Schalnat 已提交
1694
#endif
1695
#ifdef PNG_WRITE_pCAL_SUPPORTED
1696
/* Write the pCAL chunk (described in the PNG extensions document) */
1697
void /* PRIVATE */
A
Andreas Dilger 已提交
1698
png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
1699 1700
    png_int_32 X1, int type, int nparams, png_const_charp units,
    png_charpp params)
A
Andreas Dilger 已提交
1701
{
1702
   PNG_pCAL;
1703
   png_size_t purpose_len, units_len, total_len;
A
Andreas Dilger 已提交
1704 1705
   png_uint_32p params_len;
   png_byte buf[10];
1706
   png_charp new_purpose;
A
Andreas Dilger 已提交
1707 1708
   int i;

1709
   png_debug1(1, "in png_write_pCAL (%d parameters)", nparams);
1710

A
Andreas Dilger 已提交
1711 1712 1713 1714
   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;
1715
   png_debug1(3, "pCAL purpose length = %d", (int)purpose_len);
A
Andreas Dilger 已提交
1716
   units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
1717
   png_debug1(3, "pCAL units length = %d", (int)units_len);
A
Andreas Dilger 已提交
1718 1719
   total_len = purpose_len + units_len + 10;

1720
   params_len = (png_uint_32p)png_malloc(png_ptr,
1721
       (png_alloc_size_t)(nparams * png_sizeof(png_uint_32)));
A
Andreas Dilger 已提交
1722 1723

   /* Find the length of each parameter, making sure we don't count the
1724 1725
    * null terminator for the last parameter.
    */
A
Andreas Dilger 已提交
1726 1727 1728
   for (i = 0; i < nparams; i++)
   {
      params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
1729
      png_debug2(3, "pCAL parameter %d length = %lu", i,
1730
          (unsigned long)params_len[i]);
A
Andreas Dilger 已提交
1731 1732 1733
      total_len += (png_size_t)params_len[i];
   }

1734
   png_debug1(3, "pCAL total length = %d", (int)total_len);
1735 1736
   png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
   png_write_chunk_data(png_ptr, (png_const_bytep)new_purpose,
1737
       (png_size_t)purpose_len);
A
Andreas Dilger 已提交
1738 1739 1740 1741
   png_save_int_32(buf, X0);
   png_save_int_32(buf + 4, X1);
   buf[8] = (png_byte)type;
   buf[9] = (png_byte)nparams;
1742
   png_write_chunk_data(png_ptr, buf, (png_size_t)10);
1743
   png_write_chunk_data(png_ptr, (png_const_bytep)units, (png_size_t)units_len);
A
Andreas Dilger 已提交
1744 1745 1746 1747 1748

   png_free(png_ptr, new_purpose);

   for (i = 0; i < nparams; i++)
   {
1749
      png_write_chunk_data(png_ptr, (png_const_bytep)params[i],
1750
          (png_size_t)params_len[i]);
A
Andreas Dilger 已提交
1751 1752
   }

1753
   png_free(png_ptr, params_len);
A
Andreas Dilger 已提交
1754 1755 1756 1757
   png_write_chunk_end(png_ptr);
}
#endif

1758
#ifdef PNG_WRITE_sCAL_SUPPORTED
1759
/* Write the sCAL chunk */
1760
void /* PRIVATE */
1761 1762
png_write_sCAL_s(png_structp png_ptr, int unit, png_const_charp width,
    png_const_charp height)
1763 1764
{
   PNG_sCAL;
1765 1766
   png_byte buf[64];
   png_size_t wlen, hlen, total_len;
1767

1768
   png_debug(1, "in png_write_sCAL_s");
1769

1770 1771 1772
   wlen = png_strlen(width);
   hlen = png_strlen(height);
   total_len = wlen + hlen + 2;
1773

1774 1775 1776 1777 1778
   if (total_len > 64)
   {
      png_warning(png_ptr, "Can't write sCAL (buffer too small)");
      return;
   }
1779

1780
   buf[0] = (png_byte)unit;
1781 1782
   png_memcpy(buf + 1, width, wlen + 1);      /* Append the '\0' here */
   png_memcpy(buf + wlen + 2, height, hlen);  /* Do NOT append the '\0' here */
1783

1784
   png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);
1785
   png_write_chunk(png_ptr, png_sCAL, buf, total_len);
1786 1787 1788
}
#endif

1789
#ifdef PNG_WRITE_pHYs_SUPPORTED
1790
/* Write the pHYs chunk */
1791
void /* PRIVATE */
A
Andreas Dilger 已提交
1792
png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
1793 1794
    png_uint_32 y_pixels_per_unit,
    int unit_type)
G
Guy Schalnat 已提交
1795
{
1796
   PNG_pHYs;
G
Guy Schalnat 已提交
1797 1798
   png_byte buf[9];

1799
   png_debug(1, "in png_write_pHYs");
1800

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

A
Andreas Dilger 已提交
1804 1805
   png_save_uint_32(buf, x_pixels_per_unit);
   png_save_uint_32(buf + 4, y_pixels_per_unit);
G
Guy Schalnat 已提交
1806
   buf[8] = (png_byte)unit_type;
G
Guy Schalnat 已提交
1807

1808
   png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
G
Guy Schalnat 已提交
1809
}
G
Guy Schalnat 已提交
1810
#endif
G
Guy Schalnat 已提交
1811

1812
#ifdef PNG_WRITE_tIME_SUPPORTED
1813 1814 1815
/* Write the tIME chunk.  Use either png_convert_from_struct_tm()
 * or png_convert_from_time_t(), or fill in the structure yourself.
 */
1816
void /* PRIVATE */
1817
png_write_tIME(png_structp png_ptr, png_const_timep mod_time)
G
Guy Schalnat 已提交
1818
{
1819
   PNG_tIME;
G
Guy Schalnat 已提交
1820 1821
   png_byte buf[7];

1822
   png_debug(1, "in png_write_tIME");
1823

G
Guy Schalnat 已提交
1824 1825 1826 1827 1828 1829 1830 1831
   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 已提交
1832 1833 1834 1835 1836 1837 1838
   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;

1839
   png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
G
Guy Schalnat 已提交
1840
}
G
Guy Schalnat 已提交
1841
#endif
G
Guy Schalnat 已提交
1842

1843
/* Initializes the row writing capability of libpng */
1844
void /* PRIVATE */
G
Guy Schalnat 已提交
1845
png_write_start_row(png_structp png_ptr)
G
Guy Schalnat 已提交
1846
{
1847
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
1848
   /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1849

1850
   /* Start of interlace block */
1851
   int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
1852

1853
   /* Offset to next interlace block */
1854
   int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1855

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

1859
   /* Offset to next interlace block in the y direction */
1860
   int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
1861
#endif
1862

A
Andreas Dilger 已提交
1863 1864
   png_size_t buf_size;

1865
   png_debug(1, "in png_write_start_row");
1866

1867
   buf_size = (png_size_t)(PNG_ROWBYTES(
1868
       png_ptr->usr_channels*png_ptr->usr_bit_depth, png_ptr->width) + 1);
A
Andreas Dilger 已提交
1869

1870
   /* Set up row buffer */
1871
   png_ptr->row_buf = (png_bytep)png_malloc(png_ptr,
1872
       (png_alloc_size_t)buf_size);
1873

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

1876
#ifdef PNG_WRITE_FILTER_SUPPORTED
1877
   /* Set up filtering buffer, if using this filter */
G
Guy Schalnat 已提交
1878
   if (png_ptr->do_filter & PNG_FILTER_SUB)
G
Guy Schalnat 已提交
1879
   {
1880
      png_ptr->sub_row = (png_bytep)png_malloc(png_ptr, png_ptr->rowbytes + 1);
1881

A
Andreas Dilger 已提交
1882
      png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
G
Guy Schalnat 已提交
1883 1884
   }

A
Andreas Dilger 已提交
1885
   /* We only need to keep the previous row if we are using one of these. */
G
Guy Schalnat 已提交
1886 1887
   if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
   {
1888 1889
      /* Set up previous row buffer */
      png_ptr->prev_row = (png_bytep)png_calloc(png_ptr,
1890
          (png_alloc_size_t)buf_size);
G
Guy Schalnat 已提交
1891 1892 1893

      if (png_ptr->do_filter & PNG_FILTER_UP)
      {
1894
         png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
1895
            png_ptr->rowbytes + 1);
1896

A
Andreas Dilger 已提交
1897
         png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
G
Guy Schalnat 已提交
1898 1899 1900 1901
      }

      if (png_ptr->do_filter & PNG_FILTER_AVG)
      {
1902
         png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
1903
             png_ptr->rowbytes + 1);
1904

A
Andreas Dilger 已提交
1905
         png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
G
Guy Schalnat 已提交
1906 1907 1908 1909
      }

      if (png_ptr->do_filter & PNG_FILTER_PAETH)
      {
1910
         png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
1911
             png_ptr->rowbytes + 1);
1912

A
Andreas Dilger 已提交
1913
         png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
G
Guy Schalnat 已提交
1914
      }
G
Guy Schalnat 已提交
1915
   }
1916
#endif /* PNG_WRITE_FILTER_SUPPORTED */
G
Guy Schalnat 已提交
1917

1918
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
1919
   /* If interlaced, we need to set up width and height of pass */
G
Guy Schalnat 已提交
1920
   if (png_ptr->interlaced)
G
Guy Schalnat 已提交
1921 1922 1923 1924
   {
      if (!(png_ptr->transformations & PNG_INTERLACE))
      {
         png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
1925
             png_pass_ystart[0]) / png_pass_yinc[0];
1926

A
Andreas Dilger 已提交
1927
         png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
1928
             png_pass_start[0]) / png_pass_inc[0];
G
Guy Schalnat 已提交
1929
      }
1930

G
Guy Schalnat 已提交
1931 1932 1933 1934 1935 1936
      else
      {
         png_ptr->num_rows = png_ptr->height;
         png_ptr->usr_width = png_ptr->width;
      }
   }
1937

G
Guy Schalnat 已提交
1938
   else
1939
#endif
G
Guy Schalnat 已提交
1940
   {
G
Guy Schalnat 已提交
1941 1942 1943
      png_ptr->num_rows = png_ptr->height;
      png_ptr->usr_width = png_ptr->width;
   }
1944

A
Andreas Dilger 已提交
1945 1946
   png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
   png_ptr->zstream.next_out = png_ptr->zbuf;
G
Guy Schalnat 已提交
1947 1948
}

A
Andreas Dilger 已提交
1949
/* Internal use only.  Called when finished processing a row of data. */
1950
void /* PRIVATE */
G
Guy Schalnat 已提交
1951
png_write_finish_row(png_structp png_ptr)
G
Guy Schalnat 已提交
1952
{
1953
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
1954
   /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
1955

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

1959
   /* Offset to next interlace block */
1960
   int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
1961

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

1965
   /* Offset to next interlace block in the y direction */
1966
   int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
1967
#endif
1968

G
Guy Schalnat 已提交
1969 1970
   int ret;

1971
   png_debug(1, "in png_write_finish_row");
1972

1973
   /* Next row */
G
Guy Schalnat 已提交
1974
   png_ptr->row_number++;
G
Guy Schalnat 已提交
1975

1976
   /* See if we are done */
G
Guy Schalnat 已提交
1977
   if (png_ptr->row_number < png_ptr->num_rows)
G
Guy Schalnat 已提交
1978
      return;
G
Guy Schalnat 已提交
1979

1980
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
1981
   /* If interlaced, go to next pass */
G
Guy Schalnat 已提交
1982 1983 1984 1985 1986 1987 1988
   if (png_ptr->interlaced)
   {
      png_ptr->row_number = 0;
      if (png_ptr->transformations & PNG_INTERLACE)
      {
         png_ptr->pass++;
      }
1989

G
Guy Schalnat 已提交
1990 1991
      else
      {
1992
         /* Loop until we find a non-zero width or height pass */
G
Guy Schalnat 已提交
1993 1994 1995
         do
         {
            png_ptr->pass++;
1996

G
Guy Schalnat 已提交
1997 1998
            if (png_ptr->pass >= 7)
               break;
1999

G
Guy Schalnat 已提交
2000
            png_ptr->usr_width = (png_ptr->width +
2001 2002 2003
                png_pass_inc[png_ptr->pass] - 1 -
                png_pass_start[png_ptr->pass]) /
                png_pass_inc[png_ptr->pass];
2004

G
Guy Schalnat 已提交
2005
            png_ptr->num_rows = (png_ptr->height +
2006 2007 2008
                png_pass_yinc[png_ptr->pass] - 1 -
                png_pass_ystart[png_ptr->pass]) /
                png_pass_yinc[png_ptr->pass];
2009

G
Guy Schalnat 已提交
2010 2011
            if (png_ptr->transformations & PNG_INTERLACE)
               break;
2012

G
Guy Schalnat 已提交
2013 2014 2015 2016
         } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);

      }

2017
      /* Reset the row above the image for the next pass */
G
Guy Schalnat 已提交
2018
      if (png_ptr->pass < 7)
G
Guy Schalnat 已提交
2019
      {
A
Andreas Dilger 已提交
2020
         if (png_ptr->prev_row != NULL)
2021
            png_memset(png_ptr->prev_row, 0,
2022 2023
                (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
                png_ptr->usr_bit_depth, png_ptr->width)) + 1);
2024

G
Guy Schalnat 已提交
2025
         return;
G
Guy Schalnat 已提交
2026
      }
G
Guy Schalnat 已提交
2027
   }
2028
#endif
G
Guy Schalnat 已提交
2029

2030
   /* If we get here, we've just written the last row, so we need
G
Guy Schalnat 已提交
2031 2032 2033
      to flush the compressor */
   do
   {
2034
      /* Tell the compressor we are done */
A
Andreas Dilger 已提交
2035
      ret = deflate(&png_ptr->zstream, Z_FINISH);
2036

2037
      /* Check for an error */
2038 2039
      if (ret == Z_OK)
      {
2040
         /* Check to see if we need more room */
2041 2042 2043 2044 2045 2046 2047
         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;
         }
      }
2048

2049
      else if (ret != Z_STREAM_END)
G
Guy Schalnat 已提交
2050
      {
A
Andreas Dilger 已提交
2051
         if (png_ptr->zstream.msg != NULL)
A
Andreas Dilger 已提交
2052
            png_error(png_ptr, png_ptr->zstream.msg);
2053

G
Guy Schalnat 已提交
2054
         else
G
Guy Schalnat 已提交
2055
            png_error(png_ptr, "zlib error");
G
Guy Schalnat 已提交
2056 2057 2058
      }
   } while (ret != Z_STREAM_END);

2059
   /* Write any extra space */
A
Andreas Dilger 已提交
2060
   if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
G
Guy Schalnat 已提交
2061 2062
   {
      png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
2063
          png_ptr->zstream.avail_out);
G
Guy Schalnat 已提交
2064 2065
   }

A
Andreas Dilger 已提交
2066
   deflateReset(&png_ptr->zstream);
2067
   png_ptr->zstream.data_type = Z_BINARY;
G
Guy Schalnat 已提交
2068 2069
}

2070
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
2071 2072 2073 2074 2075 2076 2077
/* 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.
 */
2078
void /* PRIVATE */
G
Guy Schalnat 已提交
2079
png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
G
Guy Schalnat 已提交
2080
{
2081
   /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
2082

2083
   /* Start of interlace block */
2084
   int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
2085

2086
   /* Offset to next interlace block */
2087
   int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
2088

2089
   png_debug(1, "in png_do_write_interlace");
2090

2091
   /* We don't have to do anything on the last pass (6) */
A
Andreas Dilger 已提交
2092
   if (pass < 6)
G
Guy Schalnat 已提交
2093
   {
2094
      /* Each pixel depth is handled separately */
G
Guy Schalnat 已提交
2095
      switch (row_info->pixel_depth)
G
Guy Schalnat 已提交
2096
      {
G
Guy Schalnat 已提交
2097 2098
         case 1:
         {
G
Guy Schalnat 已提交
2099 2100
            png_bytep sp;
            png_bytep dp;
G
Guy Schalnat 已提交
2101 2102 2103
            int shift;
            int d;
            int value;
2104 2105
            png_uint_32 i;
            png_uint_32 row_width = row_info->width;
G
Guy Schalnat 已提交
2106 2107 2108 2109

            dp = row;
            d = 0;
            shift = 7;
2110

2111
            for (i = png_pass_start[pass]; i < row_width;
G
Guy Schalnat 已提交
2112 2113 2114
               i += png_pass_inc[pass])
            {
               sp = row + (png_size_t)(i >> 3);
2115
               value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
G
Guy Schalnat 已提交
2116 2117 2118 2119 2120
               d |= (value << shift);

               if (shift == 0)
               {
                  shift = 7;
G
Guy Schalnat 已提交
2121
                  *dp++ = (png_byte)d;
G
Guy Schalnat 已提交
2122 2123
                  d = 0;
               }
2124

G
Guy Schalnat 已提交
2125 2126 2127 2128 2129
               else
                  shift--;

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

G
Guy Schalnat 已提交
2132 2133
            break;
         }
2134

G
Guy Schalnat 已提交
2135
         case 2:
G
Guy Schalnat 已提交
2136
         {
G
Guy Schalnat 已提交
2137 2138
            png_bytep sp;
            png_bytep dp;
G
Guy Schalnat 已提交
2139 2140 2141
            int shift;
            int d;
            int value;
2142 2143
            png_uint_32 i;
            png_uint_32 row_width = row_info->width;
G
Guy Schalnat 已提交
2144 2145 2146 2147

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

2149
            for (i = png_pass_start[pass]; i < row_width;
G
Guy Schalnat 已提交
2150 2151 2152
               i += png_pass_inc[pass])
            {
               sp = row + (png_size_t)(i >> 2);
2153
               value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
G
Guy Schalnat 已提交
2154 2155 2156 2157 2158
               d |= (value << shift);

               if (shift == 0)
               {
                  shift = 6;
G
Guy Schalnat 已提交
2159
                  *dp++ = (png_byte)d;
G
Guy Schalnat 已提交
2160 2161
                  d = 0;
               }
2162

G
Guy Schalnat 已提交
2163 2164 2165 2166
               else
                  shift -= 2;
            }
            if (shift != 6)
2167 2168
               *dp = (png_byte)d;

G
Guy Schalnat 已提交
2169 2170
            break;
         }
2171

G
Guy Schalnat 已提交
2172 2173
         case 4:
         {
G
Guy Schalnat 已提交
2174 2175
            png_bytep sp;
            png_bytep dp;
G
Guy Schalnat 已提交
2176
            int shift;
G
Guy Schalnat 已提交
2177 2178
            int d;
            int value;
2179 2180
            png_uint_32 i;
            png_uint_32 row_width = row_info->width;
G
Guy Schalnat 已提交
2181 2182 2183 2184

            dp = row;
            shift = 4;
            d = 0;
2185
            for (i = png_pass_start[pass]; i < row_width;
2186
                i += png_pass_inc[pass])
G
Guy Schalnat 已提交
2187 2188
            {
               sp = row + (png_size_t)(i >> 1);
2189
               value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
G
Guy Schalnat 已提交
2190 2191 2192 2193
               d |= (value << shift);

               if (shift == 0)
               {
G
Guy Schalnat 已提交
2194 2195
                  shift = 4;
                  *dp++ = (png_byte)d;
G
Guy Schalnat 已提交
2196 2197
                  d = 0;
               }
2198

G
Guy Schalnat 已提交
2199 2200 2201 2202
               else
                  shift -= 4;
            }
            if (shift != 4)
G
Guy Schalnat 已提交
2203
               *dp = (png_byte)d;
2204

G
Guy Schalnat 已提交
2205 2206
            break;
         }
2207

G
Guy Schalnat 已提交
2208 2209
         default:
         {
G
Guy Schalnat 已提交
2210 2211
            png_bytep sp;
            png_bytep dp;
2212 2213
            png_uint_32 i;
            png_uint_32 row_width = row_info->width;
A
Andreas Dilger 已提交
2214
            png_size_t pixel_bytes;
G
Guy Schalnat 已提交
2215

2216
            /* Start at the beginning */
G
Guy Schalnat 已提交
2217
            dp = row;
2218

2219
            /* Find out how many bytes each pixel takes up */
G
Guy Schalnat 已提交
2220
            pixel_bytes = (row_info->pixel_depth >> 3);
2221 2222

            /* Loop through the row, only looking at the pixels that matter */
2223
            for (i = png_pass_start[pass]; i < row_width;
G
Guy Schalnat 已提交
2224 2225
               i += png_pass_inc[pass])
            {
2226
               /* Find out where the original pixel is */
2227
               sp = row + (png_size_t)i * pixel_bytes;
2228

2229
               /* Move the pixel */
G
Guy Schalnat 已提交
2230
               if (dp != sp)
G
Guy Schalnat 已提交
2231
                  png_memcpy(dp, sp, pixel_bytes);
2232

2233
               /* Next pixel */
G
Guy Schalnat 已提交
2234 2235
               dp += pixel_bytes;
            }
G
Guy Schalnat 已提交
2236
            break;
G
Guy Schalnat 已提交
2237 2238
         }
      }
2239
      /* Set new row width */
G
Guy Schalnat 已提交
2240
      row_info->width = (row_info->width +
2241 2242 2243
          png_pass_inc[pass] - 1 -
          png_pass_start[pass]) /
          png_pass_inc[pass];
2244

2245 2246
      row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
          row_info->width);
G
Guy Schalnat 已提交
2247 2248
   }
}
G
Guy Schalnat 已提交
2249
#endif
G
Guy Schalnat 已提交
2250

A
Andreas Dilger 已提交
2251 2252
/* 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
2253 2254
 * chosen filter.
 */
2255
#define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
A
Andreas Dilger 已提交
2256
#define PNG_HISHIFT 10
2257 2258
#define PNG_LOMASK ((png_uint_32)0xffffL)
#define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
2259
void /* PRIVATE */
G
Guy Schalnat 已提交
2260
png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
G
Guy Schalnat 已提交
2261
{
2262
   png_bytep best_row;
2263
#ifdef PNG_WRITE_FILTER_SUPPORTED
2264
   png_bytep prev_row, row_buf;
A
Andreas Dilger 已提交
2265
   png_uint_32 mins, bpp;
2266
   png_byte filter_to_do = png_ptr->do_filter;
2267
   png_size_t row_bytes = row_info->rowbytes;
2268
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2269
   int num_p_filters = (int)png_ptr->num_prev_filters;
2270
#endif
2271 2272 2273 2274

   png_debug(1, "in png_write_find_filter");

#ifndef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2275
  if (png_ptr->row_number == 0 && filter_to_do == PNG_ALL_FILTERS)
2276
  {
2277 2278
     /* These will never be selected so we need not test them. */
     filter_to_do &= ~(PNG_FILTER_UP | PNG_FILTER_PAETH);
2279
  }
2280
#endif
G
Guy Schalnat 已提交
2281

2282
   /* Find out how many bytes offset each pixel is */
2283
   bpp = (row_info->pixel_depth + 7) >> 3;
G
Guy Schalnat 已提交
2284 2285

   prev_row = png_ptr->prev_row;
2286 2287
#endif
   best_row = png_ptr->row_buf;
2288
#ifdef PNG_WRITE_FILTER_SUPPORTED
2289
   row_buf = best_row;
A
Andreas Dilger 已提交
2290 2291 2292 2293
   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
2294
    * from zero, using anything >= 128 as negative numbers.  This is known
A
Andreas Dilger 已提交
2295
    * as the "minimum sum of absolute differences" heuristic.  Other
2296
    * heuristics are the "weighted minimum sum of absolute differences"
A
Andreas Dilger 已提交
2297
    * (experimental and can in theory improve compression), and the "zlib
2298 2299 2300
    * 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 已提交
2301
    * computationally expensive).
2302 2303
    *
    * GRR 980525:  consider also
2304
    *
2305 2306 2307
    *   (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?]
2308
    *
2309 2310
    *  (1b) minimum sum of absolute differences from sliding average, probably
    *       with window size <= deflate window (usually 32K)
2311
    *
2312 2313
    *   (2) minimum sum of squared differences from zero or running average
    *       (i.e., ~ root-mean-square approach)
A
Andreas Dilger 已提交
2314
    */
G
Guy Schalnat 已提交
2315

2316

G
Guy Schalnat 已提交
2317
   /* We don't need to test the 'no filter' case if this is the only filter
A
Andreas Dilger 已提交
2318 2319
    * that has been chosen, as it doesn't actually do anything to the data.
    */
2320
   if ((filter_to_do & PNG_FILTER_NONE) && filter_to_do != PNG_FILTER_NONE)
G
Guy Schalnat 已提交
2321
   {
G
Guy Schalnat 已提交
2322 2323
      png_bytep rp;
      png_uint_32 sum = 0;
2324
      png_size_t i;
A
Andreas Dilger 已提交
2325
      int v;
G
Guy Schalnat 已提交
2326

2327
      for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
G
Guy Schalnat 已提交
2328 2329 2330 2331
      {
         v = *rp;
         sum += (v < 128) ? v : 256 - v;
      }
A
Andreas Dilger 已提交
2332

2333
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2334 2335 2336
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
         png_uint_32 sumhi, sumlo;
2337
         int j;
A
Andreas Dilger 已提交
2338 2339 2340 2341
         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 */
2342
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2343
         {
2344
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
A
Andreas Dilger 已提交
2345
            {
2346
               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2347
                   PNG_WEIGHT_SHIFT;
2348

2349
               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2350
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2351 2352 2353 2354 2355 2356 2357 2358
            }
         }

         /* 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]) >>
2359
             PNG_COST_SHIFT;
2360

A
Andreas Dilger 已提交
2361
         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
2362
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2363 2364 2365

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2366

A
Andreas Dilger 已提交
2367 2368 2369 2370
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
      }
#endif
G
Guy Schalnat 已提交
2371 2372
      mins = sum;
   }
G
Guy Schalnat 已提交
2373

2374
   /* Sub filter */
2375
   if (filter_to_do == PNG_FILTER_SUB)
2376
   /* It's the only filter so no testing is needed */
2377 2378
   {
      png_bytep rp, lp, dp;
2379
      png_size_t i;
2380

2381 2382 2383 2384 2385
      for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
           i++, rp++, dp++)
      {
         *dp = *rp;
      }
2386

2387
      for (lp = row_buf + 1; i < row_bytes;
2388 2389 2390 2391
         i++, rp++, lp++, dp++)
      {
         *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
      }
2392

2393 2394 2395 2396
      best_row = png_ptr->sub_row;
   }

   else if (filter_to_do & PNG_FILTER_SUB)
G
Guy Schalnat 已提交
2397 2398
   {
      png_bytep rp, dp, lp;
A
Andreas Dilger 已提交
2399
      png_uint_32 sum = 0, lmins = mins;
2400
      png_size_t i;
A
Andreas Dilger 已提交
2401 2402
      int v;

2403
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
2404
      /* We temporarily increase the "minimum sum" by the factor we
A
Andreas Dilger 已提交
2405 2406 2407 2408 2409
       * 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)
      {
2410
         int j;
A
Andreas Dilger 已提交
2411 2412 2413 2414
         png_uint_32 lmhi, lmlo;
         lmlo = lmins & PNG_LOMASK;
         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;

2415
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2416
         {
2417
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
A
Andreas Dilger 已提交
2418
            {
2419
               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2420
                   PNG_WEIGHT_SHIFT;
2421

2422
               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2423
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2424 2425 2426 2427
            }
         }

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

A
Andreas Dilger 已提交
2430
         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2431
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2432 2433 2434

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
2435

A
Andreas Dilger 已提交
2436 2437 2438 2439
         else
            lmins = (lmhi << PNG_HISHIFT) + lmlo;
      }
#endif
G
Guy Schalnat 已提交
2440

G
Guy Schalnat 已提交
2441 2442 2443 2444
      for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
           i++, rp++, dp++)
      {
         v = *dp = *rp;
G
Guy Schalnat 已提交
2445

G
Guy Schalnat 已提交
2446 2447
         sum += (v < 128) ? v : 256 - v;
      }
2448

2449
      for (lp = row_buf + 1; i < row_bytes;
2450
         i++, rp++, lp++, dp++)
G
Guy Schalnat 已提交
2451 2452 2453 2454
      {
         v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);

         sum += (v < 128) ? v : 256 - v;
A
Andreas Dilger 已提交
2455 2456 2457 2458 2459

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

2460
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2461 2462
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2463
         int j;
A
Andreas Dilger 已提交
2464 2465 2466 2467
         png_uint_32 sumhi, sumlo;
         sumlo = sum & PNG_LOMASK;
         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;

2468
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2469
         {
2470
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
A
Andreas Dilger 已提交
2471
            {
2472
               sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
2473
                   PNG_WEIGHT_SHIFT;
2474

2475
               sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
2476
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2477 2478 2479 2480
            }
         }

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

A
Andreas Dilger 已提交
2483
         sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
2484
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2485 2486 2487

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2488

A
Andreas Dilger 已提交
2489 2490
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
G
Guy Schalnat 已提交
2491
      }
A
Andreas Dilger 已提交
2492 2493
#endif

G
Guy Schalnat 已提交
2494 2495 2496 2497 2498
      if (sum < mins)
      {
         mins = sum;
         best_row = png_ptr->sub_row;
      }
G
Guy Schalnat 已提交
2499 2500
   }

2501
   /* Up filter */
2502 2503 2504
   if (filter_to_do == PNG_FILTER_UP)
   {
      png_bytep rp, dp, pp;
2505
      png_size_t i;
2506 2507

      for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
2508 2509
          pp = prev_row + 1; i < row_bytes;
          i++, rp++, pp++, dp++)
2510 2511 2512
      {
         *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
      }
2513

2514 2515 2516 2517
      best_row = png_ptr->up_row;
   }

   else if (filter_to_do & PNG_FILTER_UP)
G
Guy Schalnat 已提交
2518 2519
   {
      png_bytep rp, dp, pp;
A
Andreas Dilger 已提交
2520
      png_uint_32 sum = 0, lmins = mins;
2521
      png_size_t i;
A
Andreas Dilger 已提交
2522 2523
      int v;

2524

2525
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2526 2527
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2528
         int j;
A
Andreas Dilger 已提交
2529 2530 2531 2532
         png_uint_32 lmhi, lmlo;
         lmlo = lmins & PNG_LOMASK;
         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;

2533
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2534
         {
2535
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
A
Andreas Dilger 已提交
2536
            {
2537
               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2538
                   PNG_WEIGHT_SHIFT;
2539

2540
               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2541
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2542 2543 2544 2545
            }
         }

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

A
Andreas Dilger 已提交
2548
         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
2549
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2550 2551 2552

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
2553

A
Andreas Dilger 已提交
2554 2555 2556 2557
         else
            lmins = (lmhi << PNG_HISHIFT) + lmlo;
      }
#endif
G
Guy Schalnat 已提交
2558

G
Guy Schalnat 已提交
2559
      for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
2560
          pp = prev_row + 1; i < row_bytes; i++)
G
Guy Schalnat 已提交
2561
      {
2562
         v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
G
Guy Schalnat 已提交
2563 2564

         sum += (v < 128) ? v : 256 - v;
A
Andreas Dilger 已提交
2565 2566 2567

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

2570
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2571 2572
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2573
         int j;
A
Andreas Dilger 已提交
2574 2575 2576 2577
         png_uint_32 sumhi, sumlo;
         sumlo = sum & PNG_LOMASK;
         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;

2578
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2579
         {
2580
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
A
Andreas Dilger 已提交
2581
            {
2582
               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2583
                   PNG_WEIGHT_SHIFT;
2584

2585
               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2586
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2587 2588 2589 2590
            }
         }

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

A
Andreas Dilger 已提交
2593
         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
2594
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2595 2596 2597

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2598

A
Andreas Dilger 已提交
2599 2600 2601 2602 2603
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
      }
#endif

G
Guy Schalnat 已提交
2604 2605 2606 2607 2608 2609 2610
      if (sum < mins)
      {
         mins = sum;
         best_row = png_ptr->up_row;
      }
   }

2611
   /* Avg filter */
2612 2613 2614
   if (filter_to_do == PNG_FILTER_AVG)
   {
      png_bytep rp, dp, pp, lp;
2615
      png_uint_32 i;
2616

2617
      for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
2618
           pp = prev_row + 1; i < bpp; i++)
2619
      {
2620
         *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
2621
      }
2622

2623
      for (lp = row_buf + 1; i < row_bytes; i++)
2624
      {
2625 2626
         *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
                 & 0xff);
2627 2628 2629 2630 2631
      }
      best_row = png_ptr->avg_row;
   }

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

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

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

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

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

A
Andreas Dilger 已提交
2661
         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
2662
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2663 2664 2665

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
2666

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

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

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

2680
      for (lp = row_buf + 1; i < row_bytes; i++)
G
Guy Schalnat 已提交
2681
      {
2682
         v = *dp++ =
2683
             (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
G
Guy Schalnat 已提交
2684

G
Guy Schalnat 已提交
2685
         sum += (v < 128) ? v : 256 - v;
A
Andreas Dilger 已提交
2686 2687 2688

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

2691
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2692 2693
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2694
         int j;
A
Andreas Dilger 已提交
2695 2696 2697 2698
         png_uint_32 sumhi, sumlo;
         sumlo = sum & PNG_LOMASK;
         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;

2699
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2700
         {
2701
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
A
Andreas Dilger 已提交
2702
            {
2703
               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2704
                   PNG_WEIGHT_SHIFT;
2705

2706
               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2707
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2708 2709 2710 2711
            }
         }

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

A
Andreas Dilger 已提交
2714
         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
2715
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2716 2717 2718

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2719

A
Andreas Dilger 已提交
2720 2721 2722 2723 2724
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
      }
#endif

G
Guy Schalnat 已提交
2725 2726 2727 2728 2729 2730
      if (sum < mins)
      {
         mins = sum;
         best_row = png_ptr->avg_row;
      }
   }
G
Guy Schalnat 已提交
2731

A
Andreas Dilger 已提交
2732
   /* Paeth filter */
2733 2734 2735
   if (filter_to_do == PNG_FILTER_PAETH)
   {
      png_bytep rp, dp, pp, cp, lp;
2736
      png_size_t i;
2737

2738
      for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
2739
          pp = prev_row + 1; i < bpp; i++)
2740
      {
2741
         *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
2742 2743
      }

2744
      for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
2745 2746 2747
      {
         int a, b, c, pa, pb, pc, p;

2748 2749 2750
         b = *pp++;
         c = *cp++;
         a = *lp++;
2751

2752 2753
         p = b - c;
         pc = a - c;
2754 2755

#ifdef PNG_USE_ABS
2756 2757 2758
         pa = abs(p);
         pb = abs(pc);
         pc = abs(p + pc);
2759
#else
2760 2761 2762
         pa = p < 0 ? -p : p;
         pb = pc < 0 ? -pc : pc;
         pc = (p + pc) < 0 ? -(p + pc) : p + pc;
2763 2764 2765 2766
#endif

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

2767
         *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
2768 2769 2770 2771 2772
      }
      best_row = png_ptr->paeth_row;
   }

   else if (filter_to_do & PNG_FILTER_PAETH)
G
Guy Schalnat 已提交
2773 2774
   {
      png_bytep rp, dp, pp, cp, lp;
A
Andreas Dilger 已提交
2775
      png_uint_32 sum = 0, lmins = mins;
2776
      png_size_t i;
A
Andreas Dilger 已提交
2777 2778
      int v;

2779
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2780 2781
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2782
         int j;
A
Andreas Dilger 已提交
2783 2784 2785 2786
         png_uint_32 lmhi, lmlo;
         lmlo = lmins & PNG_LOMASK;
         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;

2787
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2788
         {
2789
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
A
Andreas Dilger 已提交
2790
            {
2791
               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
2792
                   PNG_WEIGHT_SHIFT;
2793

2794
               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
2795
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2796 2797 2798 2799
            }
         }

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

A
Andreas Dilger 已提交
2802
         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2803
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2804 2805 2806

         if (lmhi > PNG_HIMASK)
            lmins = PNG_MAXSUM;
2807

A
Andreas Dilger 已提交
2808 2809 2810 2811
         else
            lmins = (lmhi << PNG_HISHIFT) + lmlo;
      }
#endif
G
Guy Schalnat 已提交
2812

G
Guy Schalnat 已提交
2813
      for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
2814
          pp = prev_row + 1; i < bpp; i++)
G
Guy Schalnat 已提交
2815
      {
2816
         v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
G
Guy Schalnat 已提交
2817

G
Guy Schalnat 已提交
2818 2819
         sum += (v < 128) ? v : 256 - v;
      }
2820

2821
      for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
G
Guy Schalnat 已提交
2822 2823
      {
         int a, b, c, pa, pb, pc, p;
G
Guy Schalnat 已提交
2824

2825 2826 2827
         b = *pp++;
         c = *cp++;
         a = *lp++;
2828 2829

#ifndef PNG_SLOW_PAETH
2830 2831
         p = b - c;
         pc = a - c;
2832
#ifdef PNG_USE_ABS
2833 2834 2835
         pa = abs(p);
         pb = abs(pc);
         pc = abs(p + pc);
2836
#else
2837 2838 2839
         pa = p < 0 ? -p : p;
         pb = pc < 0 ? -pc : pc;
         pc = (p + pc) < 0 ? -(p + pc) : p + pc;
2840 2841 2842
#endif
         p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
#else /* PNG_SLOW_PAETH */
2843
         p = a + b - c;
2844 2845 2846
         pa = abs(p - a);
         pb = abs(p - b);
         pc = abs(p - c);
2847

G
Guy Schalnat 已提交
2848 2849
         if (pa <= pb && pa <= pc)
            p = a;
2850

G
Guy Schalnat 已提交
2851 2852
         else if (pb <= pc)
            p = b;
2853

G
Guy Schalnat 已提交
2854 2855
         else
            p = c;
2856
#endif /* PNG_SLOW_PAETH */
G
Guy Schalnat 已提交
2857

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

G
Guy Schalnat 已提交
2860
         sum += (v < 128) ? v : 256 - v;
A
Andreas Dilger 已提交
2861 2862 2863

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

2866
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2867 2868
      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
      {
2869
         int j;
A
Andreas Dilger 已提交
2870 2871 2872 2873
         png_uint_32 sumhi, sumlo;
         sumlo = sum & PNG_LOMASK;
         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;

2874
         for (j = 0; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2875
         {
2876
            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
A
Andreas Dilger 已提交
2877
            {
2878
               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
2879
                   PNG_WEIGHT_SHIFT;
2880

2881
               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
2882
                   PNG_WEIGHT_SHIFT;
A
Andreas Dilger 已提交
2883 2884 2885 2886
            }
         }

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

A
Andreas Dilger 已提交
2889
         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
2890
             PNG_COST_SHIFT;
A
Andreas Dilger 已提交
2891 2892 2893

         if (sumhi > PNG_HIMASK)
            sum = PNG_MAXSUM;
2894

A
Andreas Dilger 已提交
2895 2896 2897 2898 2899
         else
            sum = (sumhi << PNG_HISHIFT) + sumlo;
      }
#endif

G
Guy Schalnat 已提交
2900 2901 2902 2903
      if (sum < mins)
      {
         best_row = png_ptr->paeth_row;
      }
G
Guy Schalnat 已提交
2904
   }
2905
#endif /* PNG_WRITE_FILTER_SUPPORTED */
A
Andreas Dilger 已提交
2906
   /* Do the actual writing of the filtered row data from the chosen filter. */
2907

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

2910
#ifdef PNG_WRITE_FILTER_SUPPORTED
2911
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
A
Andreas Dilger 已提交
2912 2913 2914
   /* Save the type of filter we picked this time for future calculations */
   if (png_ptr->num_prev_filters > 0)
   {
2915
      int j;
2916

2917
      for (j = 1; j < num_p_filters; j++)
A
Andreas Dilger 已提交
2918
      {
2919
         png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
A
Andreas Dilger 已提交
2920
      }
2921

2922
      png_ptr->prev_filters[j] = best_row[0];
A
Andreas Dilger 已提交
2923 2924
   }
#endif
2925
#endif /* PNG_WRITE_FILTER_SUPPORTED */
G
Guy Schalnat 已提交
2926
}
G
Guy Schalnat 已提交
2927

G
Guy Schalnat 已提交
2928

A
Andreas Dilger 已提交
2929
/* Do the actual writing of a previously filtered row. */
2930
void /* PRIVATE */
G
Guy Schalnat 已提交
2931 2932
png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
{
2933 2934
   png_size_t avail;

2935
   png_debug(1, "in png_write_filtered_row");
2936

2937
   png_debug1(2, "filter = %d", filtered_row[0]);
2938
   /* Set up the zlib input buffer */
2939

A
Andreas Dilger 已提交
2940
   png_ptr->zstream.next_in = filtered_row;
2941 2942
   png_ptr->zstream.avail_in = 0;
   avail = png_ptr->row_info.rowbytes + 1;
2943
   /* Repeat until we have compressed all the data */
G
Guy Schalnat 已提交
2944
   do
G
Guy Schalnat 已提交
2945
   {
2946
      int ret; /* Return of zlib */
G
Guy Schalnat 已提交
2947

2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971
      /* Record the number of bytes available - zlib supports at least 65535
       * bytes at one step, depending on the size of the zlib type 'uInt', the
       * maximum size zlib can write at once is ZLIB_IO_MAX (from pngpriv.h).
       * Use this because on 16 bit systems 'rowbytes' can be up to 65536 (i.e.
       * one more than 16 bits) and, in this case 'rowbytes+1' can overflow a
       * uInt.  ZLIB_IO_MAX can be safely reduced to cause zlib to be called
       * with smaller chunks of data.
       */
      if (png_ptr->zstream.avail_in == 0)
      {
         if (avail > ZLIB_IO_MAX)
         {
            png_ptr->zstream.avail_in  = ZLIB_IO_MAX;
            avail -= ZLIB_IO_MAX;
         }

         else
         {
            /* So this will fit in the available uInt space: */
            png_ptr->zstream.avail_in = (uInt)avail;
            avail = 0;
         }
      }

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

2975
      /* Check for compression errors */
G
Guy Schalnat 已提交
2976 2977
      if (ret != Z_OK)
      {
A
Andreas Dilger 已提交
2978
         if (png_ptr->zstream.msg != NULL)
A
Andreas Dilger 已提交
2979
            png_error(png_ptr, png_ptr->zstream.msg);
2980

G
Guy Schalnat 已提交
2981 2982 2983
         else
            png_error(png_ptr, "zlib error");
      }
G
Guy Schalnat 已提交
2984

2985
      /* See if it is time to write another IDAT */
A
Andreas Dilger 已提交
2986
      if (!(png_ptr->zstream.avail_out))
G
Guy Schalnat 已提交
2987
      {
2988
         /* Write the IDAT and reset the zlib output buffer */
G
Guy Schalnat 已提交
2989
         png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
A
Andreas Dilger 已提交
2990 2991
         png_ptr->zstream.next_out = png_ptr->zbuf;
         png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
G
Guy Schalnat 已提交
2992
      }
2993
   /* Repeat until all data has been compressed */
2994
   } while (avail > 0 || png_ptr->zstream.avail_in > 0);
G
Guy Schalnat 已提交
2995

2996
   /* Swap the current and previous rows */
A
Andreas Dilger 已提交
2997
   if (png_ptr->prev_row != NULL)
G
Guy Schalnat 已提交
2998 2999 3000 3001 3002 3003 3004 3005
   {
      png_bytep tptr;

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

3006
   /* Finish row - updates counters and flushes zlib if last row */
G
Guy Schalnat 已提交
3007
   png_write_finish_row(png_ptr);
G
Guy Schalnat 已提交
3008

3009
#ifdef PNG_WRITE_FLUSH_SUPPORTED
G
Guy Schalnat 已提交
3010 3011 3012 3013 3014 3015
   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 已提交
3016
   }
3017
#endif
G
Guy Schalnat 已提交
3018
}
3019
#endif /* PNG_WRITE_SUPPORTED */